pax_global_header00006660000000000000000000000064143376364250014527gustar00rootroot0000000000000052 comment=1b78dfa895499108263bd1de88a8ebb10fad9811 buteo-syncml-0.5.15/000077500000000000000000000000001433763642500142405ustar00rootroot00000000000000buteo-syncml-0.5.15/.gitignore000066400000000000000000000001131433763642500162230ustar00rootroot00000000000000Makefile *.list *.prl *.so* src/pkgconfig tests_meego/libbuteosyncml-tests buteo-syncml-0.5.15/Scripts/000077500000000000000000000000001433763642500156675ustar00rootroot00000000000000buteo-syncml-0.5.15/Scripts/tests2junit.xsl000066400000000000000000000052431433763642500207210ustar00rootroot00000000000000 Standard buteo-syncml-0.5.15/api.file000066400000000000000000000001731433763642500156530ustar00rootroot00000000000000interface: MeeGo syncML type: library scope: Platform state: unstable libs-pkg: libmeegosyncml dev-pkg: libmeegosyncml-dev buteo-syncml-0.5.15/build_project.sh000077500000000000000000000050521433763642500174260ustar00rootroot00000000000000#!/usr/bin/env sh #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ # todo add proper exit codes # This script is for executing (re)building the library from scratch # and running unit tests # To create the debian packages, use "dpkg-buildpackage" export PATH=/home/bamboo2/qt/qtsdk-2009.02/qt/bin:$PATH if [ -f Makefile ]; then make distclean fi rm -rf tests_meego/results qmake libmeegosyncml.pro # For single core envs, maybe remove -j2 make -j3 cd tests_meego export LD_LIBRARY_PATH=$PWD/../src/ if [ -d results ]; then rm -f results/* else mkdir results fi ./libmeegosyncml-tests -xml > results/tests.xml cd results # todo catch if the parsing fails # csplit -f test- tests.xml "/<\?xml version=\"1.0\" encoding=\"ISO-8859-1\"\?>/" '{*}' awk '/^<\?xml/{n++}{print > n "-split.xml" }' tests.xml # csplit -f test- tests.xml "/^ $i-junit.xml done buteo-syncml-0.5.15/debian/000077500000000000000000000000001433763642500154625ustar00rootroot00000000000000buteo-syncml-0.5.15/debian/api000066400000000000000000000001731433763642500161570ustar00rootroot00000000000000interface: MeeGo syncML type: library scope: Platform state: unstable libs-pkg: libmeegosyncml dev-pkg: libmeegosyncml-dev buteo-syncml-0.5.15/debian/changelog000066400000000000000000001004101433763642500173300ustar00rootroot00000000000000libmeegosyncml (0.4.18) stable; urgency=low * Fixes: NB#238013 - reduce amount of logging and logging impact in sync-fw -- Deepak Kodihalli Mon, 30 May 2011 11:50:48 +0530 libmeegosyncml (0.4.17) stable; urgency=low * Fixes: NB#260125 - Remote sync failed with device and sync doesn't end in transfer-ui -- Deepak Kodihalli Thu, 26 May 2011 17:27:00 +0530 libmeegosyncml (0.4.16) stable; urgency=low * Fixes: NB#258951 - msyncd crash when cancel the sync from transfer-ui -- Deepak Kodihalli Wed, 25 May 2011 11:09:12 +0530 libmeegosyncml (0.4.15) stable; urgency=low * Fixes: NB#254284 - defects from libmeegosyncml/0.4.14_0m6 . -- Amit Wed, 18 May 2011 18:11:00 +0300 libmeegosyncml (0.4.14) stable; urgency=low * Unit test cases updated. -- Santosh Puranik Mon, 02 May 2011 18:11:00 +0300 libmeegosyncml (0.4.13) stable; urgency=low * Check if tables exist before removing change logs and anchors. -- Santosh Puranik Wed, 06 Apr 2011 20:00:00 +0530 libmeegosyncml (0.4.12) stable; urgency=low * Fixes: NB#223952 - Not all the contacts are syncd from DUT to S60 * Adding changes to remove default configuration and abort sync to take parameter. -- Amit Thu, 03 Feb 2011 14:40:03 +0530 libmeegosyncml (0.4.11) stable; urgency=low * 1. Please try to use 3 digits for the version x.y.z - 0.0.1 * 2. When something significant happens (sprint, X-something review) increase second digit - 0.1.0 * 3. When something very significant happens (dali release, etc) increase first digit - 1.0.0 * 4. Whenever regular changes in the code are done (bugfixes, minor features implemented) please always increment the last digit - 0.0.2. -- Mallikarjun Hunalli Mon, 31 Jan 2011 18:00:00 +0530 libmeegosyncml (0.4.10-7) stable; urgency=low * Fixes - Removed the "silent" option set in CONFIG of a pro file -- Mallikarjun Hunalli Tue, 27 Jan 2011 18:00:00 +0530 libmeegosyncml (0.4.10-6) stable; urgency=low * Fixes: NB#201619 - Synchronization is stuck in the progress indicator screen when the internet is interrupted while sync. -- Amit Tue, 25 Jan 2011 18:00:00 +0530 libmeegosyncml (0.4.10-5) stable; urgency=low * Fixes - Bookmark sync support removed -- Mallikarjun Hunalli Thu, 20 Jan 2011 18:00:00 +0530 libmeegosyncml (0.4.10-4) stable; urgency=low * Fixes: NB#204328 - msyncd crashed while resyncing SMS after sync fails with S40(5310), remote initiated -- Amit Mon, 17 Jan 2011 10:00:00 +0200 libmeegosyncml (0.4.10-3) stable; urgency=low * Deleting the waiting bug. -- Amit Thu, 30 Dec 2010 16:25:00 +0530 libmeegosyncml (0.4.10-1) stable; urgency=low * Fixes: NB#212083 - Consecutive sync (after a successful sync) with ovi.com always fails. * Fixes: NB#212465 - Synchronization is stuck in the progress indicator screen when the internet is interrupted while sync. -- Amit Fri, 17 Dec 2010 16:25:00 +0530 libmeegosyncml (0.4.10-0) stable; urgency=low * Mark package as stable -- Santosh Puranik Mon, 13 Dec 2010 16:25:00 +0530 libmeegosyncml (0.4.9-52) unstable; urgency=low * Fixes: NB#208762 - All data sync from S40 fails. As problem with size for xml. Now using size calculation based on wbxml for ms size threshold. -- Amit Wed, 08 Dec 2010 15:14:00 +0530 libmeegosyncml (0.4.9-51) unstable; urgency=low * Fixes: NB#203771 Conflict set to N95:Calendar entry is deleted in N95 when modified a calendar entry in N95 and deleted the same in DUT -- Santosh Puranik Thu, 02 Dec 2010 15:14:00 +0530 libmeegosyncml (0.4.9-50) unstable; urgency=low * Fix tests.xml -- Santosh Puranik Wed, 01 Dec 2010 15:14:00 +0530 libmeegosyncml (0.4.9-49) unstable; urgency=low * Support both DS and DM content types in transports. -- Duggirala Karthik Tue, 30 Nov 2010 18:30:00 +0530 libmeegosyncml (0.4.9-48) unstable; urgency=low * Fixes: NB#206970 - After synchronising contacts, incorrect number of contacts synced is reported. -- Santosh Puranik Wed, 24 Nov 2010 18:30:00 +0530 libmeegosyncml (0.4.9-47) unstable; urgency=low * Support DMDDF wbxml codepage -- Duggirala Karthik Wed, 24 Nov 2010 15:15:00 +0530 libmeegosyncml (0.4.9-46) unstable; urgency=low * Fixes: NB#176179 - Contacts not copied to device during sync. Added a check for packages to be sent before we dtermine whether the data update status package can be sent. * Added Ext parameter support for Storage plugins. -- Santosh Puranik Mon, 15 Nov 2010 15:15:00 +0530 libmeegosyncml (0.4.9-45) unstable; urgency=low * Fixes: NB#176179 - Contacts not copied to device during sync. -- Santosh Puranik Wed, 10 Nov 2010 20:00:00 +0530 libmeegosyncml (0.4.9-44) unstable; urgency=low * Fixes: NB#198594 - ovi.com contact sync fails with Invalid syncML message. -- Santosh Puranik Thu, 04 Nov 2010 15:00:00 +0530 libmeegosyncml (0.4.9-43) unstable; urgency=low * Fixes: NB#180964 - SMS messages synced from N95 all have today's time stamp -- Santosh Puranik Fri, 20 Oct 2010 20:45:32 +0530 libmeegosyncml (0.4.9-42) unstable; urgency=low * Fixes: NB#196459 - Memory leaks when one Note is synced from S60 to Dali. * Fixes: NB#198456 - Modified contact with avatar in S60 (N95) is duplicated in device after resync from device. -- Amit Thu, 18 Oct 2010 15:16:32 +0530 libmeegosyncml (0.4.9-41) unstable; urgency=low * Fixed a couple of issues seen with google sync - not handling percent encoded respURIs and not updating target LocURIs with the respURIs. -- Deepak Kodihalli Thu, 14 Oct 2010 15:16:32 +0530 libmeegosyncml (0.4.9-40) unstable; urgency=low * Refactoring to make handling of SyncML protocol more generic * Fixes to MD5 authentication * Graceful handling of unsupported commands -- Amit Wed, 13 Oct 2010 14:00:00 +0300 libmeegosyncml (0.4.9-39) unstable; urgency=low * Fixes: NB#194061 - Sync always fails for calendar only data with S40 (6500). -- Amit Tue, 12 Oct 2010 18:20:00 +0330 libmeegosyncml (0.4.9-38) unstable; urgency=low * NB#197079 - Existing data in N900 is not transferred to device after reflashing the device. -- Santosh Puranik Sat, 09 Oct 2010 18:20:00 +0330 libmeegosyncml (0.4.9-37) unstable; urgency=low * Tests deb pkg dependency changes to testrunner->testrunner-line -- Duggirala Karthik Thu, 07 Oct 2010 17:16:14 +0330 libmeegosyncml (0.4.9-36) unstable; urgency=low * Fixes: NB#195583 Some data not copied message dislayed for any/all data when sync initiated from S60 to device -- Duggirala Karthik Mon, 04 Oct 2010 09:00:00 +0300 libmeegosyncml (0.4.9-35) unstable; urgency=low * Parsing of device information sent by remote device * Delayed loading of storage plugins in D2D sync -- Deepak Kodihalli Tue, 21 Sep 2010 09:00:00 +0300 libmeegosyncml (0.4.9-34) unstable; urgency=low * Fixed installation of default conf file -- Deepak Kodihalli Mon, 20 Sep 2010 14:30:00 +0300 libmeegosyncml (0.4.9-33) unstable; urgency=low * Disabled schema-based validation of conf file -- Deepak Kodihalli Thu, 16 Sep 2010 16:30:00 +0300 libmeegosyncml (0.4.9-32) unstable; urgency=low * Implemented item data prefetching on idle time * Added more configuration parameters -- Deepak Kodihalli Wed, 15 Sep 2010 15:00:00 +0300 libmeegosyncml (0.4.9-31) unstable; urgency=low * OBEX connectivity updates -- Deepak Kodihalli Mon, 6 Sep 2010 16:30:00 +0300 libmeegosyncml (0.4.9-30) unstable; urgency=low * Fixes: NB#188615 - Characters with codes above U+00FF get corrupted during sync -- Deepak Kodihalli Tue, 31 Aug 2010 13:30:00 +0530 libmeegosyncml (0.4.9-29) unstable; urgency=low * Fixes: NB#183589 - Development packages libmeegosyncml-dev and sync-fw-dev does not contain .pc files -- Deepak Kodihalli Tue, 31 Aug 2010 09:32:56 +0530 libmeegosyncml (0.4.9-28) unstable; urgency=low * Tag for Meego * Made fixes for NB#185704: The bug can't yet be resolved due to dependencies, though. * Removed some proprietary HTTP headers. -- Duggirala Karthik Tue, 24 Aug 2010 16:00:00 +0300 libmeegosyncml (0.4.9-27) unstable; urgency=low * Fixes: NB#182304 - Some data not transfered message displayed when all data sync initiated from 5200 * Fixes: NB#185413 - Sync with Nokia 6300i fails with "no content available for sync" failure when there are three content types enabled -- Deepak Kodihalli Thu, 19 Aug 2010 11:59:04 +0530 libmeegosyncml (0.4.9-26) unstable; urgency=low * Fixed a regression in LocalChangesPackage::processRemovedItems : don't fetch these items from backend, as they have been deleted and don't exist! * Fixes: NB#185595 - Sync log doesnot display all the content type label names. -- Deepak Kodihalli Wed, 18 Aug 2010 11:59:04 +0530 libmeegosyncml (0.4.9-25) unstable; urgency=low * TODO : PR * Fixes: NB#179954 - It took ~10 minutes to display device contacts from NOS -- Deepak Kodihalli Tue, 17 Aug 2010 11:59:04 +0530 libmeegosyncml (0.4.9-24) unstable; urgency=low * Removed unnecessary stuff from debian/rules which was causing compilation issues! * Fixes: NB#183589 - Development packages libmeegosyncml-dev and sync-fw-dev does not contain .pc files -- Deepak Kodihalli Mon, 16 Aug 2010 14:06:48 +0530 libmeegosyncml (0.4.9-23) unstable; urgency=low * Fixes: NB#171728 - Switch needs to fall back to sync if client does not support one way sync. -- Deepak Kodihalli Tue, 10 Aug 2010 12:05:04 +0530 libmeegosyncml (0.4.9-22) unstable; urgency=low * Fixes: NB#183511 - SSU Fails: Packaging conflict between libmeegosyncml_0.4.9-17+0m6_armel.deb and libmaemosyncml 0.4.9-8+0m6 * Added UT cases for refresh sync. * Workaround for NB#176070 - QNetworkAccessManager can't be used in QThreads. * Fixes: 183009 - Optimize signals from sync backend to UI. -- Deepak Kodihalli Mon, 09 Aug 2010 10:14:00 +0530 libmeegosyncml (0.4.9-21) unstable; urgency=low * Fixes: NB#183706 Modified contact in N95 is updated to DUT after sync when delete the same contact in DUT before sync, when conflict set to DUT -- Duggirala Karthik Fri, 05 Aug 2010 09:26:52 +0530 libmeegosyncml (0.4.9-20) unstable; urgency=low * In case of an anchor mismatch, revert to refresh/slow sync based on the sync direction, sync initiator and remote device sync types. * Fixes: NB#183279 defects from libmaemosyncml -- Duggirala Karthik Thu, 05 Aug 2010 09:26:52 +0530 libmeegosyncml (0.4.9-19) unstable; urgency=low * Fixes: NB#180367 Conflict set to DUT: Modified contact in DUT is not updated to N95, when modify a contact in DUT and delete the same contact in N95. * Fixes: NB#180360 Modifications made to device contacts are not reflected in N900 when conflict is set to device and vice versa * Fixes: NB#183324 - Unable to integrate SyncScheduleSettingsDialog into MfE accounts ui plugin. -- Duggirala Karthik Wed, 04 Aug 2010 11:30:08 +0530 libmeegosyncml (0.4.9-18) unstable; urgency=low * Implemented refresh sync, merged changes from refresh_sync branch to nokia_proprietary branch. * Fixes: NB#180900 - Support refresh sync in client and server modes. * Fixes: NB#177628 - N900 : Send use case fails when sync initiated from * Fixes: NB#182959 - Sync failed for Calendar only data when initiated from S60 (N97mini) * Don't fail addition/modification for an item that has without a . -- Duggirala Karthik Mon, 02 Aug 2010 11:30:08 +0530 libmeegosyncml (0.4.9-17) unstable; urgency=low * Changing package name libmaemosyncml->libmeegosyncml -- Duggirala Karthik Fri, 23 Jul 2010 14:29:24 +0530 libmaemosyncml (0.4.9-16) unstable; urgency=low * Fixes: NB#167889 - Sync fails if bluetooth pairing is removed from device -- Duggirala Karthik Thu, 22 Jul 2010 14:29:24 +0530 libmaemosyncml (0.4.9-15) unstable; urgency=low * Fixes: NB#181297 - "remote initiated sync from S40/S60/N900 does not end at all" -- Duggirala Karthik Wed, 21 Jul 2010 14:29:24 +0530 libmaemosyncml (0.4.9-14) unstable; urgency=low * Fixes: NB#179703 - Syncing calendar data and notes with S60 (N97mini) fails, initiated from Device -- Duggirala Karthik Tue, 20 Jul 2010 14:29:24 +0530 libmaemosyncml (0.4.9-13) unstable; urgency=low * Rebuild -- Duggirala Karthik Mon, 19 Jul 2010 15:10:24 +0530 libmaemosyncml (0.4.9-12) unstable; urgency=low * Reverted fix 177628 * Fixes: NB#180426 - Switch fails for all/individual data with S60 phone -- Duggirala Karthik Fri, 16 Jul 2010 15:10:24 +0530 libmaemosyncml (0.4.9-11) unstable; urgency=low * Fixes: NB#176944 - Changes required in syncml stack state machine to handle receiving of mappings while it's sending items. * Close the obex BT link in client mode when there is a link error. * Fixes: 177628 - N900 : Send use case fails when sync initiated from device in particular scenario -- Duggirala Karthik Wed, 14 Jul 2010 15:10:24 +0530 libmaemosyncml (0.4.9-10) unstable; urgency=low * Rebuild . -- Duggirala Karthik Thu, 08 Jul 2010 14:52:24 +0530 libmaemosyncml (0.4.9-9) unstable; urgency=low * Compilation fixes . -- Duggirala Karthik Wed, 07 Jul 2010 14:52:24 +0530 libmaemosyncml (0.4.9-8) unstable; urgency=low * Support for reading configuration from a file * Modified configuration API to be based on properties, and easier to use * Added support of http x-headers * Fixes: NB#176791 - There should be a HTTP patches to sync-app and libmaemosyncml for AT&T addressbook synch -- Duggirala Karthik Sat, 03 Jul 2010 14:52:24 +0530 libmaemosyncml (0.4.9-7) unstable; urgency=low * Fixes: NB#174412 - All data sync from device to N900 does not end * Fixes: NB#174748 - Remote sync from S40 fails always, if sync application is open then sync ui crashes too * Fixes: NB#176871 - msyncd crash when delete a calendar event in N95 and modify the same event in device. -- Duggirala Karthik Mon, 28 Jun 2010 14:52:24 +0530 libmaemosyncml (0.4.9-6) unstable; urgency=low * Fixes: NB#166841 - Contacts in device are not synchronized to S40 device - server client role change * Dynamic role selection -- Duggirala Karthik Mon, 21 Jun 2010 14:52:24 +0530 libmaemosyncml (0.4.9-5) unstable; urgency=low * Removal of profile related changes. -- Duggirala Karthik Fri, 18 Jun 2010 14:52:24 +0530 libmaemosyncml (0.4.9-3) unstable; urgency=low * Fixes: 174265 - Msyncd crashed when avatar is added to contact and synced from DUT to N900 -- Duggirala Karthik Mon, 14 Jun 2010 14:52:24 +0530 libmaemosyncml (0.4.9-2) unstable; urgency=low * Fixed issues related to storing and cleaning of id mappings * Fixes: NB#171533 - Device sync to S40-msyncd crashed for all data -- Duggirala Karthik Sun, 13 Jun 2010 15:42:48 +0530 libmaemosyncml (0.4.9-1) unstable; urgency=low * Fixes: NB#172829 - Contacts created in DUT does not synchronize to N900 - N900 Initiated * Accounts related changes. -- Duggirala Karthik Wed, 09 Jun 2010 14:46:29 +0530 libmaemosyncml (0.4.8-13) unstable; urgency=low * Fixes: NB#172626 None of the calendar events from S40 gets synchronized to DUT - S40 Initiated * Fixes: NB#166780 Syncing combination of any 2 N900 contents failing when sync initiated from N900 . -- Duggirala Karthik Fri, 04 Jun 2010 13:35:21 +0530 libmaemosyncml (0.4.8-12) unstable; urgency=low * Fixes: Phone number is displayed in the Contact application instead of Name after transferring contacts via switch application. -- Duggirala Karthik Mon, 02 Jun 2010 13:35:21 +0530 libmaemosyncml (0.4.8-10) unstable; urgency=low * Fixes: Phone number is displayed in the Contact application instead of Name after transferring contacts via switch application. * Fixes: NB#171057 - msyncd crash for calendar data with N95 in conflict scenario. -- Duggirala Karthik Mon, 31 May 2010 13:35:21 +0530 libmaemosyncml (0.4.8-9) unstable; urgency=low * Fixes: NB#171057 - msyncd crash for calendar data with N95 in conflict scenario. * Fixes: NB#169487 Phone number is displayed in the Contact application instead of Name after transferring contacts via switch application -- Duggirala Karthik Tue, 25 May 2010 13:35:21 +0530 libmaemosyncml (0.4.8-8) unstable; urgency=low * Added convinience function to ChangeLog to allow external applications to manipulate and delete sync anchor data -- Duggirala Karthik Wed, 19 May 2010 13:35:21 +0530 libmaemosyncml (0.4.8-7) unstable; urgency=low * Added convinience function to ChangeLog to allow external applications to manipulate and delete sync anchor data * Fixes: NB#167135 - Modified Calendar/Contact data is added as duplicate copies in DUT if first sync is initiated from S60 -- Duggirala Karthik Sat, 15 May 2010 13:35:21 +0530 libmaemosyncml (0.4.8-6) unstable; urgency=low * Week 18 PR * Large improvements to OBEX transport * Updates to doxygen documentation * Fixes: NB161729 - Remote sync from the latest S60 phones does not work due to d2dsettings message * Fixes: NB164672 None of the bookmarks are synchronized from DUT to PC via Ovi_suite BT/USB * Removed SAN package digest check. -- Duggirala Karthik Wed, 28 Apr 2010 16:11:43 +0300 libmaemosyncml (0.4.8-5) unstable; urgency=low * Week 17 PR * Made server URI comparison case insensitive when figuring out MIME type -- Duggirala Karthik Wed, 21 Apr 2010 13:44:05 +0300 libmaemosyncml (0.4.8-4) unstable; urgency=low * Week 16 PR -- Duggirala Karthik Wed, 14 Apr 2010 13:48:45 +0300 libmaemosyncml (0.4.8-3) unstable; urgency=low * Week 15 PR -- Duggirala Karthik Wed, 07 Apr 2010 13:39:36 +0300 libmaemosyncml (0.4.8-2) unstable; urgency=low * Minor fix for crash seen in ovi suite sync with contacts -- Srikanth Kavoori Thu, 01 Apr 2010 16:21:17 +0300 libmaemosyncml (0.4.8-1) unstable; urgency=low * Week 14 PR * Added support for re-sending initialization package for HTTP transport * Review Comments Changes updated -- Srikanth Kavoori Wed, 31 Mar 2010 14:17:17 +0300 libmaemosyncml (0.4.8-0) unstable; urgency=low * Week 13 PR * Fixes: NB#157296 - Code review for libmaemosyncml -- Srikanth Kavoori Wed, 24 Mar 2010 17:49:10 +0200 libmaemosyncml (0.4.7-9) unstable; urgency=low * Week 12 PR * Added support for server initiated syncing using SyncML 1.2 SAN package -- Srikanth Kavoori Thu, 18 Mar 2010 19:22:03 +0200 libmaemosyncml (0.4.7-8) unstable; urgency=low * Fix for properly sending wbxml when requested after receiving SAN message * Fixes: NB#160190 - 'Some data not copied' message is displayed after synchronizing calendar data/notes/contacts with S60 phone * Support for multiple CTCap objects per storage -- Srikanth Kavoori Tue, 16 Mar 2010 14:54:47 +0200 libmaemosyncml (0.4.7-7) unstable; urgency=low * Week 10 PR -- Srikanth Kavoori Thu, 11 Mar 2010 11:32:03 +0200 libmaemosyncml (0.4.7-6) unstable; urgency=low * Week 09 PR * Fixed some bugs in OBEX transport * Different MTU's for BT and USB transports * Fixes: NB#153864 - msyncd constantly consumes ~75% of CPU after transferring 2 GB of data to DUT -- Srikanth Kavoori Wed, 3 Mar 2010 09:52:47 +0200 libmaemosyncml (0.4.7-5) unstable; urgency=low * Week 08 PR * Reinforced OBEX transport to only accept Connect commands with target set to "SYNCML-SYNC" * Support for hierarchical synchronization added -- Srikanth Kavoori Wed, 24 Feb 2010 16:04:45 +0200 libmaemosyncml (0.4.7-4) unstable; urgency=low * Week 07 PR * Removed dependency to sqlite3 package * Added support for parsing & initiating sync from SyncML 1.2 SAN package -- Srikanth Kavoori Thu, 18 Feb 2010 15:44:17 +0200 libmaemosyncml (0.4.7-3) unstable; urgency=low * Week 07 Release * Implemented: SWP#Hsync-698: Busy Signalling * Made upper limit for number of changes as configurable * Fixes: NB#150562 - in sync * Fixes: NB#156558 - valgrind returns 2 Invalid Read issues for libmaemosyncml-tests -- Srikanth Kavoori Mon, 15 Feb 2010 09:24:47 +0200 libmaemosyncml (0.4.7-2) unstable; urgency=low * Week 06 Release 2 -- Srikanth Kavoori Thu, 11 Feb 2010 13:14:14 +0200 libmaemosyncml (0.4.7-1) unstable; urgency=low * Week 06 Release -- Srikanth Kavoori Mon, 8 Feb 2010 10:15:56 +0200 libmaemosyncml (0.4.7-0) unstable; urgency=low * Week 05 Release * Fixed itemProcessed() signal not being emitted when items have been added to remote database * Fixes: NB#153991 - msyncd crashed while synchronizing all data with N900 -- Srikanth Kavoori Mon, 1 Feb 2010 14:38:16 +0200 libmaemosyncml (0.4.6-4) unstable; urgency=low * Week 04 Release * Added the feature to limit the number of messages per syncml message -- Srikanth Kavoori Mon, 25 Jan 2010 11:44:55 +0200 libmaemosyncml (0.4.6-3) unstable; urgency=low * Week 03 Release 01 -- Srikanth Kavoori Mon, 18 Jan 2010 11:31:47 +0200 libmaemosyncml (0.4.6-2) unstable; urgency=low * Week 02 Release 2 -- Srikanth Kavoori Wed, 13 Jan 2010 12:06:10 +0200 libmaemosyncml (0.4.6-1) unstable; urgency=low * Week 02 Release * Fixes: NB#150562 - Memory leaks in libmaemosyncml tests -- Srikanth Kavoori Mon, 11 Jan 2010 14:33:59 +0200 libmaemosyncml (0.4.6-0) unstable; urgency=low * Week 52 Release -- Srikanth Kavoori Mon, 21 Dec 2009 14:36:39 +0200 libmaemosyncml (0.4.5-0) unstable; urgency=low * Week 51 Release * Fixes: NB#149311 - First sync does not add any data from N900 * Fixes: NB#148705 - Coverity defects for libmaemosyncml -- Srikanth Kavoori Mon, 14 Dec 2009 14:55:31 +0200 libmaemosyncml (0.4.4-1) unstable; urgency=low * Week 50 Release 2 * Fixed anchor handling in server initiated syncs -- Srikanth Kavoori Tue, 8 Dec 2009 15:48:46 +0200 libmaemosyncml (0.4.4-0) unstable; urgency=low * Week 50 Release * Fixed hanging issue occurring when in OBEX server mode * Fixed server initiated one-way syncs * Fixes: NB#147760 - Unit test problems in CI environment * Fixes: NB#146321 - Transfer of contacts and calendar fails from Switch UI -- Srikanth Kavoori Mon, 7 Dec 2009 11:40:39 +0200 libmaemosyncml (0.4.3-0) unstable; urgency=low * Week 49 Release * Fixed not sending SyncML Status in response to received Results -- Srikanth Kavoori Tue, 1 Dec 2009 10:31:46 +0200 libmaemosyncml (0.4.2-0) unstable; urgency=low * Week 48 Release * Fixes: NB#146324 - Synchronization fails with S40 devices * Send MaxGUIDSize in DevInf in client mode * Fixes: NB#145231 - Code review comments -- Srikanth Kavoori Tue, 24 Nov 2009 16:32:35 +0200 libmaemosyncml (0.4.1-1) unstable; urgency=low * Week 47 Release 2 -- Srikanth Kavoori Wed, 18 Nov 2009 15:19:51 +0200 libmaemosyncml (0.4.1-0) unstable; urgency=low * Week 47 Release * Fixes: NB#144679 - some major and moderate defects from sync -- Srikanth Kavoori Mon, 16 Nov 2009 17:23:51 +0200 libmaemosyncml (0.4.0-0) unstable; urgency=low * Week 46 Release * Added Optimisation Flags * Fixes: NB#145558 - Code review comments * Dedicated CTCaps handling for both SyncML 1.1 and SyncML 1.2 * Database performance improvements -- Srikanth Kavoori Tue, 10 Nov 2009 18:55:14 +0200 libmaemosyncml (0.3.9-0) unstable; urgency=low * Week 45 Release 1 * Commit changes to local database in batches -- Srikanth Kavoori Wed, 4 Nov 2009 12:22:46 +0200 libmaemosyncml (0.3.8-2) unstable; urgency=low * Week 44 Release 2 -- Srikanth Kavoori Tue, 27 Oct 2009 17:27:13 +0200 libmaemosyncml (0.3.8-1) unstable; urgency=low * Week 44 Release 1 * Added libmaemosyncml-tests package support to run unit tests during CI -- Srikanth Kavoori Mon, 26 Oct 2009 18:31:42 +0200 libmaemosyncml (0.3.8-0) unstable; urgency=low * Week 43 Release * Direct wbxml encoding using libwbxml2 * Use libwbxml2 instead of xml2wbxml in wbxml conversions -- Srikanth Kavoori Tue, 20 Oct 2009 17:26:42 +0300 libmaemosyncml (0.3.7-1) unstable; urgency=low * Week 42 Release 2 * Item format specified under Item Meta now overrides ones specified under Add/Replace Meta * Removed BT service from libmaemosyncml as obsolete -- Srikanth Kavoori Fri, 16 Oct 2009 17:58:17 +0300 libmaemosyncml (0.3.7-0) unstable; urgency=low * Week 42 Release * Accept "bin" encoding format as "b64" * Fixed progress reporting of SyncAgent -- Srikanth Kavoori Tue, 13 Oct 2009 18:32:56 +0300 libmaemosyncml (0.3.6-1) unstable; urgency=low * Week 41 Release * made coverage as an extra target -- Srikanth Kavoori Mon, 5 Oct 2009 18:29:09 +0300 libmaemosyncml (0.3.6-0) unstable; urgency=low * Removed debug package installation as the size exceeds the limit -- Srikanth Kavoori Fri, 2 Oct 2009 11:48:09 +0300 libmaemosyncml (0.3.5-9) unstable; urgency=low * Week 40 Release 2 * minor changes to session handler -- Srikanth Kavoori Thu, 1 Oct 2009 18:38:52 +0300 libmaemosyncml (0.3.5-8) unstable; urgency=low * Week 40 Release -- Srikanth Kavoori Tue, 29 Sep 2009 17:53:52 +0300 libmaemosyncml (0.3.5-7) unstable; urgency=low * Week 39 Release 2 -- Srikanth Kavoori Fri, 25 Sep 2009 08:14:26 +0300 libmaemosyncml (0.3.5-6) unstable; urgency=low * Week 39 Release * Code review fixes -- Srikanth Kavoori Tue, 22 Sep 2009 17:43:00 +0300 libmaemosyncml (0.3.5-5) unstable; urgency=low * Week 38 Release 2 * Changed retrieval of storages from as-supplied to on-demand -- Srikanth Kavoori Thu, 17 Sep 2009 18:16:19 +0300 libmaemosyncml (0.3.5-4) unstable; urgency=low * Week 38 Release * Fixed OBEX transport not to crash in SB * Optimized SyncML Delete command performance * Fixed retrieval of item id from Replace/Delete when running in server mode * Fixes: NB#133670 - No license information for the source files -- Srikanth Kavoori Wed, 16 Sep 2009 11:46:35 +0300 libmaemosyncml (0.3.5-3) unstable; urgency=low * week 37 Release 2 -- Srikanth Kavoori Thu, 10 Sep 2009 18:11:05 +0300 libmaemosyncml (0.3.5-2) unstable; urgency=low * Week 37 Release * Minor bugfixes to OBEX server operation -- Lassi Nieminen Tue, 8 Sep 2009 17:35:31 +0300 libmaemosyncml (0.3.5-1) unstable; urgency=low * Week 36 Release 2 * Last sync time now rounded to the next following second -- Lassi Nieminen Thu, 3 Sep 2009 14:41:04 +0300 libmaemosyncml (0.3.5-0) unstable; urgency=low * Week 36 Release * Fixed issues with database opening warning -- Lassi Nieminen Tue, 1 Sep 2009 17:12:10 +0300 libmaemosyncml (0.3.4-1) unstable; urgency=low * Fixed issues in BT disconnect * Cleaned up StoragePlugin and SyncItem APIs -- Lassi Nieminen Thu, 27 Aug 2009 16:11:00 +0300 libmaemosyncml (0.3.4-0) unstable; urgency=low * Week35 Release -- Lassi Nieminen Tue, 25 Aug 2009 17:43:26 +0300 libmaemosyncml (0.3.3-0) unstable; urgency=low * Week 34 release: * Added Suspend/Resume feature -- Lassi Nieminen Fri, 21 Aug 2009 09:27:11 +0300 libmaemosyncml (0.3.2-1) unstable; urgency=low * Added MD5 authentication support for server and client * Added server-side authentication * Added sync without initialization phase -- Lassi Nieminen Wed, 19 Aug 2009 18:24:38 +0300 libmaemosyncml (0.3.2-0) unstable; urgency=low * Week33 release * Device to Device Sync functionality is checked using 2 harmattan devices. Note: This Cannot be done from existing UI though * SyncAgent API Interface has been updated and a new API for setting the authentication has been added * BT sync issue with s60 fixed * ID mapping tracking has been added to the code. yet to verify. * Week 32 release * Added device capability sending * Added authentication challenge handling. MD5 and server side authentication not yet done. -- Lassi Nieminen Wed, 19 Aug 2009 18:24:27 +0300 * Week 31 release. Fixes: NB#129610,NB#126685 * Removed: transport/HTTPServerTransport.h transport/HTTPServerTransport.cpp -- Lassi Nieminen Thu, 30 Jul 2009 18:00:00 +0200 * Week 29 release -- Lassi Nieminen Sat, 18 Jul 2009 17:59:50 +0200 * Week 28 release -- Lassi Nieminen Tue, 08 Jul 2009 17:49:50 +0200 * Week 27 release -- Lassi Nieminen Thu, 02 Jul 2009 17:49:50 +0200 libmaemosyncml (0.2.5-1) unstable; urgency=low * Week 26 release -- Lassi Nieminen Thu, 25 Jun 2009 15:49:50 +0200 libmaemosyncml (0.2.2-0) unstable; urgency=low * Phase 2 Initial release (Closes: #nnnn) -- Lassi Nieminen Mon, 1 Jun 2009 15:11:50 +0200 buteo-syncml-0.5.15/debian/compat000066400000000000000000000000021433763642500166600ustar00rootroot000000000000005 buteo-syncml-0.5.15/debian/control000066400000000000000000000027651433763642500170770ustar00rootroot00000000000000Source: libmeegosyncml Priority: extra Maintainer: Duggirala Karthik Build-Depends: debhelper (>= 5),doxygen, cdbs ,libqt4-dev (>= 4.5), libwbxml2-dev, libsqlite3-dev, libopenobex1-dev, libqt4-sql-sqlite, sync-fw-dev Standards-Version: 3.7.2 Section: libs Package: libmeegosyncml Section: libs Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, libqt4-sql-sqlite (>= 4.5) Replaces: libmaemosyncml Conflicts: libmaemosyncml Description: SyncML library for Harmattan sync. Package holds SyncmL library for Harmattan sync. Package: libmeegosyncml-dev Section: libdevel Architecture: any Depends: libmeegosyncml (= ${binary:Version}), libqt4-dev (>= 4.5) Replaces: libmaemosyncml-dev Conflicts: libmaemosyncml-dev Description: Header files for SyncML library for synchronization. Package holds h-files for Harmattan SyncML. Package: libmeegosyncml-dbg Section: libs Architecture: any Depends: libmeegosyncml (= ${binary:Version}) Description: Debug symbols for libmeegosyncml. Debug symbols for libmeegosyncml. Package: libmeegosyncml-doc Section: doc Architecture: any Description: API documentation for libmeegosyncml. Empty documentation package for libmeegosyncml. Package: libmeegosyncml-tests Section: tests Priority: optional Architecture: any Depends: ${shlibs:Depends},libmeegosyncml, testrunner-lite XB-Maemo-CI-Stage: staging XB-Maemo-CI-Packages: libmeegosyncml-tests Description: Module test package for libmeegosyncml. Module test package for libmeegosyncml. buteo-syncml-0.5.15/debian/copyright000066400000000000000000000010521433763642500174130ustar00rootroot00000000000000This package was debianized by Tatu Lahtela on Wed, 10 Dec 2008 13:53:12 +0200. It was downloaded from Upstream Author: Copyright: License: The Debian packaging is (C) 2009, Tatu LahtelaLassi # Please also look if there are files or directories which have a # different copyright/license attached and list them here. buteo-syncml-0.5.15/debian/libmeegosyncml-dev.install000066400000000000000000000000741433763642500226400ustar00rootroot00000000000000usr/include/* usr/lib/pkgconfig usr/lib/libmeegosyncml.prl buteo-syncml-0.5.15/debian/libmeegosyncml-doc.install000066400000000000000000000000201433763642500226160ustar00rootroot00000000000000usr/share/doc/* buteo-syncml-0.5.15/debian/libmeegosyncml-tests.install000066400000000000000000000000531433763642500232210ustar00rootroot00000000000000usr/share/libmeegosyncml-tests/* usr/bin/* buteo-syncml-0.5.15/debian/libmeegosyncml.install000066400000000000000000000000551433763642500220630ustar00rootroot00000000000000usr/lib/lib*.so.* usr/lib/lib*.so etc/sync/* buteo-syncml-0.5.15/debian/rules000077500000000000000000000077611433763642500165550ustar00rootroot00000000000000#!/usr/bin/make -f # -*- makefile -*- # Sample debian/rules that uses debhelper. # This file was originally written by Joey Hess and Craig Small. # As a special exception, when this file is copied by dh-make into a # dh-make output file, you may use that output file without restriction. # This special exception was added by Craig Small in version 0.37 of dh-make. # # # Uncomment this to turn on verbose mode. export DH_VERBOSE=1 QMAKE = /usr/bin/qmake -makefile libmeegosyncml.pro CFLAGS += -Wall -Wextra -Wno-unused-parameter --strip-unneeded CXXFLAGS += -Wall -Wextra -Wno-unused-parameter --strip-unneeded comma :=, empty := space := $(empty) $(empty) ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS))) INSTALL_PROGRAM += -s endif TMP_BUILD_OPTS = $(subst $(comma),$(space),$(DEB_BUILD_OPTIONS)) ifneq (,$(filter parallel=%,$(TMP_BUILD_OPTS))) NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(TMP_BUILD_OPTS))) PARALLEL_MAKEFLAGS += -j$(NUMJOBS) endif configure: configure-stamp configure-stamp: dh_testdir # Add here commands to configure the package. /usr/bin/qmake -makefile libmeegosyncml.pro touch configure-stamp build: build-stamp build-stamp: configure-stamp dh_testdir # Add here commands to compile the package. $(MAKE) $(PARALLEL_MAKEFLAGS) touch $@ clean: dh_testdir dh_testroot rm -f build-stamp configure-stamp # Add here commands to clean up after the build process. # $(MAKE) clean [ ! -f Makefile ] || $(MAKE) distclean rm -f Makefile src/Makefile dh_clean install: build dh_testdir dh_testroot dh_clean -k dh_installdirs make $(PARALLEL_MAKEFLAGS) doc INSTALL_ROOT=$(CURDIR)/debian/tmp make $(PARALLEL_MAKEFLAGS) install # Add here commands to install the package into debian/tmp $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install # Build architecture-independent files here. binary-indep: build install # We have nothing to do by default. # # Build architecture-dependent files here. binary-arch: build install dh_testdir dh_testroot dh_installdirs dh_installchangelogs dh_installdocs dh_installexamples dh_install --sourcedir=debian/tmp -v dh_installman dh_strip --dbg-package=libmeegosyncml-dbg dh_compress dh_fixperms dh_makeshlibs dh_installdeb dh_shlibdeps ## TODO Disabled for now so the build succeeds dh_gencontrol dh_md5sums dh_builddeb binary: binary-indep binary-arch .PHONY: build clean binary-indep binary-arch binary install configure #!/usr/bin/make -f #include /usr/share/cdbs/1/rules/debhelper.mk #include /usr/share/cdbs/1/class/qmake.mk #QMAKE = /usr/bin/qmake -makefile libmeegosyncml.pro #CFLAGS += -Wall -Wextra -Wno-unused-parameter #CXXFLAGS += -Wall -Wextra -Wno-unused-parameter DEB_DESTDIR := $(CURDIR)/debian/tmp #DEB_DH_INSTALL_SOURCEDIR := debian/tmp buteo-syncml-0.5.15/doc/000077500000000000000000000000001433763642500150055ustar00rootroot00000000000000buteo-syncml-0.5.15/doc/Doxyfile000066400000000000000000000261551433763642500165240ustar00rootroot00000000000000# Doxyfile 1.5.6-KDevelop #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- DOXYFILE_ENCODING = UTF-8 PROJECT_NAME = buteo-syncml PROJECT_NUMBER = OUTPUT_DIRECTORY = . CREATE_SUBDIRS = NO OUTPUT_LANGUAGE = English BRIEF_MEMBER_DESC = YES REPEAT_BRIEF = YES ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the ALWAYS_DETAILED_SEC = NO INLINE_INHERITED_MEMB = NO FULL_PATH_NAMES = NO STRIP_FROM_PATH = STRIP_FROM_INC_PATH = SHORT_NAMES = NO JAVADOC_AUTOBRIEF = NO QT_AUTOBRIEF = NO MULTILINE_CPP_IS_BRIEF = NO DETAILS_AT_TOP = NO INHERIT_DOCS = YES SEPARATE_MEMBER_PAGES = NO TAB_SIZE = 4 ALIASES = OPTIMIZE_OUTPUT_FOR_C = NO OPTIMIZE_OUTPUT_JAVA = NO OPTIMIZE_FOR_FORTRAN = NO OPTIMIZE_OUTPUT_VHDL = NO BUILTIN_STL_SUPPORT = NO CPP_CLI_SUPPORT = NO SIP_SUPPORT = NO IDL_PROPERTY_SUPPORT = YES DISTRIBUTE_GROUP_DOC = NO SUBGROUPING = YES TYPEDEF_HIDES_STRUCT = NO SYMBOL_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- EXTRACT_ALL = NO EXTRACT_PRIVATE = NO EXTRACT_STATIC = NO EXTRACT_LOCAL_CLASSES = YES EXTRACT_LOCAL_METHODS = NO EXTRACT_ANON_NSPACES = NO HIDE_UNDOC_MEMBERS = NO HIDE_UNDOC_CLASSES = NO HIDE_FRIEND_COMPOUNDS = NO HIDE_IN_BODY_DOCS = NO INTERNAL_DOCS = NO CASE_SENSE_NAMES = YES HIDE_SCOPE_NAMES = NO SHOW_INCLUDE_FILES = YES INLINE_INFO = YES SORT_MEMBER_DOCS = YES SORT_BRIEF_DOCS = NO SORT_GROUP_NAMES = NO SORT_BY_SCOPE_NAME = NO GENERATE_TODOLIST = YES GENERATE_TESTLIST = YES GENERATE_BUGLIST = YES GENERATE_DEPRECATEDLIST= YES ENABLED_SECTIONS = MAX_INITIALIZER_LINES = 30 SHOW_USED_FILES = YES SHOW_DIRECTORIES = NO SHOW_FILES = YES SHOW_NAMESPACES = YES FILE_VERSION_FILTER = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- QUIET = NO WARNINGS = YES WARN_IF_UNDOCUMENTED = YES WARN_IF_DOC_ERROR = YES WARN_NO_PARAMDOC = NO WARN_FORMAT = "$file:$line: $text" WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- INPUT = ../src/ INPUT_ENCODING = UTF-8 FILE_PATTERNS = *.c \ *.cc \ *.cxx \ *.cpp \ *.c++ \ *.d \ *.java \ *.ii \ *.ixx \ *.ipp \ *.i++ \ *.inl \ *.h \ *.hh \ *.hxx \ *.hpp \ *.h++ \ *.idl \ *.odl \ *.cs \ *.php \ *.php3 \ *.inc \ *.m \ *.mm \ *.dox \ *.py \ *.f90 \ *.f \ *.vhd \ *.vhdl \ *.C \ *.CC \ *.C++ \ *.II \ *.I++ \ *.H \ *.HH \ *.H++ \ *.CS \ *.PHP \ *.PHP3 \ *.M \ *.MM \ *.PY \ *.F90 \ *.F \ *.VHD \ *.VHDL \ *.C \ *.H \ *.tlh \ *.diff \ *.patch \ *.moc \ *.xpm \ *.dox RECURSIVE = yes EXCLUDE = EXCLUDE_SYMLINKS = NO EXCLUDE_PATTERNS = EXCLUDE_SYMBOLS = EXAMPLE_PATH = EXAMPLE_PATTERNS = * EXAMPLE_RECURSIVE = NO IMAGE_PATH = INPUT_FILTER = FILTER_PATTERNS = FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- SOURCE_BROWSER = NO INLINE_SOURCES = NO STRIP_CODE_COMMENTS = YES REFERENCED_BY_RELATION = NO REFERENCES_RELATION = NO REFERENCES_LINK_SOURCE = YES USE_HTAGS = NO VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- ALPHABETICAL_INDEX = NO COLS_IN_ALPHA_INDEX = 5 IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- GENERATE_HTML = YES HTML_OUTPUT = html HTML_FILE_EXTENSION = .html HTML_HEADER = HTML_FOOTER = HTML_STYLESHEET = HTML_ALIGN_MEMBERS = YES GENERATE_HTMLHELP = NO GENERATE_DOCSET = NO DOCSET_FEEDNAME = "Doxygen generated docs" DOCSET_BUNDLE_ID = org.doxygen.Project HTML_DYNAMIC_SECTIONS = NO CHM_FILE = HHC_LOCATION = QTHELP_FILE = QTHELP_CONFIG = DOXYGEN2QTHELP_LOC = GENERATE_CHI = NO CHM_INDEX_ENCODING = BINARY_TOC = NO TOC_EXPAND = NO DISABLE_INDEX = NO ENUM_VALUES_PER_LINE = 4 GENERATE_TREEVIEW = NONE TREEVIEW_WIDTH = 250 FORMULA_FONTSIZE = 10 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- GENERATE_LATEX = NO LATEX_OUTPUT = latex LATEX_CMD_NAME = latex MAKEINDEX_CMD_NAME = makeindex COMPACT_LATEX = NO PAPER_TYPE = a4wide EXTRA_PACKAGES = LATEX_HEADER = PDF_HYPERLINKS = YES USE_PDFLATEX = YES LATEX_BATCHMODE = NO LATEX_HIDE_INDICES = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- GENERATE_RTF = NO RTF_OUTPUT = rtf COMPACT_RTF = NO RTF_HYPERLINKS = NO RTF_STYLESHEET_FILE = RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- GENERATE_MAN = NO MAN_OUTPUT = man MAN_EXTENSION = .3 MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- GENERATE_XML = no XML_OUTPUT = xml XML_SCHEMA = XML_DTD = XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- GENERATE_PERLMOD = NO PERLMOD_LATEX = NO PERLMOD_PRETTY = YES PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- ENABLE_PREPROCESSING = YES MACRO_EXPANSION = NO EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES INCLUDE_PATH = INCLUDE_FILE_PATTERNS = PREDEFINED = EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- TAGFILES = GENERATE_TAGFILE = buteo-syncml.tag ALLEXTERNALS = NO EXTERNAL_GROUPS = YES PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- CLASS_DIAGRAMS = YES MSCGEN_PATH = HIDE_UNDOC_RELATIONS = YES HAVE_DOT = NO DOT_FONTNAME = FreeSans DOT_FONTPATH = CLASS_GRAPH = YES COLLABORATION_GRAPH = YES GROUP_GRAPHS = YES UML_LOOK = NO TEMPLATE_RELATIONS = NO INCLUDE_GRAPH = YES INCLUDED_BY_GRAPH = YES CALL_GRAPH = NO CALLER_GRAPH = NO GRAPHICAL_HIERARCHY = YES DIRECTORY_GRAPH = YES DOT_IMAGE_FORMAT = png DOT_PATH = DOTFILE_DIRS = DOT_GRAPH_MAX_NODES = 50 MAX_DOT_GRAPH_DEPTH = 1000 DOT_TRANSPARENT = YES DOT_MULTI_TARGETS = NO GENERATE_LEGEND = YES DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::additions related to the search engine #--------------------------------------------------------------------------- SEARCHENGINE = NO buteo-syncml-0.5.15/doc/coverage/000077500000000000000000000000001433763642500166005ustar00rootroot00000000000000buteo-syncml-0.5.15/doc/coverage/build_documentation.sh000077500000000000000000000032751433763642500231760ustar00rootroot00000000000000#!/bin/sh #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ ./coverage.sh cd .. doxygen Doxyfile buteo-syncml-0.5.15/doc/coverage/coverage-html.sh000077500000000000000000000051521433763642500216770ustar00rootroot00000000000000#!/bin/sh #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ #alias echo='echo -e'\E[31;40m #check for the Makefile #COVERAGE_LOG=/var/log/libmeegosyncml_coverage.log #if [ -f $COVERAGE_LOG ] #then #rm -f $COVERAGE_LOG #fi WD=$PWD STACKDIR=../../ cd $STACKDIR if [ -f Makefile ]; then echo "Makefile Exists.. Removing it and creating one" find . -name Makefile | xargs rm -f qmake else echo "Makefile does not exist .. Creating one... " qmake fi #run the coverage script echo "Running the coverage script .. " sh $WD/coverage.sh if [ $? -ne 0 ]; then echo "Coverage Script Failed" echo "Exiting the script" exit 1 else echo "Coverage Script ran successfully " fi echo "Running lcov" lcov -d . -c -o doc/coverage/coverage.info if [ $? -ne 0 ]; then echo "Script Failed while using Lcov" exit 1 else echo "Lcov successfully Ran" fi cd doc/coverage echo "Generating Documentation" genhtml -o cov coverage.info if [ $? -ne 0 ]; then echo "Documentation Generation Failed" exit 1 else echo "Documentation Generation Successful" fi buteo-syncml-0.5.15/doc/coverage/coverage.sh000077500000000000000000000043441433763642500207370ustar00rootroot00000000000000#!/bin/sh #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ export LD_LIBRARY_PATH=$PWD/meegosyncml echo -e "PWD is $PWD" cd meegosyncml qmake make clean echo 'Building meegosyncml with coverage support' make coverage if [ $? -ne 0 ]; then echo "meegosyncml build failed" exit 1 else echo "meegosyncml Built Successfully" fi cd ../Tests qmake make clean echo 'Building Tests' make if [ $? -ne 0 ]; then echo "Tests build failed" exit 1 else echo "Tests Built Successfully" fi echo 'Running Tests' ./Tests if [ $? -ne 0 ]; then echo "Ran Tests Successfully" echo "Running Tests Failed" exit 1 else echo "Ran Tests Successfully" exit 0 fi buteo-syncml-0.5.15/doc/coverage/gcov_info.pl000077500000000000000000000056521433763642500211210ustar00rootroot00000000000000#!/usr/bin/perl #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ # Author : Srikanth Kavoori # Not Tested fully yet. There could be some issues. # If you see any issues Let me know and i shall fix it :) open(INPUTFILE, "<$ARGV[0]"); open(EXTRACTED_INFO,">$ARGV[2]"); $exclude_string = "/usr/include/"; $exclude_string2 = ".h"; $coverage_count_string ="Lines executed:"; $count = 0; $filecount = 0; $coverage_percent = 0; while() { my($line) = $_; if ($count == 3) { $count = 0; } if(/$exclude_string/ || /$exclude_string2/) { #print "Found usr_include or header file on line $. \n" ; $count ++; } if ($count == 0) { # Print the line to the extracted_info and add a newline print EXTRACTED_INFO "$line\n"; if(/$coverage_count_string/) { $filecount ++; $index = rindex($line,':') + 1; $percent = substr($line,$index); $perc_index = rindex($percent,'%'); $percent = substr($percent,0,$perc_index); $coverage_percent += $percent; } } else { #count should be 1 or 2 omit the line $count ++; } } if($filecount != 0 ) { $coverage_percent=sprintf("%.2f",$coverage_percent/$filecount); } print "Total No. of files : $filecount Coverage Percent : $coverage_percent "; open(PERCENTFILE,">$ARGV[1]"); print PERCENTFILE "$coverage_percent\n" ; close(PERCENTFILE); close(INPUTFILE); close(EXTRACTED_INFO); buteo-syncml-0.5.15/doc/coverage/run-tests-libmaemosyncml.sh000077500000000000000000000117001433763642500241130ustar00rootroot00000000000000#!/bin/bash #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ #Author - Srikanth Kavoori # This file should run unittests for libmaemosyncml # and create the result file with unittest rate # and coverage to this folder with name # libmaemosyncml-results # # The release number should be in the file # this script generates the results automatically # for the latest weekXxX directory under libmaemosyncml #this script updation should be rarely needed #Script Specific Variables TARGET=libmaemosyncml WD=$PWD if [ $# == 0 ]; then echo "Enviroment is set to trunk " ROOTDIR=$WD/../.. TESTS_DIR=$ROOTDIR/Tests STACK_DIR=$ROOTDIR/maemosyncml RESULTS_FILE=$WD/$TARGET-results else echo "Enviroment is set to tags" WD=$1 TARGET_WEEK=$(ls -c $WD/../$TARGET | head -1) TESTS_DIR=$WD/../$TARGET/$TARGET_WEEK/Tests STACK_DIR=$WD/../$TARGET/$TARGET_WEEK/maemosyncml RESULTS_DIR=$2 RESULTS_FILE=$RESULTS_DIR/$TARGET-results_$TARGET_WEEK export SBOX_USE_CCACHE=no ccache -c fi export LD_LIBRARY_PATH=$STACK_DIR:$LD_LIBRARY_PATH TEMPFILE1=$WD/.temp_results if [ -f $TEMPFILE1 ] then rm -f $TEMPFILE1 fi TEMPFILE2=$WD/.gcov_info.txt if [ -f $TEMPFILE2 ] then rm -f $TEMPFILE2 fi TEMPFILE3=$WD/.percent if [ -f $TEMPFILE3 ] then rm -f $TEMPFILE3 fi export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$STACK_DIR echo "Running the unit tests for $TARGET..." echo "Results will be stored in: $RESULTS_FILE ...." #Build the library with coverage echo "Building Stack in $STACK_DIR" cd $STACK_DIR qmake make clean make coverage echo "tests directory is $TESTS_DIR" cd $TESTS_DIR qmake make clean make echo "Running the tests in $PWD" ./libmaemosyncml-tests > $TEMPFILE1 echo "Getting the Coverage Results" cd $STACK_DIR echo $PWD rm -f moc_* file_list=$(ls *.gcno) #echo "Printing File List :$file_list " for file in $file_list do echo "Running gcov on $file" gcov $file >> $TEMPFILE2 done # get coverage information for the files using perl echo "executing perl gcov_info.pl $TEMPFILE2 $TEMPFILE3" GCOV_REPORT=$WD/gcov_report.txt perl $WD/gcov_info.pl $TEMPFILE2 $TEMPFILE3 $GCOV_REPORT if [ ! $? -eq 0 ]; then # echo "Perl Script for gcov information exit normal" #else echo "Perl Script for gcov information Failed to execute ... Exiting ... " exit 0 fi SUMMARY_FILE=$WD/.summary_file if [ -f $SUMMARY_FILE ] then rm -f $SUMMARY_FILE fi perl $WD/test_info.pl $TEMPFILE1 $SUMMARY_FILE if [ ! $? -eq 0 ]; then #echo "Perl Script for test information exit normal" #else echo "Perl Script for test information Failed to execute ... Exiting ... " exit 0 fi echo "Writing the file $RESULTS_FILE" echo "#Results for $TARGET_WEEK " > $RESULTS_FILE echo "Results Summary STARTED " >> $RESULTS_FILE echo "#Current gcov reported coverage (line rate) is" >> $RESULTS_FILE cat $TEMPFILE3 >> $RESULTS_FILE echo "Unit test Results Summary " >> $RESULTS_FILE cat $SUMMARY_FILE >> $RESULTS_FILE echo "Results Summary ENDED " >> $RESULTS_FILE echo "(all unit tests are not refactored yet)" >> $RESULTS_FILE echo "#Coverage report is visible in $WD/gcov_report.txt" >> $RESULTS_FILE echo "****************UNIT_TEST Results **************" >> $RESULTS_FILE cat $TEMPFILE1 >> $RESULTS_FILE rm -f $TEMPFILE1 $TEMPFILE2 $TEMPFILE3 $SUMMARY_FILE cd $STACK_DIR rm -f *.gcno *.gcda *.gcov cd $WD echo "$RESULTS_FILE created" buteo-syncml-0.5.15/doc/coverage/run-tests-libmeegosyncml.sh000077500000000000000000000117001433763642500241110ustar00rootroot00000000000000#!/bin/bash #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ #Author - Srikanth Kavoori # This file should run unittests for libmeegosyncml # and create the result file with unittest rate # and coverage to this folder with name # libmeegosyncml-results # # The release number should be in the file # this script generates the results automatically # for the latest weekXxX directory under libmeegosyncml #this script updation should be rarely needed #Script Specific Variables TARGET=libmeegosyncml WD=$PWD if [ $# == 0 ]; then echo "Enviroment is set to trunk " ROOTDIR=$WD/../.. TESTS_DIR=$ROOTDIR/Tests STACK_DIR=$ROOTDIR/meegosyncml RESULTS_FILE=$WD/$TARGET-results else echo "Enviroment is set to tags" WD=$1 TARGET_WEEK=$(ls -c $WD/../$TARGET | head -1) TESTS_DIR=$WD/../$TARGET/$TARGET_WEEK/Tests STACK_DIR=$WD/../$TARGET/$TARGET_WEEK/meegosyncml RESULTS_DIR=$2 RESULTS_FILE=$RESULTS_DIR/$TARGET-results_$TARGET_WEEK export SBOX_USE_CCACHE=no ccache -c fi export LD_LIBRARY_PATH=$STACK_DIR:$LD_LIBRARY_PATH TEMPFILE1=$WD/.temp_results if [ -f $TEMPFILE1 ] then rm -f $TEMPFILE1 fi TEMPFILE2=$WD/.gcov_info.txt if [ -f $TEMPFILE2 ] then rm -f $TEMPFILE2 fi TEMPFILE3=$WD/.percent if [ -f $TEMPFILE3 ] then rm -f $TEMPFILE3 fi export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$STACK_DIR echo "Running the unit tests for $TARGET..." echo "Results will be stored in: $RESULTS_FILE ...." #Build the library with coverage echo "Building Stack in $STACK_DIR" cd $STACK_DIR qmake make clean make coverage echo "tests directory is $TESTS_DIR" cd $TESTS_DIR qmake make clean make echo "Running the tests in $PWD" ./libmeegosyncml-tests > $TEMPFILE1 echo "Getting the Coverage Results" cd $STACK_DIR echo $PWD rm -f moc_* file_list=$(ls *.gcno) #echo "Printing File List :$file_list " for file in $file_list do echo "Running gcov on $file" gcov $file >> $TEMPFILE2 done # get coverage information for the files using perl echo "executing perl gcov_info.pl $TEMPFILE2 $TEMPFILE3" GCOV_REPORT=$WD/gcov_report.txt perl $WD/gcov_info.pl $TEMPFILE2 $TEMPFILE3 $GCOV_REPORT if [ ! $? -eq 0 ]; then # echo "Perl Script for gcov information exit normal" #else echo "Perl Script for gcov information Failed to execute ... Exiting ... " exit 0 fi SUMMARY_FILE=$WD/.summary_file if [ -f $SUMMARY_FILE ] then rm -f $SUMMARY_FILE fi perl $WD/test_info.pl $TEMPFILE1 $SUMMARY_FILE if [ ! $? -eq 0 ]; then #echo "Perl Script for test information exit normal" #else echo "Perl Script for test information Failed to execute ... Exiting ... " exit 0 fi echo "Writing the file $RESULTS_FILE" echo "#Results for $TARGET_WEEK " > $RESULTS_FILE echo "Results Summary STARTED " >> $RESULTS_FILE echo "#Current gcov reported coverage (line rate) is" >> $RESULTS_FILE cat $TEMPFILE3 >> $RESULTS_FILE echo "Unit test Results Summary " >> $RESULTS_FILE cat $SUMMARY_FILE >> $RESULTS_FILE echo "Results Summary ENDED " >> $RESULTS_FILE echo "(all unit tests are not refactored yet)" >> $RESULTS_FILE echo "#Coverage report is visible in $WD/gcov_report.txt" >> $RESULTS_FILE echo "****************UNIT_TEST Results **************" >> $RESULTS_FILE cat $TEMPFILE1 >> $RESULTS_FILE rm -f $TEMPFILE1 $TEMPFILE2 $TEMPFILE3 $SUMMARY_FILE cd $STACK_DIR rm -f *.gcno *.gcda *.gcov cd $WD echo "$RESULTS_FILE created" buteo-syncml-0.5.15/doc/coverage/test_info.pl000077500000000000000000000066051433763642500211410ustar00rootroot00000000000000#!/usr/bin/perl #/* #* This file is part of buteo-syncml package #* #* Copyright (C) 2010 Nokia Corporation. All rights reserved. #* #* Contact: Sateesh Kavuri #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are met: #* #* Redistributions of source code must retain the above copyright notice, #* this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #* this list of conditions and the following disclaimer in the documentation #* and/or other materials provided with the distribution. #* Neither the name of Nokia Corporation nor the names of its contributors may #* be used to endorse or promote products derived from this software without #* specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE #* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #* THE POSSIBILITY OF SUCH DAMAGE. #* #*/ # Author : Srikanth Kavoori # Not Tested fully yet. There could be some issues. # If you see any issues Let me know and i shall fix it :) open(INPUTFILE, "<$ARGV[0]"); # Totals: 0 passed, 2 failed, 0 skipped $tests_string = "Totals:"; $pass_count = 0; $fail_count = 0; $skip_count = 0; $total_count = 0; while() { my($line) = $_; if(/$tests_string/) { #print $line; #print "Found usr_include or header file on line $. \n" ; $pass_start_index = rindex($line,':') + 1; $passed_index = rindex($line,"passed") - 1; $length = $passed_index - $start_index; $pass_count += substr($line,$pass_start_index,$length); #print "pass_count $pass_count "; $fail_start_index = rindex($line,'passed,') + 8; $failed_index = rindex($line,"failed") - 1; $length = $failed_index - $fail_start_index; $fail_count += substr($line,$fail_start_index,$length); #print "fail_count $fail_count "; $skip_start_index = rindex($line,'failed,') + 8; $skipped_index = rindex($line,"skipped") - 1; $length = $failed_index - $skip_start_index; $skip_count += substr($line,$skip_start_index,$length); #print "skip_count $skip_count \n"; } } #if($filecount != 0 ) { # $coverage_percent=sprintf("%.2f",$coverage_percent/$filecount); #} $total_count += $pass_count + $fail_count + $skip_count; print "Total No. TESTS: $total_count \n"; print "Passed: $pass_count \n"; print "Failed: $fail_count \n"; print "Skipped: $skip_count \n"; open(SUMMARY_FILE,">$ARGV[1]"); print SUMMARY_FILE "" ; print SUMMARY_FILE "Total TESTS: $total_count \n"; print SUMMARY_FILE "Passed: $pass_count \n"; print SUMMARY_FILE "Failed: $fail_count \n"; print SUMMARY_FILE "Skipped: $skip_count \n"; close(SUMMARY_FILE); close(INPUTFILE); buteo-syncml-0.5.15/doc/doc.pri000066400000000000000000000005741433763642500162740ustar00rootroot00000000000000DOXYGEN_BIN = $$system(command -v doxygen) isEmpty(DOXYGEN_BIN):error("Unable to detect doxygen in PATH") doc.CONFIG = phony doc.commands = cd $${PWD} && $${DOXYGEN_BIN} Doxyfile QMAKE_EXTRA_TARGETS += doc QMAKE_CLEAN += $${PWD}/html/* $${PWD}/buteo-syncml.tag # Install rules htmldocs.files = $${PWD}/html/ htmldocs.path = /usr/share/doc/buteo-syncml-doc/ INSTALLS += htmldocs buteo-syncml-0.5.15/libbuteosyncml.pro000066400000000000000000000003211433763642500200110ustar00rootroot00000000000000include(doc/doc.pri) CONFIG += ordered \ qt \ thread # Directories SUBDIRS += src \ tests_meego QT += core # Make sure gui is not enabled. QT -= gui QTDIR = /usr/lib/qt4 TEMPLATE = subdirs buteo-syncml-0.5.15/rpm/000077500000000000000000000000001433763642500150365ustar00rootroot00000000000000buteo-syncml-0.5.15/rpm/buteo-syncml-qt5.spec000066400000000000000000000025001433763642500210370ustar00rootroot00000000000000Name: buteo-syncml-qt5 Version: 0.5.13 Release: 1 Summary: SyncML library for MeeGo sync License: LGPLv2+ URL: https://git.sailfishos.org/mer-core/buteo-syncml Source0: %{name}-%{version}.tar.gz BuildRequires: doxygen BuildRequires: pkgconfig(Qt5Core) BuildRequires: pkgconfig(Qt5XmlPatterns) BuildRequires: pkgconfig(Qt5Xml) BuildRequires: pkgconfig(Qt5Sql) BuildRequires: pkgconfig(Qt5Test) BuildRequires: pkgconfig(libwbxml2) >= 0.11.6 BuildRequires: pkgconfig(sqlite3) BuildRequires: pkgconfig(openobex) BuildRequires: pkgconfig(buteosyncfw5) >= 0.6.24 %description %{summary}. %files %defattr(-,root,root,-) %config %{_sysconfdir}/buteo/*.xsd %config %{_sysconfdir}/buteo/*.xml %{_libdir}/*.so.* %package devel Summary: Development files for %{name} Requires: %{name} = %{version}-%{release} %description devel %{summary}. %files devel %defattr(-,root,root,-) %{_includedir}/* %{_libdir}/*.so %{_libdir}/*.prl %{_libdir}/pkgconfig/*.pc %package tests Summary: Development files for %{name} Requires: %{name} = %{version}-%{release} %description tests %{summary}. %files tests %defattr(-,root,root,-) /opt/tests/%{name}/* %prep %setup -q %build %qmake5 "VERSION=%{version}" -recursive libbuteosyncml.pro make %{?_smp_mflags} %install make INSTALL_ROOT=%{buildroot} install %post -p /sbin/ldconfig %postun -p /sbin/ldconfig buteo-syncml-0.5.15/rpm/buteo-syncml.changes000066400000000000000000000023531433763642500210140ustar00rootroot00000000000000* Mon Sep 24 2012 Bernd Wachter - 0.5.0 - Update to nemo upstream, contributing to JB#2310 * Thu Sep 06 2012 Bernd Wachter - 0.4.18 - Update to latest upstream - Move tests to /opt/tests * Mon Jan 31 2011 Bernd Wachter - 0.4.10.7 - Update version, fixing BMC#13137 * Wed Jan 05 2011 Bernd Wachter - 0.4.10.2 - Update version, fixing BMC#11996 * Fri Dec 17 2010 Bernd Wachter - 0.4.9.52 - Update version, fixing BMC#11096 * Wed Nov 24 2010 Bernd Wachter - 0.4.9.47 - Update version, required for buteo-sync-plugins fixes from BME#3888 * Sun Oct 17 2010 Bernd Wachter - 0.4.9.38 - Update to latest version * Thu Sep 23 2010 Bernd Wachter - 0.4.9.35 - Update version, fixing BMC#6136 * Tue Aug 24 2010 Bernd Wachter - 0.4.9.28 - Update to latest version - Change BuildRequires to pkgconfig * Mon Jun 28 2010 Bernd Wachter - 0.4.9 - Update to latest version * Fri Jun 18 2010 Bernd Wachter - 0.4.6 - Initial RPM versionbuteo-syncml-0.5.15/src/000077500000000000000000000000001433763642500150275ustar00rootroot00000000000000buteo-syncml-0.5.15/src/AlertPackage.cpp000066400000000000000000000076011433763642500200620ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "AlertPackage.h" #include "SyncMLMessage.h" #include "SyncMLAlert.h" #include "SyncTarget.h" #include "SyncMode.h" #include "SyncMLLogging.h" using namespace DataSync; AlertPackage::AlertPackage( qint32 aAlertCode ) : iParams( CommandParams::COMMAND_ALERT) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iParams.data = QString::number( aAlertCode ); } AlertPackage::AlertPackage( qint32 aAlertCode, const QString& aSourceDatabase, const QString& aTargetDatabase ) : iParams( CommandParams::COMMAND_ALERT ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iParams.data = QString::number( aAlertCode ); ItemParams item; item.source = aSourceDatabase; item.target = aTargetDatabase; iParams.items.append(item); } AlertPackage::AlertPackage( qint32 aAlertCode, const QString& aSourceDatabase, const QString& aTargetDatabase, const QString& aLocalLastAnchor, const QString& aLocalNextAnchor ) : iParams( CommandParams::COMMAND_ALERT ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iParams.data = QString::number( aAlertCode ); ItemParams item; item.source = aSourceDatabase; item.target = aTargetDatabase; item.meta.anchor.last = aLocalLastAnchor; item.meta.anchor.next = aLocalNextAnchor; iParams.items.append(item); // This is needed for S60, do NOT remove // @todo: should this be here, or in session handling?? if( iParams.items.first().meta.anchor.last.isEmpty() ) { iParams.items.first().meta.anchor.last = '0'; } } AlertPackage::AlertPackage( const QString& aSourceDatabase, const QString& aMIMEType, qint32 aAlertCode ) : iParams( CommandParams::COMMAND_ALERT ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iParams.data = QString::number( aAlertCode ); ItemParams item; item.source = aSourceDatabase; item.meta.type = aMIMEType; iParams.items.append(item); } AlertPackage::~AlertPackage() { } bool AlertPackage::write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iParams.cmdId = aMessage.getNextCmdId(); SyncMLAlert* alertObject = new SyncMLAlert( iParams ); aMessage.addToBody( alertObject ); aSizeThreshold -= alertObject->calculateSize(aWBXML, aVersion); return true; } buteo-syncml-0.5.15/src/AlertPackage.h000066400000000000000000000073721433763642500175340ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef ALERTPACKAGE_H #define ALERTPACKAGE_H #include "Package.h" #include "Fragments.h" class AlertPackageTest; namespace DataSync { class SyncTarget; class SyncMode; /*! \brief Handles sending an Alert to remote side * */ class AlertPackage : public Package { Q_OBJECT; public: /*! \brief Constructor for Alerts that include only the alert code * */ AlertPackage( qint32 aAlertCode ); /*! \brief Constructor for Alert that includes source and target databases * * This should be used for example which Alerts related to suspend & resume and * requesting next messages * * @param aAlertCode Code of this Alert * @param aSourceDatabase Source database * @param aTargetDatabase Target database */ AlertPackage( qint32 aAlertCode, const QString& aSourceDatabase, const QString& aTargetDatabase ); /*! \brief Constructor for Alert that includes source/target databases and anchor information * * This should be used for Alerts related to sync modes * * @param aAlertCode Code of this Alert * @param aSourceDatabase Source database * @param aTargetDatabase Target database * @param aLocalLastAnchor Local last anchor * @param aLocalNextAnchor Local next anchor */ AlertPackage( qint32 aAlertCode, const QString& aSourceDatabase, const QString& aTargetDatabase, const QString& aLocalLastAnchor, const QString& aLocalNextAnchor ); /*! \brief Constructor for Alert that includes source database and MIME type * * This should be used for Alerts related to server initiated sync * * @param aSourceDatabase Source database * @param aMIMEType MIME type * @param aAlertCode Code of this Alert */ AlertPackage( const QString& aSourceDatabase, const QString& aMIMEType, qint32 aAlertCode ); /*! \brief Destructor * */ virtual ~AlertPackage(); virtual bool write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion); protected: private: CommandParams iParams; friend class ::AlertPackageTest; }; } #endif // ALERTPACKAGE_H buteo-syncml-0.5.15/src/AuthHelper.cpp000066400000000000000000000054661433763642500176070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "AuthHelper.h" #include #include "SyncMLLogging.h" using namespace DataSync; AuthHelper::AuthHelper() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } AuthHelper::~AuthHelper() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } QByteArray AuthHelper::encodeBasicB64Auth( const QString& aUsername, const QString& aPassword ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QByteArray in; in.append( aUsername ); in.append( ':' ); in.append( aPassword ); return in.toBase64(); } QByteArray AuthHelper::encodeMD5Auth( const QString& aUsername, const QString& aPassword, const QString& aNonce ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QByteArray in; in.append( aUsername.toUtf8() ); in.append( ':' ); in.append( aPassword.toUtf8() ); QByteArray tmp = toMD5( in ); tmp = tmp.toBase64(); tmp.append( ':' ); tmp.append( aNonce.toUtf8() ); return toMD5( tmp ); } QByteArray AuthHelper::toMD5( const QByteArray& aString ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QCryptographicHash md5Hash( QCryptographicHash::Md5 ); md5Hash.addData( aString ); return md5Hash.result(); } buteo-syncml-0.5.15/src/AuthHelper.h000066400000000000000000000054731433763642500172520ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef AUTHHELPER_H #define AUTHHELPER_H #include namespace DataSync { /*! \brief Utility class that is able to encode and decode SyncML basic and * md5 authentication */ class AuthHelper { public: /*! \brief Constructor * */ AuthHelper(); /*! \brief Destructor * */ virtual ~AuthHelper(); /*! \brief Encode SyncML basic base64-encoded authentication * * @param aUsername Username * @param aPassword Password * @return Encoded data */ QByteArray encodeBasicB64Auth( const QString& aUsername, const QString& aPassword ) const; /*! \brief Encode SyncML md5 authentication * * Note that this function does not automatically base64-encode the data, so it must be done * separately if the information is passed through clear-text protocol like XML * * @param aUsername Username * @param aPassword Password * @param aNonce Nonce to use * @return Encoded data */ QByteArray encodeMD5Auth( const QString& aUsername, const QString& aPassword, const QString& aNonce ) const; protected: private: QByteArray toMD5( const QByteArray& aString ) const; }; } #endif // AUTHHELPER_H buteo-syncml-0.5.15/src/AuthenticationPackage.cpp000066400000000000000000000063641433763642500217770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "AuthenticationPackage.h" #include "SyncMLCred.h" #include "SyncMLMessage.h" #include "AuthHelper.h" #include "datatypes.h" #include "SyncMLLogging.h" using namespace DataSync; AuthenticationPackage::AuthenticationPackage( const AuthType& aAuthType, const QString& aUsername, const QString& aPassword, const QByteArray& aNonce ) : iAuthType( aAuthType ), iUsername( aUsername ), iPassword( aPassword ), iNonce( aNonce ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } AuthenticationPackage::~AuthenticationPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool AuthenticationPackage::write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncMLCred* cred = NULL; AuthHelper helper; if( iAuthType == AUTH_BASIC ) { QByteArray data = helper.encodeBasicB64Auth( iUsername, iPassword ); cred = new SyncMLCred( SYNCML_FORMAT_ENCODING_B64, SYNCML_FORMAT_AUTH_BASIC, data ); } else if( iAuthType == AUTH_MD5 ) { QByteArray data = helper.encodeMD5Auth( iUsername, iPassword, iNonce ); // @todo: wouldn't necessarily have to B64-encode over WbXML data = data.toBase64(); cred = new SyncMLCred( SYNCML_FORMAT_ENCODING_B64, SYNCML_FORMAT_AUTH_MD5, data ); } else { Q_ASSERT( 0 ); } if(cred) { aMessage.addToHeader( cred ); aSizeThreshold -= cred->calculateSize(aWBXML, aVersion); } return true; } buteo-syncml-0.5.15/src/AuthenticationPackage.h000066400000000000000000000053311433763642500214350ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef AUTHENTICATIONPACKAGE_H #define AUTHENTICATIONPACKAGE_H #include "Package.h" #include "SyncAgentConsts.h" class AuthenticationPackageTest; namespace DataSync { /*! \brief Handles sync initialization phase authentication */ class AuthenticationPackage : public Package { Q_OBJECT public: /*! \brief Constructor * * @param aAuthType Type of authentication to use (either BASIC or MD5) * @param aUsername Username to use (BASIC and MD5) * @param aPassword Password to use (BASIC and MD5) * @param aNonce Nonce to use (MD5) */ AuthenticationPackage( const AuthType& aAuthType, const QString& aUsername, const QString& aPassword, const QByteArray& aNonce = "" ); /*! \brief Destructor * */ virtual ~AuthenticationPackage(); virtual bool write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ); protected: private: AuthType iAuthType; QString iUsername; QString iPassword; QByteArray iNonce; friend class ::AuthenticationPackageTest; }; } #endif // AUTHENTICATIONPACKAGE_H buteo-syncml-0.5.15/src/CTCap.cpp000066400000000000000000000037521433763642500164740ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "CTCap.h" using namespace DataSync; CTCap::CTCap() { } CTCap::~CTCap() { } void CTCap::setFormat( const ContentFormat& aFormat ) { iFormat = aFormat; } const ContentFormat& CTCap::getFormat() const { return iFormat; } const QList& CTCap::properties() const { return iProperties; } QList& CTCap::properties() { return iProperties; } buteo-syncml-0.5.15/src/CTCap.h000066400000000000000000000072571433763642500161450ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CTCAPS_H #define CTCAPS_H #include #include #include "StorageContentFormatInfo.h" namespace DataSync { /*! \brief Parameter of a property * */ struct CTCapParameter { QString iName; /*!< Name of the parameter*/ QString iType; /*!< Type of the parameter*/ QString iDisplayName; /*!< Human-readable name of the parameter*/ QList iValues; /*!< Allowed values for the parameter*/ }; /*! \brief CTCap property * */ struct CTCapProperty { QString iName; /*!< Name of the property*/ QString iType; /*!< Type of the property*/ int iMaxOccur; /*!< Maximum number of times this property can occur*/ int iSize; /*!< Maximum size of the property*/ bool iNoTruncate; /*!< Specifies whether this property can be truncated*/ QString iDisplayName; /*!< Human-readable name of the property*/ QList iValues; /*!< Allowed values for the property*/ QList iParameters; /*!< Parameters of the property*/ CTCapProperty() : iMaxOccur( -1 ), iSize( -1 ), iNoTruncate( false ) { } }; /*! \brief Describes single content format and its properties * */ class CTCap { public: /*! \brief Constructor * */ CTCap(); /*! \brief Destructor * */ ~CTCap(); /*! \brief Set content format * * @param aFormat Content format */ void setFormat( const ContentFormat& aFormat ); /*! \brief Returns content format * * @return */ const ContentFormat& getFormat() const; /*! \brief Returns properties * * @return */ const QList& properties() const; /*! \brief Returns properties * * @return */ QList& properties(); private: ContentFormat iFormat; /*!< Format*/ QList iProperties; /*!< Properties*/ }; } #endif // CTCAPS_H buteo-syncml-0.5.15/src/ChangeLog.cpp000066400000000000000000000351551433763642500173730ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ChangeLog.h" #include #include "SyncMLLogging.h" using namespace DataSync; ChangeLog::ChangeLog( const QString& aRemoteDevice, const QString& aSourceDbURI, SyncDirection aSyncDirection ) : iRemoteDevice( aRemoteDevice ), iSourceDbURI( aSourceDbURI ), iSyncDirection( aSyncDirection ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } ChangeLog::~ChangeLog() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool ChangeLog::load( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Loading changelog information:"; qCDebug(lcSyncML) << "Remote device:" << iRemoteDevice; qCDebug(lcSyncML) << "Database URI:" << iSourceDbURI; qCDebug(lcSyncML) << "Sync direction:" << iSyncDirection; return ( loadAnchors( aDbHandle ) && loadMaps( aDbHandle ) ); } bool ChangeLog::load( const QString& aDbName ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; QString connectionName = generateConnectionName(); QSqlDatabase database = QSqlDatabase::addDatabase( "QSQLITE", connectionName ); database.setDatabaseName( aDbName ); if( database.open() ) { success = load( database ); database.close(); } else { qCCritical(lcSyncML) << "Could not open database!"; } database = QSqlDatabase(); QSqlDatabase::removeDatabase( connectionName ); return success; } bool ChangeLog::save( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Saving changelog information:"; qCDebug(lcSyncML) << "Remote device:" << iRemoteDevice; qCDebug(lcSyncML) << "Database URI:" << iSourceDbURI; qCDebug(lcSyncML) << "Sync direction:" << iSyncDirection; if( !ensureAnchorDatabase( aDbHandle ) || !ensureMapsDatabase( aDbHandle ) ) { return false; } bool transaction = aDbHandle.transaction(); bool success = ( saveAnchors( aDbHandle ) && saveMaps( aDbHandle ) ); if( transaction && ( !success || !aDbHandle.commit() ) ) { success = false; aDbHandle.rollback(); } return success; } bool ChangeLog::save( const QString& aDbName ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; QString connectionName = generateConnectionName(); QSqlDatabase database = QSqlDatabase::addDatabase( "QSQLITE", connectionName ); database.setDatabaseName( aDbName ); if( database.open() ) { success = save( database ); database.close(); } else { qCCritical(lcSyncML) << "Could not open database!"; } database = QSqlDatabase(); QSqlDatabase::removeDatabase( connectionName ); return success; } bool ChangeLog::remove( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Removing changelog information:"; qCDebug(lcSyncML) << "Remote device:" << iRemoteDevice; qCDebug(lcSyncML) << "Database URI:" << iSourceDbURI; qCDebug(lcSyncML) << "Sync direction:" << iSyncDirection; return ( removeAnchors( aDbHandle ) && removeMaps( aDbHandle ) ); } bool ChangeLog::remove( const QString& aDbName ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; QString connectionName = generateConnectionName(); QSqlDatabase database = QSqlDatabase::addDatabase( "QSQLITE", connectionName ); database.setDatabaseName( aDbName ); if( database.open() ) { success = remove( database ); database.close(); } else { qCCritical(lcSyncML) << "Could not open database!"; } database = QSqlDatabase(); QSqlDatabase::removeDatabase( connectionName ); return success; } const QString& ChangeLog::getLastLocalAnchor() const { return iLastLocalAnchor; } void ChangeLog::setLastLocalAnchor( const QString& aLastLocalAnchor ) { iLastLocalAnchor = aLastLocalAnchor; } const QString& ChangeLog::getLastRemoteAnchor() const { return iLastRemoteAnchor; } void ChangeLog::setLastRemoteAnchor( const QString& aLastRemoteAnchor ) { iLastRemoteAnchor = aLastRemoteAnchor; } const QDateTime& ChangeLog::getLastSyncTime() const { return iLastSyncTime; } void ChangeLog::setLastSyncTime( const QDateTime& aLastSyncTime ) { iLastSyncTime = aLastSyncTime; } const QList& ChangeLog::getMaps() const { return iMaps; } void ChangeLog::setMaps( const QList& aMaps ) { iMaps = aMaps; } QString ChangeLog::generateConnectionName() { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString CONNECTIONNAME( "changelog" ); static unsigned connectionNumber = 0; return CONNECTIONNAME + QString::number( connectionNumber++ ); } bool ChangeLog::ensureAnchorDatabase( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString( "CREATE TABLE if not exists change_logs(id integer primary key autoincrement, remote_device varchar(512), source_db_uri varchar(512), sync_direction INTEGER, local_sync_anchor varchar(128), remote_sync_anchor varchar(128), last_sync_time timestamp)" ); QSqlQuery query( queryString, aDbHandle ); if( query.exec() ) { return true; } else { qCCritical(lcSyncML) << "Could not ensure anchor database table:" << query.lastError(); return false; } } bool ChangeLog::ensureMapsDatabase( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString( "CREATE TABLE IF NOT EXISTS id_maps(id integer primary key autoincrement, remote_device varchar(512), source_db_uri varchar(512), sync_direction INTEGER, local_id varchar(128), remote_id varchar(128))" ); QSqlQuery query( queryString, aDbHandle ); if( query.exec() ) { return true; } else { qCCritical(lcSyncML) << "Could not ensure ID maps database table:" << query.lastError(); return false; } } bool ChangeLog::loadAnchors( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool loaded = false; const QString queryString( "SELECT local_sync_anchor, remote_sync_anchor, last_sync_time FROM change_logs WHERE remote_device = :remote_device AND source_db_uri = :source_db_uri AND sync_direction = :sync_direction" ); QSqlQuery query( queryString, aDbHandle ); query.prepare( queryString ); query.bindValue( ":remote_device", iRemoteDevice ); query.bindValue( ":source_db_uri", iSourceDbURI ); query.bindValue( ":sync_direction", iSyncDirection ); if( query.exec() ) { if( query.next() ) { iLastLocalAnchor = query.value(0).toString(); iLastRemoteAnchor = query.value(1).toString(); iLastSyncTime = query.value(2).toDateTime(); qCDebug(lcSyncML) << "Found anchor information:"; qCDebug(lcSyncML) << "Last local anchor:" << iLastLocalAnchor; qCDebug(lcSyncML) << "Last remote anchor:" << iLastRemoteAnchor; qCDebug(lcSyncML) << "Sync session end time:" << iLastSyncTime; loaded = true; } else { qCDebug(lcSyncML) << "No existing anchor entry found from database, creating new"; } } else { qCWarning(lcSyncML) << "Could not load anchors:" << query.lastError(); } return loaded; } bool ChangeLog::saveAnchors( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; if( removeAnchors( aDbHandle ) ) { const QString queryString( "INSERT INTO change_logs(remote_device, source_db_uri, sync_direction, local_sync_anchor, remote_sync_anchor, last_sync_time) VALUES (:remote_device, :source_db_uri, :sync_direction, :local_sync_anchor, :remote_sync_anchor, :last_sync_time)" ); QSqlQuery query( queryString, aDbHandle ); query.prepare( queryString ); query.bindValue( ":remote_device", iRemoteDevice ); query.bindValue( ":source_db_uri", iSourceDbURI ); query.bindValue( ":sync_direction", iSyncDirection ); query.bindValue( ":local_sync_anchor", iLastLocalAnchor ); query.bindValue( ":remote_sync_anchor", iLastRemoteAnchor ); query.bindValue( ":last_sync_time", iLastSyncTime ); if( query.exec() ) { qCDebug(lcSyncML) << "Anchor information saved:"; qCDebug(lcSyncML) << "Last local anchor:" << iLastLocalAnchor; qCDebug(lcSyncML) << "Last remote anchor:" << iLastRemoteAnchor; qCDebug(lcSyncML) << "Sync session end time:" << iLastSyncTime; success = true; } else { qCCritical(lcSyncML) << "Could not save anchors:" << query.lastError(); } } else { qCCritical(lcSyncML) << "Could not save anchors as database cleaning failed"; } return success; } bool ChangeLog::removeAnchors( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; QStringList tables = aDbHandle.tables(); if( !tables.contains("change_logs") ) { qCDebug(lcSyncML) << "Change logs table not present. Considering anchors as removed"; success = true; } else { const QString queryString( "DELETE FROM change_logs WHERE remote_device = :remote_device AND source_db_uri = :source_db_uri AND sync_direction = :sync_direction" ); QSqlQuery query( queryString, aDbHandle ); query.prepare( queryString ); query.bindValue( ":remote_device", iRemoteDevice ); query.bindValue( ":source_db_uri", iSourceDbURI ); query.bindValue( ":sync_direction", iSyncDirection ); if( query.exec() ) { success = true; } else { qCWarning(lcSyncML) << "Could not remove anchors:" << query.lastError(); } } return success; } bool ChangeLog::loadMaps( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool loaded = false; const QString queryString("SELECT local_id, remote_id FROM id_maps WHERE remote_device = :remote_device AND source_db_uri = :source_db_uri AND sync_direction = :sync_direction" ); QSqlQuery query( queryString, aDbHandle ); query.prepare( queryString ); query.bindValue( ":remote_device", iRemoteDevice ); query.bindValue( ":source_db_uri", iSourceDbURI ); query.bindValue( ":sync_direction", iSyncDirection ); if( query.exec() ) { iMaps.clear(); while( query.next() ) { UIDMapping mapping; mapping.iLocalUID = query.value(0).toString(); mapping.iRemoteUID = query.value(1).toString(); iMaps.append( mapping ); } loaded = true; } else { qCCritical(lcSyncML) << "Could not load ID maps:" << query.lastError(); } return loaded; } bool ChangeLog::saveMaps( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; if( removeMaps( aDbHandle ) ) { const QString queryString( "INSERT INTO id_maps(remote_device, source_db_uri, sync_direction, local_id, remote_id) values(:remote_device, :source_db_uri, :sync_direction, :local_id, :remote_id)" ); QSqlQuery query( queryString, aDbHandle ); query.prepare( queryString ); QVariantList device; QVariantList sourceDbURI; QVariantList syncDirection; QVariantList localId; QVariantList remoteId; for( int i = 0; i < iMaps.count(); ++i ) { device << iRemoteDevice; sourceDbURI << iSourceDbURI; syncDirection << iSyncDirection; localId << iMaps[i].iLocalUID; remoteId << iMaps[i].iRemoteUID; } query.addBindValue( device ); query.addBindValue( sourceDbURI ); query.addBindValue( syncDirection ); query.addBindValue( localId ); query.addBindValue( remoteId ); if( query.execBatch() ) { qCDebug(lcSyncML) << "ID maps information saved"; success = true; } else { qCWarning(lcSyncML) << "Query failed: " << query.lastError(); } } else { qCCritical(lcSyncML) << "Could not save ID maps as database cleaning failed"; } return success; } bool ChangeLog::removeMaps( QSqlDatabase& aDbHandle ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; QStringList tables = aDbHandle.tables(); if( !tables.contains("id_maps") ) { qCDebug(lcSyncML) << "id maps table not present"; success = true; } else { const QString queryString( "DELETE FROM id_maps WHERE remote_device = :remote_device AND source_db_uri = :source_db_uri AND sync_direction = :sync_direction" ); QSqlQuery query( queryString, aDbHandle ); query.prepare( queryString ); query.bindValue( ":remote_device", iRemoteDevice ); query.bindValue( ":source_db_uri", iSourceDbURI ); query.bindValue( ":sync_direction", iSyncDirection ); if( query.exec() ) { success = true; } else { qCWarning(lcSyncML) << "Could not remove ID maps:" << query.lastError(); } } return success; } buteo-syncml-0.5.15/src/ChangeLog.h000066400000000000000000000132301433763642500170260ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CHANGELOG_H #define CHANGELOG_H #include #include #include "SyncAgentConsts.h" #include "SyncMLGlobals.h" class QSqlDatabase; namespace DataSync { /*! \brief Stores the sync anchors and changes of different sync profiles. * */ class ChangeLog { public: /*! \brief Constructor * * @param aRemoteDevice Remote device * @param aSourceDbURI URI of the local database * @param aSyncDirection Direction of the sync */ ChangeLog( const QString& aRemoteDevice, const QString& aSourceDbURI, SyncDirection aSyncDirection ); /*! \brief Destructor * */ ~ChangeLog(); /*! \brief Loads change log information from database * * @param aDbHandle Database handle to use * @return True on success, otherwise false */ bool load( QSqlDatabase& aDbHandle ); /*! \brief Loads change log information from database * * @param aDbName Name of the database file to open * @return True on success, otherwise false */ bool load( const QString& aDbName ); /*! \brief Saves change log information to database * * @param aDbHandle Database handle to use * @return True on success, otherwise false */ bool save( QSqlDatabase& aDbHandle ); /*! \brief Saves change log information to database * * @param aDbName Name of the database file to open * @return True on success, otherwise false */ bool save( const QString& aDbName ); /*! \brief Removes change log information from database * * @param aDbHandle Database handle to use * @return True on success, otherwise false */ bool remove( QSqlDatabase& aDbHandle ); /*! \brief Removes change log information from database * * @param aDbName Name of the database file to open * @return True on success, otherwise false */ bool remove( const QString& aDbName ); /*! \brief Gets the last local anchor of previous successful synchronization * * @return Last local anchor if found, otherwise empty */ const QString& getLastLocalAnchor() const; /*! \brief Sets the last local anchor * * @param aLastLocalAnchor Last local anchor to set */ void setLastLocalAnchor( const QString& aLastLocalAnchor ); /*! \brief Gets the last remote anchor of previous successful synchronization * * @return Last remote anchor if found, otherwise empty */ const QString& getLastRemoteAnchor() const; /*! \brief Sets the last remote anchor * * @param aLastRemoteAnchor Last remote anchor to set */ void setLastRemoteAnchor( const QString& aLastRemoteAnchor ); /*! \brief Returns the time when last sync was completed * * @return Last sync time */ const QDateTime& getLastSyncTime() const; /*! \brief Stores the time when last sync was completed * * @param aLastSyncTime Last sync time * @return Operation status code */ void setLastSyncTime( const QDateTime& aLastSyncTime ); /*! \brief Returns the ID mappings associated with this ChangeLog * * @return */ const QList& getMaps() const; /*! \brief Sets the ID mappings associated with this ChangeLog * * @return */ void setMaps( const QList& aMaps ); private: QString generateConnectionName(); bool ensureAnchorDatabase( QSqlDatabase& aDbHandle ); bool ensureMapsDatabase( QSqlDatabase& aDbHandle ); bool loadAnchors( QSqlDatabase& aDbHandle ); bool saveAnchors( QSqlDatabase& aDbHandle ); bool removeAnchors( QSqlDatabase& aDbHandle ); bool loadMaps( QSqlDatabase& aDbHandle ); bool saveMaps( QSqlDatabase& aDbHandle ); bool removeMaps( QSqlDatabase& aDbHandle ); QString iRemoteDevice; QString iSourceDbURI; SyncDirection iSyncDirection; QString iLastLocalAnchor; QString iLastRemoteAnchor; QDateTime iLastSyncTime; QList iMaps; }; } #endif buteo-syncml-0.5.15/src/CommandHandler.cpp000066400000000000000000000664421433763642500204230ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "CommandHandler.h" #include "StorageHandler.h" #include "SyncTarget.h" #include "SyncMLLogging.h" #include "SyncAgentConfig.h" #include "ResponseGenerator.h" #include "ConflictResolver.h" #include "DevInfPackage.h" #include "AlertPackage.h" #include "LocalMappingsPackage.h" using namespace DataSync; CommandHandler::CommandHandler( const Role& aRole ) : iRole( aRole ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } CommandHandler::~CommandHandler() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } ResponseStatusCode CommandHandler::handleMap( const MapParams& aMapParams, SyncTarget& aTarget ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); UIDMapping mapping; for( int i = 0; i < aMapParams.mapItems.count(); ++i ) { mapping.iRemoteUID = aMapParams.mapItems[i].source; mapping.iLocalUID = aMapParams.mapItems[i].target; aTarget.addUIDMapping( mapping ); } return SUCCESS; } void CommandHandler::handleSync( const SyncParams& aSyncParams, SyncTarget& aTarget, StorageHandler& aStorageHandler, ResponseGenerator& aResponseGenerator, ConflictResolver& aConflictResolver, bool aFastMapsSend ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !aSyncParams.noResp ) { aResponseGenerator.addStatus( aSyncParams, SUCCESS ); } QMap responses; composeBatches( aSyncParams, aTarget, aStorageHandler, aResponseGenerator, responses ); QList newMappings; commitBatches( aStorageHandler, aConflictResolver, aTarget, aSyncParams, responses, newMappings ); processResults( aSyncParams, responses, aResponseGenerator ); manageNewMappings( aTarget, newMappings, aResponseGenerator, aFastMapsSend ); } void CommandHandler::rejectSync( const SyncParams& aSyncParams, ResponseGenerator& aResponseGenerator, ResponseStatusCode aResponseCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !aSyncParams.noResp ) { aResponseGenerator.addStatus( aSyncParams, aResponseCode ); } for( int i = 0; i < aSyncParams.commands.count(); ++i ) { rejectCommand( aSyncParams.commands[i], aResponseGenerator, aResponseCode ); } } void CommandHandler::rejectCommand( const CommandParams& aCommand, ResponseGenerator& aResponseGenerator, ResponseStatusCode aResponseCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !aCommand.noResp ) { aResponseGenerator.addStatus( aCommand, aResponseCode, true ); } for( int i = 0; i < aCommand.subCommands.count(); ++i ) { rejectCommand( aCommand.subCommands[i], aResponseGenerator, aResponseCode ); } } void CommandHandler::handleStatus(StatusParams* aStatusParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode statusCode; StatusCodeType statusType; if (aStatusParams != NULL) statusCode = aStatusParams->data; else return; statusType = getStatusType(statusCode); switch (statusType) { case INFORMATIONAL: { // an informational message, no actions needed break; } case SUCCESSFUL: { // Success, no actions needed break; } case REDIRECTION: { handleRedirection( statusCode ); break; } case ORIGINATOR_EXCEPTION: case RECIPIENT_EXCEPTION: { handleError(statusCode); break; } default: { // Unknown code qCDebug(lcSyncML) << "Found unknown code: " << statusCode; break; } } if ( aStatusParams->cmd == SYNCML_ELEMENT_ADD || aStatusParams->cmd == SYNCML_ELEMENT_REPLACE || aStatusParams->cmd == SYNCML_ELEMENT_DELETE ) { emit itemAcknowledged( aStatusParams->msgRef, aStatusParams->cmdRef, aStatusParams->sourceRef ); } } void CommandHandler::handleError( ResponseStatusCode aErrorCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); StatusCodeType statusType = getStatusType( aErrorCode ); if (statusType == ORIGINATOR_EXCEPTION) { switch (aErrorCode) { case ALREADY_EXISTS: { // This merely an informational error that can happen e.g // during slow sync. No need to abort the session. break; } default: { emit abortSync(aErrorCode); break; } } } else if (statusType == RECIPIENT_EXCEPTION) { if (aErrorCode == REFRESH_REQUIRED) { /// @todo init resresh sync } else { emit abortSync(aErrorCode); } } } StatusCodeType CommandHandler::getStatusType(ResponseStatusCode aStatus) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const int informationalLowBound = 100; const int informationalHighBound = 199; const int succesfullLowBound = 200; const int successfullHighBound = 299; const int redirectionLowBound = 300; const int redirectionHighBound = 399; const int originatorExceptionLowBound = 400; const int originatorExceptionHighBound = 499; const int recipientExceptionLowBound = 500; const int recipientExceptionHighBound = 599; StatusCodeType statusType = UNKNOWN; if (aStatus >= informationalLowBound && aStatus < informationalHighBound) { statusType = INFORMATIONAL; } else if (aStatus >= succesfullLowBound && aStatus < successfullHighBound) { statusType = SUCCESSFUL; } else if (aStatus >= redirectionLowBound && aStatus < redirectionHighBound) { statusType = REDIRECTION; } else if (aStatus >= originatorExceptionLowBound && aStatus < originatorExceptionHighBound) { statusType = ORIGINATOR_EXCEPTION; } else if (aStatus >= recipientExceptionLowBound && aStatus < recipientExceptionHighBound) { statusType = RECIPIENT_EXCEPTION; } else { statusType = UNKNOWN; } return statusType; } bool CommandHandler::resolveConflicts() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iRole == ROLE_CLIENT ) { // At the moment, do not try to resolve conflicts on the client side return false; } else { // Server should resolve conflicts return true; } } ResponseStatusCode CommandHandler::handleRedirection(ResponseStatusCode /*aRedirectionCode*/) { FUNCTION_CALL_TRACE(lcSyncMLTrace); return NOT_IMPLEMENTED; } void CommandHandler::composeBatches( const SyncParams& aSyncParams, SyncTarget& aTarget, StorageHandler& aStorageHandler, ResponseGenerator& aResponseGenerator, QMap& aResponses ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Batch updates for( int i = 0; i < aSyncParams.commands.count(); ++i ) { const CommandParams& data = aSyncParams.commands[i]; QString defaultType = data.meta.type; QString defaultFormat = data.meta.format; // Process items associated with the command for( int a = 0; a < data.items.count(); ++a ) { const ItemParams& item = data.items[a]; // Resolve id of the item ItemId id; id.iCmdId = data.cmdId; id.iItemIndex = a; // Resolve type of the item QString type; if( !item.meta.type.isEmpty() ) { type = item.meta.type; } else { type = defaultType; } // Resolve format of the item QString format; if( !item.meta.format.isEmpty() ) { format = item.meta.format; } else { format = defaultFormat; } // Get the version of the item QString version = item.meta.version; if( data.commandType == CommandParams::COMMAND_ADD ) { // Resolve item key QString remoteKey = item.source; // Resolve parent QString parentKey; if( iRole == ROLE_CLIENT ) { // Client might receive SourceParent or TargetParent. SourceParent is used // when server does not yet know the id of parent. TargetParent is used if // server knows the id of the parent. if( !item.sourceParent.isEmpty() ) { parentKey = aTarget.mapToLocalUID( item.sourceParent ); } else { parentKey = item.targetParent; } } else if( iRole == ROLE_SERVER && !item.sourceParent.isEmpty() ) { // Server always receives SourceParent, which must be mapped to local id parentKey = aTarget.mapToLocalUID( item.sourceParent ); } // no else qCDebug(lcSyncML) << "Processing ADD with item URL:" << remoteKey; // Large object chunk if( item.moreData ) { // First chunk of large object if( !aStorageHandler.buildingLargeObject() ) { // Size needs to be specified for first chunk if( item.meta.size == 0 ) { qCWarning(lcSyncML) << "No size found for large object:" << id.iCmdId <<"/" << id.iItemIndex; } if( !aStorageHandler.startLargeObjectAdd( *aTarget.getPlugin(), remoteKey, parentKey, type, format, version, item.meta.size ) ) { aResponses.insert( id, COMMAND_FAILED ); } } if( aStorageHandler.buildingLargeObject() ) { if( aStorageHandler.appendLargeObjectData( item.data ) ) { aResponseGenerator.addPackage( new AlertPackage( NEXT_MESSAGE, aTarget.getSourceDatabase(), aTarget.getTargetDatabase() ) ); aResponses.insert( id, CHUNKED_ITEM_ACCEPTED ); } else { aResponses.insert( id, COMMAND_FAILED ); } } } // Last chunk of large object else if( aStorageHandler.buildingLargeObject() ) { if( !aStorageHandler.matchesLargeObject( remoteKey ) ) { aResponseGenerator.addPackage( new AlertPackage( NO_END_OF_DATA, aTarget.getSourceDatabase(), aTarget.getTargetDatabase() ) ); aResponses.insert( id, COMMAND_NOT_ALLOWED ); } else if( aStorageHandler.appendLargeObjectData( item.data ) ) { if( !aStorageHandler.finishLargeObject( id ) ) { aResponses.insert( id, COMMAND_FAILED ); } } else { aResponses.insert( id, COMMAND_FAILED ); } } // Normal object else if( !aStorageHandler.addItem( id, *aTarget.getPlugin(), QString(), parentKey, type, format, version, item.data ) ) { aResponses.insert( id, COMMAND_FAILED ); } } else if( data.commandType == CommandParams::COMMAND_REPLACE ) { // Resolve item key QString localKey; if( iRole == ROLE_CLIENT ) { localKey = item.target; } else { localKey = aTarget.mapToLocalUID( item.source ); } // Resolve parent QString parentKey; if( iRole == ROLE_CLIENT ) { // Client might receive SourceParent or TargetParent. SourceParent is used // when server does not yet know the id of parent. TargetParent is used if // server knows the id of the parent. if( !item.sourceParent.isEmpty() ) { parentKey = aTarget.mapToLocalUID( item.sourceParent ); } else { parentKey = item.targetParent; } } else if( iRole == ROLE_SERVER ) { // Server always receives SourceParent, which must be mapped to local id parentKey = aTarget.mapToLocalUID( item.sourceParent ); } // no else qCDebug(lcSyncML) << "Processing REPLACE with item URL:" << localKey; // Large object chunk if( item.moreData ) { // First chunk of large object if( !aStorageHandler.buildingLargeObject() ) { // Size needs to be specified for first chunk if( item.meta.size == 0 ) { qCDebug(lcSyncML) << "No size found for large object:" << id.iCmdId <<"/" << id.iItemIndex; } if( !aStorageHandler.startLargeObjectReplace( *aTarget.getPlugin(), localKey, parentKey, type, format, version, item.meta.size ) ) { aResponses.insert( id, COMMAND_FAILED ); } } if( aStorageHandler.buildingLargeObject() ) { if( aStorageHandler.appendLargeObjectData( item.data.toUtf8() ) ) { aResponseGenerator.addPackage( new AlertPackage( NEXT_MESSAGE, aTarget.getSourceDatabase(), aTarget.getTargetDatabase() ) ); aResponses.insert( id, CHUNKED_ITEM_ACCEPTED ); } else { aResponses.insert( id, COMMAND_FAILED ); } } } // Last chunk of large object else if( aStorageHandler.buildingLargeObject() ) { if( !aStorageHandler.matchesLargeObject( localKey ) ) { aResponseGenerator.addPackage( new AlertPackage( NO_END_OF_DATA, aTarget.getSourceDatabase(), aTarget.getTargetDatabase() ) ); aResponses.insert( id, COMMAND_NOT_ALLOWED ); } else if( aStorageHandler.appendLargeObjectData( item.data ) ) { if( !aStorageHandler.finishLargeObject( id ) ) { aResponses.insert( id, COMMAND_FAILED ); } } else { aResponses.insert( id, COMMAND_FAILED ); } } // Normal object else if( !aStorageHandler.replaceItem( id, *aTarget.getPlugin(), localKey, parentKey, type, format, version, item.data ) ) { aResponses.insert( id, COMMAND_FAILED ); } } else if( data.commandType == CommandParams::COMMAND_DELETE ) { // Resolve item key QString localKey; if( iRole == ROLE_CLIENT ) { localKey = item.target; } else { localKey = aTarget.mapToLocalUID( item.source ); } qCDebug(lcSyncML) << "Processing REPLACE with item URL:" << localKey; if( !aStorageHandler.deleteItem( id, localKey ) ) { aResponses.insert( id, COMMAND_FAILED ); } } else { // @todo: This is OK if we receive Copy/Move inside Sync, but what about // Atomic/Sequence, should we also send status about the subcommands? aResponses.insert( id, NOT_IMPLEMENTED ); } } } } void CommandHandler::commitBatches( StorageHandler& aStorageHandler, ConflictResolver& aConflictResolver, SyncTarget& aTarget, const SyncParams& aSyncParams, QMap& aResponses, QList& aNewMappings ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Commit batches QMap results; ConflictResolver* resolver = NULL; if( resolveConflicts() ) { resolver = &aConflictResolver; } else { resolver = NULL; } results.unite( aStorageHandler.commitAddedItems( *aTarget.getPlugin(), resolver ) ); results.unite( aStorageHandler.commitReplacedItems( *aTarget.getPlugin(), resolver ) ); results.unite( aStorageHandler.commitDeletedItems( *aTarget.getPlugin(), resolver ) ); // Process commit results and convert them to result codes for( int i = 0; i < aSyncParams.commands.count(); ++i ) { const CommandParams& data = aSyncParams.commands[i]; // Process items associated with the command for( int a = 0; a < data.items.count(); ++a ) { const ItemParams& item = data.items[a]; ItemId id; id.iCmdId = data.cmdId; id.iItemIndex = a; if( !aResponses.contains( id ) ) { if( results.contains( id ) ) { ResponseStatusCode statusCode = COMMAND_FAILED; const CommitResult& result = results.value( id ); if( result.iStatus == COMMIT_ADDED || result.iStatus == COMMIT_INIT_ADD) { if( result.iConflict == CONFLICT_LOCAL_WIN ) { if( iRole == ROLE_CLIENT ) { statusCode = RESOLVED_CLIENT_WINNING; } else { statusCode = RESOLVED_WITH_SERVER_DATA; } } else if( result.iConflict == CONFLICT_REMOTE_WIN ) { if( iRole == ROLE_CLIENT ) { statusCode = RESOLVED_WITH_SERVER_DATA; } else { statusCode = RESOLVED_CLIENT_WINNING; } } else { statusCode = ITEM_ADDED; } UIDMapping map; map.iRemoteUID = item.source; map.iLocalUID = result.iItemKey; aNewMappings.append( map ); } else if( result.iStatus == COMMIT_REPLACED || result.iStatus == COMMIT_INIT_REPLACE ) { if( result.iConflict == CONFLICT_LOCAL_WIN ) { if( iRole == ROLE_CLIENT ) { statusCode = RESOLVED_CLIENT_WINNING; } else { statusCode = RESOLVED_WITH_SERVER_DATA; } } else if( result.iConflict == CONFLICT_REMOTE_WIN ) { if( iRole == ROLE_CLIENT ) { statusCode = RESOLVED_WITH_SERVER_DATA; } else { statusCode = RESOLVED_CLIENT_WINNING; } } else { statusCode = SUCCESS; } } else if( result.iStatus == COMMIT_DELETED || result.iStatus == COMMIT_INIT_DELETE ) { if( result.iConflict == CONFLICT_LOCAL_WIN ) { if( iRole == ROLE_CLIENT ) { statusCode = RESOLVED_CLIENT_WINNING; } else { statusCode = RESOLVED_WITH_SERVER_DATA; } } else if( result.iConflict == CONFLICT_REMOTE_WIN ) { aTarget.removeUIDMapping( result.iItemKey ); if( iRole == ROLE_CLIENT ) { statusCode = RESOLVED_WITH_SERVER_DATA; } else { statusCode = RESOLVED_CLIENT_WINNING; } } else { aTarget.removeUIDMapping( result.iItemKey ); statusCode = SUCCESS; } } else if( result.iStatus == COMMIT_DUPLICATE ) { statusCode = ALREADY_EXISTS; } else if( result.iStatus == COMMIT_NOT_DELETED ) { statusCode = ITEM_NOT_DELETED; aTarget.removeUIDMapping( result.iItemKey ); } else if( result.iStatus == COMMIT_UNSUPPORTED_FORMAT ) { statusCode = UNSUPPORTED_FORMAT; } else if( result.iStatus == COMMIT_ITEM_TOO_BIG ) { statusCode = REQUEST_SIZE_TOO_BIG; } else if( result.iStatus == COMMIT_NOT_ENOUGH_SPACE ) { statusCode = DEVICE_FULL; } else { statusCode = COMMAND_FAILED; } aResponses.insert( id, statusCode ); } else { aResponses.insert( id, COMMAND_FAILED ); } } } } } void CommandHandler::processResults( const SyncParams& aSyncParams, const QMap& aResponses, ResponseGenerator& aResponseGenerator ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Process result codes and write corresponding status elements for( int i = 0; i < aSyncParams.commands.count(); ++i ) { const CommandParams& command = aSyncParams.commands[i]; if( command.noResp ) { continue; } QMultiMap responses; // Process items associated with the command for( int a = 0; a < command.items.count(); ++a ) { ItemId id; id.iCmdId = command.cmdId; id.iItemIndex = a; responses.insert( aResponses.value( id ), a ); } QList codes = responses.uniqueKeys(); for( int b = 0; b < codes.count(); ++b ) { QList itemIndexes = responses.values( codes[b] ); // values() returns items sorted by most recently added, so we need to // reverse the list QList reverseIndexes; QListIterator iterator( itemIndexes ); for( iterator.toBack(); iterator.hasPrevious(); ) { reverseIndexes.append( iterator.previous() ); } aResponseGenerator.addStatus( command, codes[b], reverseIndexes ); } } } void CommandHandler::manageNewMappings( SyncTarget& aTarget, const QList& aNewMappings, ResponseGenerator& aResponseGenerator, bool aFastMapsSend ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Manage new mappings: Save them to persistent storage. Also if we are acting as a client // and we have been configured to fast-send mappings, compose LocalMappingsPackage for( int i = 0; i < aNewMappings.size(); ++i ) { aTarget.addUIDMapping( aNewMappings[i] ); } if ( (iRole == ROLE_CLIENT) && (aFastMapsSend) && (aNewMappings.size() > 0) ) { LocalMappingsPackage* localMappingsPackage = new LocalMappingsPackage( aTarget.getSourceDatabase(), aTarget.getTargetDatabase(), aNewMappings ); aResponseGenerator.addPackage( localMappingsPackage ); } } buteo-syncml-0.5.15/src/CommandHandler.h000066400000000000000000000161371433763642500200640ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef COMMANDHANDLER_H #define COMMANDHANDLER_H #include #include "SyncMLGlobals.h" #include "SyncAgentConsts.h" #include "StorageHandler.h" #include "datatypes.h" namespace DataSync { /*! \brief SyncML Status code groups * */ enum StatusCodeType { UNKNOWN, INFORMATIONAL, SUCCESSFUL, REDIRECTION, ORIGINATOR_EXCEPTION, RECIPIENT_EXCEPTION }; class SyncTarget; class StoragePlugin; class StorageHandler; class ResponseGenerator; class ConflictResolver; class DeviceInfo; struct MapParams; struct SyncParams; struct StatusParams; struct CommandParams; class CommandHandlerTest; /*! \brief Responsible for handling and processing individual SyncML commands * */ class CommandHandler : public QObject { Q_OBJECT public: /*! \brief Constructor * * @param aRole Role in use */ explicit CommandHandler( const Role& aRole ); /*! \brief Destructor * */ virtual ~CommandHandler(); /*! \brief Process SyncML MAP command * * @param aMapParams MAP element data * @param aTarget Target associated with the command * @return Status code */ ResponseStatusCode handleMap( const MapParams& aMapParams, SyncTarget& aTarget ); /*! \brief Process SyncML SYNC command * * @param aSyncParams SYNC element data * @param aTarget Target associated with the command * @param aStorageHandler Storage handler to use in manipulating local database * @param aResponseGenerator Response generator to use * @param aConflictResolver Conflict resolver to use * @param aFastMapsSend True if possible mappings should be sent immediately */ void handleSync( const SyncParams& aSyncParams, SyncTarget& aTarget, StorageHandler& aStorageHandler, ResponseGenerator& aResponseGenerator, ConflictResolver& aConflictResolver, bool aFastMapsSend); /*! \brief Reject SyncML SYNC command * * @param aSyncParams SYNC element data * @param aResponseGenerator Response generator to use * @param aResponseCode Response code to use */ void rejectSync( const SyncParams& aSyncParams, ResponseGenerator& aResponseGenerator, ResponseStatusCode aResponseCode ); /*! \brief Reject SyncML command (and all it's subcommands) * * @param aCommand Command element data * @param aResponseGenerator Response generator to use * @param aResponseCode Response code to use */ void rejectCommand( const CommandParams& aCommand, ResponseGenerator& aResponseGenerator, ResponseStatusCode aResponseCode ); /*! \brief Handle incoming status element * * @param aStatusParams Status params of the response */ void handleStatus(StatusParams* aStatusParams ); signals: /*! \brief Signal indicating that remote device has acknowledged an item we've sent * * @param aMsgRef Message reference to the item * @param aCmdRef Command reference to the item * @param aSyncItemKey Key of the item */ void itemAcknowledged( int aMsgRef, int aCmdRef, SyncItemKey aSyncItemKey ); /*! \brief Signal indicating that remote device has acknowledged a map we've sent * * @param aMsgRef Message reference to the item * @param aCmdRef Command reference to the item */ void mappingAcknowledged( int aMsgRef, int aCmdRef ); /*! \brief Signal indicating that the session should be aborted * * @param aAbortReason Abort code */ void abortSync(ResponseStatusCode aAbortReason); protected: // functions /*! \brief Returns whether conflict resolution is enabled * * @return True if conflict resolution should be done, otherwise false */ bool resolveConflicts(); private: // functions /** * \brief Handles error situation * @param aErrorCode Error code */ void handleError(ResponseStatusCode aErrorCode); /** * \brief Handles redirection information message * @param aRedirectionCode */ virtual ResponseStatusCode handleRedirection( ResponseStatusCode aRedirectionCode ); /** * \brief Return the type of the status code given as parameter * @param aStatus Status code * @return The type of the status code */ StatusCodeType getStatusType(ResponseStatusCode aStatus); void composeBatches( const SyncParams& aSyncParams, SyncTarget& aTarget, StorageHandler& aStorageHandler, ResponseGenerator& aResponseGenerator, QMap& aResponses ); void commitBatches( StorageHandler& aStorageHandler, ConflictResolver& aConflictResolver, SyncTarget& aTarget, const SyncParams& aSyncParams, QMap& aResponses, QList& aNewMappings ); void processResults( const SyncParams& aSyncParams, const QMap& aResponses, ResponseGenerator& aResponseGenerator ); void manageNewMappings( SyncTarget& aTarget, const QList& aNewMappings, ResponseGenerator& aResponseGenerator, bool aFastMapsSend ); private: // data Role iRole; ///< Role in use QMap iStatusTypes; ///< A map that is used to find the type of a status code friend class CommandHandlerTest; }; } #endif buteo-syncml-0.5.15/src/ConflictResolver.cpp000066400000000000000000000105201433763642500210140ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ConflictResolver.h" #include "SyncAgentConsts.h" #include "LocalChanges.h" #include "SyncMLLogging.h" using namespace DataSync; ConflictResolver::ConflictResolver( LocalChanges& aLocalChanges, ConflictResolutionPolicy aPolicy ) : iLocalChanges( aLocalChanges ), iPolicy( aPolicy ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } ConflictResolver::~ConflictResolver() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool ConflictResolver::isConflict( const SyncItemKey& aKey, bool aDelete ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); if (aKey.isEmpty()) return false; // If item can be found from modified list, it is always a conflict. If item can // be found from removed list, it is conflict only if command doesn't involve deleting the item bool removalConflict = iLocalChanges.removed.contains( aKey ) && !aDelete; bool modificationConflict = iLocalChanges.modified.contains( aKey ); return ( removalConflict || modificationConflict ); } bool ConflictResolver::localSideWins() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iPolicy == PREFER_LOCAL_CHANGES ) { return true; } else { return false; } } void ConflictResolver::removeLocalChange( const SyncItemKey& aLocalKey ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool retval = false; if (iLocalChanges.removed.contains( aLocalKey )) retval = iLocalChanges.removed.removeOne( aLocalKey ); else retval = iLocalChanges.modified.removeOne( aLocalKey ); } void ConflictResolver::changeLocalModifyToLocalAdd( const SyncItemKey& aLocalKey ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); /* Reason for this is that in the case of a conflict scenario if the remote is delete and local is * modify and if remote wins the mapping is lost in remote side so a replace returns with an error*/ for (int i = 0; i < iLocalChanges.modified.size(); ++i) { qCDebug(lcSyncML) << "Key :" << aLocalKey << "Remote" << iLocalChanges.modified.at(i); if (iLocalChanges.modified.at(i) == aLocalKey){ qCDebug(lcSyncML) << "Change from replace to add "; iLocalChanges.modified.removeAt(i); iLocalChanges.added.append(aLocalKey); break; } } } void ConflictResolver::revertLocalChange( const SyncItemKey& aLocalKey, ConflictRevertPolicy policy ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); switch (policy) { case CR_REMOVE_LOCAL: removeLocalChange ( aLocalKey ); break; case CR_MODIFY_TO_ADD: changeLocalModifyToLocalAdd ( aLocalKey ); break; default: qCWarning(lcSyncML) << "Wrong ConflictRevertPolicy"; break; } } buteo-syncml-0.5.15/src/ConflictResolver.h000066400000000000000000000100171433763642500204620ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CONFLICTRESOLVER_H #define CONFLICTRESOLVER_H #include "SyncAgentConsts.h" #include "SyncItemKey.h" namespace DataSync { class LocalChanges; class ConflictResolverTest; enum ConflictRevertPolicy { CR_REMOVE_LOCAL, /*! * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "DataStore.h" using namespace DataSync; Datastore::Datastore() : iSupportsHierarchicalSync( false ) { } Datastore::~Datastore() { } void Datastore::setSourceURI( const QString& aSourceURI ) { iSourceURI = aSourceURI; } const QString& Datastore::getSourceURI() const { return iSourceURI; } StorageContentFormatInfo& Datastore::formatInfo() { return iFormatInfo; } const StorageContentFormatInfo& Datastore::formatInfo() const { return iFormatInfo; } void Datastore::setSupportsHierarchicalSync( bool aSupports ) { iSupportsHierarchicalSync = aSupports; } bool Datastore::getSupportsHierarchicalSync() const { return iSupportsHierarchicalSync; } const QList& Datastore::syncCaps() const { return iSyncCaps; } QList& Datastore::syncCaps() { return iSyncCaps; } const QList& Datastore::ctCaps() const { return iCTCaps; } QList& Datastore::ctCaps() { return iCTCaps; } buteo-syncml-0.5.15/src/DataStore.h000066400000000000000000000066471433763642500171030ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DATASTORE_H #define DATASTORE_H #include "CTCap.h" #include "SyncMLGlobals.h" namespace DataSync { /*! \brief Describes the properties of a storage * */ class Datastore { public: /*! \brief Constructor * */ Datastore(); /*! \brief Destructor * */ ~Datastore(); /*! \brief Set source URI of this datastore * * @param aSourceURI Source URI to set */ void setSourceURI( const QString& aSourceURI ); /*! \brief Retrieve source URI of this datastore * * @return */ const QString& getSourceURI() const; /*! \brief Access format info * * @return */ StorageContentFormatInfo& formatInfo(); /*! \brief Access format info * * @return */ const StorageContentFormatInfo& formatInfo() const; /*! \brief Sets support hierarchical sync property * * @param aSupports Value to set */ void setSupportsHierarchicalSync( bool aSupports ); /*! \brief Retrieve support hierarchical sync property * * @return */ bool getSupportsHierarchicalSync() const; /*! \brief Access sync caps of this datastore * * @return */ const QList& syncCaps() const; /*! \brief Access sync caps of this datastore * * @return */ QList& syncCaps(); /*! \brief Access CT caps of this datastore * * @return */ const QList& ctCaps() const; /*! \brief Access CT caps of this datastore * * @return */ QList& ctCaps(); private: QString iSourceURI; StorageContentFormatInfo iFormatInfo; bool iSupportsHierarchicalSync; QList iSyncCaps; QList iCTCaps; }; } #endif // DATASTORE_H buteo-syncml-0.5.15/src/DatabaseHandler.cpp000066400000000000000000000047601433763642500205440ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "DatabaseHandler.h" #include "SyncMLLogging.h" using namespace DataSync; const QString CONNECTIONNAME( "dbhandler" ); DatabaseHandler::DatabaseHandler( const QString& aDbFilePath ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); static unsigned connectionNumber = 0; iConnectionName = CONNECTIONNAME + QString::number( connectionNumber++ ); iDb = QSqlDatabase::addDatabase( "QSQLITE", iConnectionName ); iDb.setDatabaseName( aDbFilePath ); if(!iDb.open()) qCCritical(lcSyncML) << "can not open database"; } DatabaseHandler::~DatabaseHandler() { FUNCTION_CALL_TRACE(lcSyncMLTrace); iDb.close(); iDb = QSqlDatabase(); QSqlDatabase::removeDatabase( iConnectionName ); } bool DatabaseHandler::isValid() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); return iDb.isOpen(); } QSqlDatabase& DatabaseHandler::getDbHandle() { return iDb; } buteo-syncml-0.5.15/src/DatabaseHandler.h000066400000000000000000000050201433763642500201770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DATABASEHANDLER_H #define DATABASEHANDLER_H #include namespace DataSync { /*! \brief Manages Qt's SQL database * */ class DatabaseHandler { public: /*! \brief Constructor * * @param aDbFile Path of database file to create and open * */ explicit DatabaseHandler( const QString& aDbFilePath ); /*! \brief Destructor * */ virtual ~DatabaseHandler(); /*! \brief Returns true if database handle is currently valid and can be used * * @return */ bool isValid() const; /*! \brief Returns a handle to the database connection * * @return Handle to the database connection */ QSqlDatabase& getDbHandle(); private: private: // data QSqlDatabase iDb; ///< Database object QString iConnectionName; ///< Database connection name }; } #endif // DATABASEHANDLER_H buteo-syncml-0.5.15/src/DevInfHandler.cpp000066400000000000000000000135711433763642500202130ustar00rootroot00000000000000 /* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "DevInfHandler.h" #include "DevInfPackage.h" #include "ResponseGenerator.h" #include "Fragments.h" #include "SyncMLLogging.h" using namespace DataSync; DevInfHandler::DevInfHandler( const DeviceInfo& aDeviceInfo ) : iLocalDeviceInfo( aDeviceInfo ), iLocalDevInfSent( false ), iRemoteDevInfReceived( false ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } DevInfHandler::~DevInfHandler() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } const DeviceInfo& DevInfHandler::getLocalDeviceInfo() const { return iLocalDeviceInfo; } const RemoteDeviceInfo& DevInfHandler::getRemoteDeviceInfo() const { return iRemoteDevInfo; } void DevInfHandler::composeLocalInitiatedDevInfExchange( const QList& aDataStores, const ProtocolVersion& aVersion, const Role& aRole, ResponseGenerator& aResponseGenerator ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iLocalDevInfSent ) { DevInfPackage* devInf = new DevInfPackage( aDataStores, iLocalDeviceInfo, aVersion, aRole ); aResponseGenerator.addPackage( devInf ); iLocalDevInfSent = true; } } ResponseStatusCode DevInfHandler::handleGet( const CommandParams& aGet, const ProtocolVersion& aVersion, const QList& aDataStores, const Role& aRole, ResponseGenerator& aResponseGenerator ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status = NOT_IMPLEMENTED; bool valid = false; if( aGet.items.count() == 1 ) { if( aVersion == SYNCML_1_1 && aGet.items.first().target == SYNCML_DEVINF_PATH_11 ) { valid = true; } else if( aVersion == SYNCML_1_2 && aGet.items.first().target == SYNCML_DEVINF_PATH_12 ) { valid = true; } } if( valid ) { // If we haven't yet received remote device info, send GET in addition to the // RESULTS DevInfPackage* devInf = new DevInfPackage( aResponseGenerator.getRemoteMsgId(), aGet.cmdId, aDataStores, iLocalDeviceInfo, aVersion, aRole, !iRemoteDevInfReceived ); aResponseGenerator.addPackage( devInf ); iLocalDevInfSent = true; status = SUCCESS; } else { status = COMMAND_FAILED; } return status; } ResponseStatusCode DevInfHandler::handlePut( const PutParams& aPut, const ProtocolVersion& aVersion ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status = NOT_IMPLEMENTED; bool valid = false; if( aVersion == SYNCML_1_1 && aPut.devInf.source == SYNCML_DEVINF_PATH_11 ) { valid = true; } else if( aVersion == SYNCML_1_2 && aPut.devInf.source == SYNCML_DEVINF_PATH_12 ) { valid = true; } if( valid ) { iRemoteDevInfo = aPut.devInf.devInfo; iRemoteDevInfReceived = true; status = SUCCESS; } else { status = COMMAND_FAILED; } return status; } ResponseStatusCode DevInfHandler::handleResults( const ResultsParams& aResults, const ProtocolVersion& aVersion ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status = NOT_IMPLEMENTED; bool valid = false; if( aVersion == SYNCML_1_1 && aResults.devInf.source == SYNCML_DEVINF_PATH_11 ) { valid = true; } else if( aVersion == SYNCML_1_2 && aResults.devInf.source == SYNCML_DEVINF_PATH_12 ) { valid = true; } if( valid ) { iRemoteDevInfo = aResults.devInf.devInfo; iRemoteDevInfReceived = true; status = SUCCESS; } else { status = COMMAND_FAILED; } return status; } void DevInfHandler::reset() { FUNCTION_CALL_TRACE(lcSyncMLTrace); iLocalDevInfSent = false; iRemoteDevInfReceived = false; } buteo-syncml-0.5.15/src/DevInfHandler.h000066400000000000000000000114001433763642500176450ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DEVINFHANDLER_H #define DEVINFHANDLER_H #include "DeviceInfo.h" #include "RemoteDeviceInfo.h" #include "SyncAgentConsts.h" #include "datatypes.h" class DevInfHandlerTest; namespace DataSync { class StoragePlugin; class ResponseGenerator; struct CommandParams; struct PutParams; struct ResultsParams; /*! \brief Class that governs the exchange of device information in * synchronization session */ class DevInfHandler { public: /*! \brief Constructor * * @param aDeviceInfo Device information object */ DevInfHandler( const DeviceInfo& aDeviceInfo ); /*! \brief Destructor * */ ~DevInfHandler(); /*! \brief Retrieves the local device information * * @return */ const DeviceInfo& getLocalDeviceInfo() const; /*! \brief Retrieves the remote device information * * @return */ const RemoteDeviceInfo& getRemoteDeviceInfo() const; /*! \brief Initiate a device info exchange with remote device * * @param aDataStores Data stores to use * @param aVersion Protocol version in use * @param aRole Role in use * @param aResponseGenerator Response generator to use */ void composeLocalInitiatedDevInfExchange( const QList& aDataStores, const ProtocolVersion& aVersion, const Role& aRole, ResponseGenerator& aResponseGenerator ); /*! \brief Respond to device info requested by remote device * * @param aGet GET element data * @param aDataStores Data stores to use * @param aVersion Protocol version in use * @param aRole Role in use * @param aResponseGenerator Response generator to use * @return */ ResponseStatusCode handleGet( const CommandParams& aGet, const ProtocolVersion& aVersion, const QList& aDataStores, const Role& aRole, ResponseGenerator& aResponseGenerator ); /*! \brief Respond to device info sent by remote device * * @param aPut PUT element data * @param aVersion Protocol version in use * @return */ ResponseStatusCode handlePut( const PutParams& aPut, const ProtocolVersion& aVersion ); /*! \brief Respond to device info received from remote device * * @param aResults RESULTS element data * @param aVersion Protocol version in use */ ResponseStatusCode handleResults( const ResultsParams& aResults, const ProtocolVersion& aVersion ); /*! \brief Resets device information exchange state * * Needed for example when initialization package needs to be re-sent */ void reset(); protected: private: friend class ::DevInfHandlerTest; DeviceInfo iLocalDeviceInfo; RemoteDeviceInfo iRemoteDevInfo; bool iLocalDevInfSent; bool iRemoteDevInfReceived; }; } #endif // DEVINFHANDLER_H buteo-syncml-0.5.15/src/DevInfPackage.cpp000066400000000000000000000117101433763642500201620ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "DevInfPackage.h" #include "SyncMLPut.h" #include "SyncMLGet.h" #include "SyncMLResults.h" #include "SyncMLMessage.h" #include "datatypes.h" #include "SyncMLLogging.h" using namespace DataSync; DevInfPackage::DevInfPackage( const QList& aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole ) : iMsgRef(0), iCmdRef(0), iDataStores( aDataStores ), iDeviceInfo( aDeviceInfo ), iVersion( aVersion ), iRole( aRole ), iType( PUTGET ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } DevInfPackage::DevInfPackage( int aMsgRef, int aCmdRef, const QList& aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole, bool aRetrieveRemoteDevInf ) : iMsgRef( aMsgRef ), iCmdRef( aCmdRef ), iDataStores( aDataStores ), iDeviceInfo( aDeviceInfo ),iVersion( aVersion ), iRole( aRole ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aRetrieveRemoteDevInf ) { iType = RESULTSGET; } else { iType = RESULTS; } } DevInfPackage::~DevInfPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool DevInfPackage::write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iType == PUTGET ) { // Compose PUT SyncMLPut* put = new SyncMLPut( aMessage.getNextCmdId(), iDataStores, iDeviceInfo, iVersion, iRole ); // Compose GET SyncMLGet* get = new SyncMLGet( aMessage.getNextCmdId(), SYNCML_CONTTYPE_DEVINF_XML, iVersion == SYNCML_1_1 ? SYNCML_DEVINF_PATH_11 : SYNCML_DEVINF_PATH_12 ); aSizeThreshold -= put->calculateSize(aWBXML, aVersion); aMessage.addToBody( put ); aSizeThreshold -= get->calculateSize(aWBXML, aVersion); aMessage.addToBody( get ); } else if( iType == RESULTS ) { // Compose RESULTS SyncMLResults* results = new SyncMLResults( aMessage.getNextCmdId(), iMsgRef, iCmdRef, iDataStores, iDeviceInfo, iVersion, iRole ); aSizeThreshold -= results->calculateSize(aWBXML, aVersion); aMessage.addToBody( results ); } else if( iType == RESULTSGET ) { // Compose RESULTS SyncMLResults* results = new SyncMLResults( aMessage.getNextCmdId(), iMsgRef, iCmdRef, iDataStores, iDeviceInfo, iVersion, iRole ); // Compose GET SyncMLGet* get = new SyncMLGet( aMessage.getNextCmdId(), SYNCML_CONTTYPE_DEVINF_XML, iVersion == SYNCML_1_1 ? SYNCML_DEVINF_PATH_11 : SYNCML_DEVINF_PATH_12 ); aSizeThreshold -= results->calculateSize(aWBXML, aVersion); aMessage.addToBody( results ); aSizeThreshold -= get->calculateSize(aWBXML, aVersion); aMessage.addToBody( get ); } else { Q_ASSERT(0); } return true; } buteo-syncml-0.5.15/src/DevInfPackage.h000066400000000000000000000102011433763642500176210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DEVINFPACKAGE_H #define DEVINFPACKAGE_H #include "Package.h" #include "SyncAgentConsts.h" #include "datatypes.h" namespace DataSync { class StoragePlugin; class DeviceInfo; /*! \brief DevInfPackage handles exchanging of device information to remote side * */ class DevInfPackage : public Package { Q_OBJECT; public: /*! \brief Construct device information package using PUT * * This constructor should be used when local side is initiating device * info exchange. Local device info is sent with PUT, and remote device info * is requested with GET. * * @param aDataStores Datastores available to use in generation * @param aDeviceInfo Device info object * @param aVersion Protocol version to use * @param aRole Role in use */ DevInfPackage( const QList& aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole ); /*! \brief Construct device information package using RESULTS * * This constructor should be used when remote side is initiating device info * exchange. Remote device has issued GET, which will be countered with * RESULTS. If remote device has not yet sent device info, GET can be * issued to retrieve it. * * @param aMsgRef Message reference for RESULTS element * @param aCmdRef Command reference for RESULTS element * @param aDataStores Datastores available to use in generation * @param aDeviceInfo Device info object * @param aVersion Protocol version to use * @param aRole Role in use * @param aRetrieveRemoteDevInf True if GET should be issued to remote side */ DevInfPackage( int aMsgRef, int aCmdRef, const QList& aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole, bool aRetrieveRemoteDevInf ); virtual ~DevInfPackage(); virtual bool write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ); protected: private: enum Type { PUTGET, RESULTS, RESULTSGET }; int iMsgRef; int iCmdRef; QList iDataStores; const DeviceInfo& iDeviceInfo; ProtocolVersion iVersion; Role iRole; Type iType; }; } #endif // DEVINFPACKAGE_H buteo-syncml-0.5.15/src/DeviceInfo.cpp000066400000000000000000000125601433763642500175520ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "DeviceInfo.h" #include #include #include "SyncMLLogging.h" #include "datatypes.h" using namespace DataSync; const QString XML_KEY_MANUFACTURER("Manufacturer"); const QString XML_KEY_MODEL("Model"); const QString XML_KEY_OEM("OEM"); const QString XML_KEY_FW_VER("FwVersion"); const QString XML_KEY_HW_VER("HwVersion"); const QString XML_KEY_SW_VER("SwVersion"); const QString XML_KEY_ID("Id"); const QString XML_KEY_DEVICE_TYPE("DeviceType"); DeviceInfo::DeviceInfo() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } DeviceInfo::~DeviceInfo() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } const QString& DeviceInfo::getManufacturer() const { return iManufacturer; } void DeviceInfo::setManufacturer(const QString &aManufacturer) { iManufacturer = aManufacturer; } const QString& DeviceInfo::getModel() const { return iModel; } void DeviceInfo::setModel(const QString &aModel) { iModel = aModel; } void DeviceInfo::setOEM( const QString& aOEM ) { iOEM = aOEM; } const QString& DeviceInfo::getOEM() const { return iOEM; } const QString& DeviceInfo::getFirmwareVersion() const { return iFirmwareVersion; } void DeviceInfo::setFirmwareVersion(const QString &aFirmwareVersion) { iFirmwareVersion = aFirmwareVersion; } const QString& DeviceInfo::getSoftwareVersion() const { return iSoftwareVersion; } void DeviceInfo::setSoftwareVersion(const QString& aSoftwareVersion) { iSoftwareVersion = aSoftwareVersion; } const QString& DeviceInfo::getHardwareVersion() const { return iHardwareVersion; } void DeviceInfo::setHardwareVersion(const QString& aHardwareVersion) { iHardwareVersion = aHardwareVersion; } void DeviceInfo::setDeviceID( const QString& aDeviceID ) { iDeviceID = aDeviceID; } const QString& DeviceInfo::getDeviceID() const { return iDeviceID; } const QString& DeviceInfo::getDeviceType() const { return iDeviceType; } void DeviceInfo::setDeviceType(const QString& aDeviceType) { iDeviceType = aDeviceType; } bool DeviceInfo::readFromFile(const QString &aFileName) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QFile file(aFileName); if( !file.open(QIODevice::ReadOnly) ) { qCWarning(lcSyncML) << "Failed open file:" << aFileName; return false; } QXmlStreamReader reader(file.readAll()); while(!reader.atEnd()) { if(reader.tokenType() == QXmlStreamReader::StartElement) { if(reader.name() == XML_KEY_MANUFACTURER) { reader.readNext(); setManufacturer(reader.text().toString()); }else if (reader.name() == XML_KEY_MODEL) { reader.readNext(); setModel(reader.text().toString()); }else if (reader.name() == XML_KEY_OEM) { reader.readNext(); setOEM(reader.text().toString()); }else if (reader.name() == XML_KEY_SW_VER){ reader.readNext(); setSoftwareVersion(reader.text().toString()); }else if (reader.name() == XML_KEY_HW_VER) { reader.readNext(); setHardwareVersion(reader.text().toString()); } else if (reader.name() == XML_KEY_FW_VER) { reader.readNext(); setFirmwareVersion(reader.text().toString()); } else if(reader.name() == XML_KEY_ID) { reader.readNext(); setDeviceID(reader.text().toString()); } else if (reader.name() == XML_KEY_DEVICE_TYPE ) { reader.readNext(); setDeviceType(reader.text().toString()); } else { qCWarning(lcSyncML) << "Ignoring unknown element:" << reader.name(); } } reader.readNext(); } file.close(); return true; } buteo-syncml-0.5.15/src/DeviceInfo.h000066400000000000000000000114221433763642500172130ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DEVICEINFO_H #define DEVICEINFO_H #include namespace DataSync { /*! \brief DeviceInfo includes information about a device * */ class DeviceInfo { public: /*! \brief Constructor * */ DeviceInfo(); /*! \brief Destructor * */ ~DeviceInfo(); /*! \brief Sets the device manufacturer * * @param aManufacturer Device manufacturer */ void setManufacturer( const QString& aManufacturer ); /*! \brief Returns the manufacturer * * @return */ const QString& getManufacturer() const; /*! \brief Sets the device model * * @param aModel Device model */ void setModel( const QString& aModel ); /*! \brief Returns the device model * * @return */ const QString& getModel() const; /*! \brief Sets the device OEM * * @param aOEM Device OEM */ void setOEM( const QString& aOEM ); /*! \brief Returns the OEM * * @return */ const QString& getOEM() const; /*! \brief Sets the device firmware version * * @param aFirmwareVersion Device firmware version */ void setFirmwareVersion( const QString& aFirmwareVersion ); /*! \brief Returns the device firmware version * * @return */ const QString& getFirmwareVersion() const; /*! \brief Sets the software version * * @param aSoftwareVersion Device software version */ void setSoftwareVersion( const QString& aSoftwareVersion ); /*! \brief Returns the device software version * * @return */ const QString& getSoftwareVersion() const; /*! \brief Sets the device hardware version * * @param aHardwareVersion Device hardware version */ void setHardwareVersion( const QString& aHardwareVersion ); /*! \brief Returns the device hardware version * * @return */ const QString& getHardwareVersion() const; /*! \brief Sets the device type * * Possible device types are enumerated in OMA DS Device * Information document in section 5.3.7 * * @param aDeviceType Device type */ void setDeviceType( const QString& aDeviceType ); /*! \brief Returns the device type * * Possible device types are enumerated in OMA DS Device * Information document in section 5.3.7 * * @return */ const QString& getDeviceType() const; /*! \brief Sets the globally unique device identification of this device * * @param aDeviceID Device identification */ void setDeviceID( const QString& aDeviceID ); /*! \brief Returns the globally unique device identification of this device * * @return */ const QString& getDeviceID() const; /*! \brief Read device information from a file * * @param aFileName File to read * @return True on success, otherwise false */ bool readFromFile(const QString &aFileName); private: QString iDeviceID; QString iManufacturer; QString iModel; QString iOEM; QString iFirmwareVersion; QString iSoftwareVersion; QString iHardwareVersion; QString iDeviceType; }; } #endif // DEVICEINFO_H buteo-syncml-0.5.15/src/FinalPackage.cpp000066400000000000000000000041251433763642500200420ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "FinalPackage.h" #include "SyncMLCmdObject.h" #include "SyncMLMessage.h" using namespace DataSync; FinalPackage::FinalPackage() { } FinalPackage::~FinalPackage() { } bool FinalPackage::write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ) { SyncMLCmdObject* finalObj = new SyncMLCmdObject("Final"); aMessage.addToBody( finalObj ); aSizeThreshold -= finalObj->calculateSize(aWBXML, aVersion); return true; } buteo-syncml-0.5.15/src/FinalPackage.h000066400000000000000000000041521433763642500175070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef FINALPACKAGE_H #define FINALPACKAGE_H #include "Package.h" namespace DataSync { /*! \brief FinalPackage handles sending a Final to remote side * */ class FinalPackage : public Package { Q_OBJECT; public: /*! \brief Constructor * */ FinalPackage(); /*! \brief Destructor * */ virtual ~FinalPackage(); virtual bool write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ); }; } #endif // FINALPACKAGE_H buteo-syncml-0.5.15/src/Fragments.h000066400000000000000000000145551433763642500171400ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef FRAGMENTS_H #define FRAGMENTS_H #include "RemoteDeviceInfo.h" #include "datatypes.h" // @todo: StatusParams.nextAnchor // @todo: Search namespace DataSync { struct CommandParams; struct AnchorParams { QString last; QString next; }; struct MetaParams { AnchorParams anchor; QList EMI; QString format; qint64 maxMsgSize; qint64 maxObjSize; QString nextNonce; qint64 size; QString type; QString version; QString mark; MetaParams() : maxMsgSize(0), maxObjSize(0), size(0) {} }; struct ItemParams { QString source; QString target; QString sourceParent; QString targetParent; MetaParams meta; QString data; bool moreData; ItemParams() : moreData(false) {} }; struct DevInfItemParams { QString source; RemoteDeviceInfo devInfo; }; struct CredParams { MetaParams meta; QString data; }; struct MapItemParams { QString target; QString source; }; struct ChalParams { MetaParams meta; }; /*! \brief Base for protocol fragments * */ struct Fragment { /*! \brief Type of fragment * */ enum FragmentType { FRAGMENT_HEADER = 0, FRAGMENT_STATUS, FRAGMENT_PUT, FRAGMENT_RESULTS, FRAGMENT_SYNC, FRAGMENT_MAP, FRAGMENT_COMMAND }; FragmentType fragmentType; Fragment( FragmentType aType ) : fragmentType( aType ) {} virtual ~Fragment() { } }; struct HeaderParams : public Fragment { QString verDTD; QString verProto; QString sessionID; int msgID; QString targetDevice; QString sourceDevice; QString respURI; bool noResp; CredParams cred; MetaParams meta; HeaderParams() : Fragment( FRAGMENT_HEADER ), msgID(-1), noResp( false ) {} }; struct StatusParams : public Fragment { int cmdId; int msgRef; int cmdRef; QString cmd; QString targetRef; QString sourceRef; ResponseStatusCode data; bool hasChal; ChalParams chal; QString nextAnchor; QList items; StatusParams() : Fragment( FRAGMENT_STATUS ), cmdId(-1), msgRef(-1), cmdRef(-1), data(SERVER_FAILURE), hasChal( false ) {} }; struct PutParams : public Fragment { int cmdId; bool noResp; MetaParams meta; DevInfItemParams devInf; PutParams() : Fragment( FRAGMENT_PUT ), cmdId( -1 ), noResp( false ) { } }; struct ResultsParams : public Fragment { int cmdId; int msgRef; int cmdRef; QString targetRef; QString sourceRef; MetaParams meta; DevInfItemParams devInf; ResultsParams() : Fragment( FRAGMENT_RESULTS ), cmdId(-1), msgRef(-1), cmdRef(-1) {} }; struct SyncParams : public Fragment { int cmdId; bool noResp; MetaParams meta; QString target; QString source; qint32 numberOfChanges; QList commands; SyncParams() : Fragment( FRAGMENT_SYNC ), cmdId(-1), noResp(false), numberOfChanges(0) {} }; struct MapParams : public Fragment { int cmdId; QString target; QString source; MetaParams meta; QList mapItems; MapParams() : Fragment( FRAGMENT_MAP ), cmdId(-1) {} }; struct CommandParams : public Fragment { enum CommandType { COMMAND_ALERT = 0, COMMAND_ADD, COMMAND_REPLACE, COMMAND_DELETE, COMMAND_GET, COMMAND_COPY, COMMAND_MOVE, COMMAND_EXEC, COMMAND_ATOMIC, COMMAND_SEQUENCE }; CommandType commandType; int cmdId; bool noResp; QString data; QString correlator; MetaParams meta; QList items; QList subCommands; CommandParams( CommandType aType ) : Fragment( FRAGMENT_COMMAND ), commandType( aType ), cmdId( -1 ), noResp( false ) {} CommandParams() : Fragment( FRAGMENT_COMMAND ), commandType( COMMAND_ALERT ), cmdId( -1 ), noResp( false ) {} }; } #endif // FRAGMENTS_H buteo-syncml-0.5.15/src/LocalChanges.h000066400000000000000000000035421433763642500175270ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LOCALCHANGES_H #define LOCALCHANGES_H #include #include "SyncItemKey.h" namespace DataSync { struct LocalChanges { QList added; QList modified; QList removed; }; } #endif // LOCALCHANGES_H buteo-syncml-0.5.15/src/LocalChangesPackage.cpp000066400000000000000000000372601433763642500213420ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "LocalChangesPackage.h" #include #include "SyncTarget.h" #include "StoragePlugin.h" #include "SyncItem.h" #include "SyncMLSync.h" #include "SyncMLMessage.h" #include "SyncMLAdd.h" #include "SyncMLReplace.h" #include "SyncMLDelete.h" #include "SyncMLItem.h" #include "SyncAgentConsts.h" #include "SyncMLLogging.h" using namespace DataSync; LocalChangesPackage::LocalChangesPackage( const SyncTarget& aSyncTarget, const LocalChanges& aLocalChanges, int aLargeObjectThreshold, const Role& aRole, int aMaxChangesPerMessage) : iLargeObjectThreshold( aLargeObjectThreshold ), iSyncTarget( aSyncTarget ), iLocalChanges( aLocalChanges ), iRole( aRole ), iMaxChangesPerMessage(aMaxChangesPerMessage), iPrefetcher( aLocalChanges.added + aLocalChanges.modified, *aSyncTarget.getPlugin(), aMaxChangesPerMessage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iNumberOfChanges = iLocalChanges.added.count() + iLocalChanges.modified.count() + iLocalChanges.removed.count(); } LocalChangesPackage::~LocalChangesPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); delete iLargeObjectState.iItem; iLargeObjectState.iItem = 0; } bool LocalChangesPackage::write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool allWritten = false; int remainingBytes = aSizeThreshold; SyncMLSync* sync = new SyncMLSync( aMessage.getNextCmdId(), iSyncTarget.getTargetDatabase(), iSyncTarget.getSourceDatabase() ); sync->addNumberOfChanges( iNumberOfChanges ); remainingBytes -= sync->calculateSize(aWBXML, aVersion); int itemsThatCanBeSent = iMaxChangesPerMessage; if( iNumberOfChanges > 0 ) { if( processAddedItems(aMessage, *sync, remainingBytes,itemsThatCanBeSent, aWBXML, aVersion) && processModifiedItems(aMessage, *sync, remainingBytes, itemsThatCanBeSent, aWBXML, aVersion) && processRemovedItems(aMessage, *sync, remainingBytes, itemsThatCanBeSent, aWBXML, aVersion) ) { allWritten = true; } } else { allWritten = true; } aMessage.addToBody( sync ); aSizeThreshold = remainingBytes; if( !allWritten ) { // If we didn't finish writing everything, schedule idle-time prefetcher iPrefetcher.setBatchSizeHint( iMaxChangesPerMessage - itemsThatCanBeSent ); QTimer::singleShot( 0, &iPrefetcher, SLOT(prefetch()) ); } return allWritten; } bool LocalChangesPackage::processAddedItems( SyncMLMessage& aMessage, SyncMLSync& aSyncElement, int& aSizeThreshold , int& aItemsThatCanBeSent, bool aWBXML, const ProtocolVersion& aVersion) { FUNCTION_CALL_TRACE(lcSyncMLTrace); int remainingBytes = aSizeThreshold; while( iLocalChanges.added.count() > 0 && aItemsThatCanBeSent > 0 && remainingBytes > 0 ) { int cmdId = aMessage.getNextCmdId(); SyncMLAdd* add = new SyncMLAdd(cmdId); SyncItemKey key = iLocalChanges.added.first(); QString mimeType; bool processed = processItem( key, *add, remainingBytes, SYNCML_ADD, mimeType ); remainingBytes -= add->calculateSize(aWBXML, aVersion); aSyncElement.addChild( add ); if (processed) { emit newItemWritten( aMessage.getMsgId(), cmdId, key, MOD_ITEM_ADDED, iSyncTarget.getSourceDatabase(), iSyncTarget.getTargetDatabase(), mimeType ); aItemsThatCanBeSent--; iLocalChanges.added.removeFirst(); } else { break; } } aSizeThreshold = remainingBytes; bool processed = false; if( iLocalChanges.added.count() == 0 ) { qCDebug(lcSyncML) << "Processed all added items"; processed = true; } return processed; } bool LocalChangesPackage::processModifiedItems( SyncMLMessage& aMessage, SyncMLSync& aSyncElement, int& aSizeThreshold, int& aItemsThatCanBeSent, bool aWBXML, const ProtocolVersion& aVersion) { FUNCTION_CALL_TRACE(lcSyncMLTrace); int remainingBytes = aSizeThreshold; while( iLocalChanges.modified.count() > 0 && aItemsThatCanBeSent > 0 && remainingBytes > 0 ) { int cmdId = aMessage.getNextCmdId(); SyncMLReplace* replace = new SyncMLReplace( cmdId ); SyncItemKey key = iLocalChanges.modified.first(); QString mimeType; bool processed = processItem( key, *replace, remainingBytes, SYNCML_REPLACE, mimeType ); remainingBytes -= replace->calculateSize(aWBXML, aVersion); aSyncElement.addChild( replace ); if (processed) { emit newItemWritten( aMessage.getMsgId(), cmdId, key, MOD_ITEM_MODIFIED, iSyncTarget.getSourceDatabase(), iSyncTarget.getTargetDatabase(), mimeType ); aItemsThatCanBeSent--; iLocalChanges.modified.removeFirst(); } else { break; } } aSizeThreshold = remainingBytes; bool processed = false; if( iLocalChanges.modified.count() == 0 ) { qCDebug(lcSyncML) << "Processed all modified items"; processed = true; } return processed; } bool LocalChangesPackage::processRemovedItems( SyncMLMessage& aMessage, SyncMLSync& aSyncElement, int& aSizeThreshold, int& aItemsThatCanBeSent, bool aWBXML, const ProtocolVersion& aVersion) { FUNCTION_CALL_TRACE(lcSyncMLTrace); int remainingBytes = aSizeThreshold; while( iLocalChanges.removed.count() > 0 && aItemsThatCanBeSent > 0 && remainingBytes > 0 ) { int cmdId = aMessage.getNextCmdId(); SyncMLDelete* del = new SyncMLDelete(cmdId); SyncItemKey key = iLocalChanges.removed.first(); // @todo: we cannot know the mime type in the case of deleted items. In overall it's bad // that we're using mimetype here, we should be able to handle identification of used // storage purely on the db uri's. QString mimeType; bool processed = processItem( key, *del, remainingBytes, SYNCML_DELETE, mimeType ); remainingBytes -= del->calculateSize(aWBXML, aVersion); aSyncElement.addChild( del ); if (processed) { emit newItemWritten( aMessage.getMsgId(), cmdId, key, MOD_ITEM_DELETED, iSyncTarget.getSourceDatabase(), iSyncTarget.getTargetDatabase(), mimeType ); aItemsThatCanBeSent--; iLocalChanges.removed.removeFirst(); } else { break; } } aSizeThreshold = remainingBytes; bool processed = false; if( iLocalChanges.removed.count() == 0 ) { qCDebug(lcSyncML) << "Processed all deleted items"; processed = true; } return processed; } bool LocalChangesPackage::processItem( const SyncItemKey& aItemKey, SyncMLLocalChange& aParent, int aSizeThreshold, SyncMLCommand aCommand, QString& aMimeType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool processed = false; SyncMLItem* itemObject = new SyncMLItem(); if( aCommand == SYNCML_ADD ) { itemObject->insertSource( aItemKey ); } else { if( iRole == ROLE_SERVER ) { SyncItemKey remoteKey = iSyncTarget.mapToRemoteUID( aItemKey ); if( !remoteKey.isEmpty() ) { itemObject->insertTarget( remoteKey ); } else { qCWarning(lcSyncML) << "Could not find mapping to for local uid: " << aItemKey; } } else { itemObject->insertSource( aItemKey ); } } if( aCommand == SYNCML_DELETE ) { // Delete command does not include item data processed = true; } else { SyncItem* item = 0; if( iLargeObjectState.iItem ) { // We're in the middle of sending a large object item = iLargeObjectState.iItem; } else { // We're not sending a large object, so get the item from plugin item = iPrefetcher.getItem( aItemKey ); } if (item) { aMimeType = item->getType(); aParent.addMimeMetadata( item->getType() ); qint64 size = item->getSize(); QString version = item->getVersion(); if ( !version.isEmpty()) { aParent.addVersionMetadata(version); } if( !item->getParentKey()->isEmpty() ) { const SyncItemKey* parentKey = item->getParentKey(); if( iRole == ROLE_SERVER ) { SyncItemKey remoteKey = iSyncTarget.mapToRemoteUID( *parentKey ); if( !remoteKey.isEmpty() ) { itemObject->insertTargetParent( remoteKey ); } else { itemObject->insertSourceParent( *parentKey ); } } else if( iRole == ROLE_CLIENT ) { itemObject->insertSourceParent( *parentKey ); } // no else } if (size > iLargeObjectThreshold) { if(iLargeObjectState.iItem) { // Item is large and needs to be sent using multiple messages qCDebug(lcSyncML) << "Writing item" << aItemKey << "as large object, size:" << size; QByteArray data; qint64 dataLeft = iLargeObjectState.iSize - iLargeObjectState.iOffset; if( dataLeft > aSizeThreshold ) { qCDebug(lcSyncML) << "Writing chunk of" << aSizeThreshold << "bytes"; // Need to send more chunks after this one item->read( iLargeObjectState.iOffset, aSizeThreshold, data ); // syncml-ds-tool from libsyncml complains that // consecutive package of a single message should // not have size in header //aParent.addSizeMetadata( size ); itemObject->insertData( data ); itemObject->insertMoreData(); iLargeObjectState.iOffset += aSizeThreshold; } else { qCDebug(lcSyncML) << "Writing last chunk of" << dataLeft << "bytes"; // This is the last chunk item->read( iLargeObjectState.iOffset, dataLeft, data ); itemObject->insertData( data ); iLargeObjectState.iItem = 0; iLargeObjectState.iSize = 0; iLargeObjectState.iOffset = 0; delete item; item = 0; processed = true; } } else if( size <= aSizeThreshold) { qCDebug(lcSyncML) << "Writing item" << aItemKey << "as normal object, size:" << size; QByteArray data; item->read( 0, size, data ); itemObject->insertData( data ); delete item; item = 0; processed = true; } else { // If no chunks of the item has yet been sent, prepare tracking // data qCDebug(lcSyncML) << "Setting up largeObject data"; iLargeObjectState.iItem = item; iLargeObjectState.iSize = size; iLargeObjectState.iOffset = 0; qCDebug(lcSyncML) << "Writing chunk of" << aSizeThreshold << "bytes"; // Need to send more chunks after this one QByteArray data; item->read( iLargeObjectState.iOffset, aSizeThreshold, data ); aParent.addSizeMetadata( size ); itemObject->insertData( data ); itemObject->insertMoreData(); iLargeObjectState.iOffset += aSizeThreshold; } } else //(size <= aSizeThreshold ) { qCDebug(lcSyncML) << "Writing item" << aItemKey << "as normal object, size:" << size; QByteArray data; item->read( 0, size, data ); itemObject->insertData( data ); delete item; item = 0; processed = true; } } else { qCWarning(lcSyncML) << "Could not retrieve item data:" << aItemKey; processed = true; } } aParent.addChild( itemObject ); return processed; } buteo-syncml-0.5.15/src/LocalChangesPackage.h000066400000000000000000000134111433763642500207770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LOCALCHANGESPACKAGE_H #define LOCALCHANGESPACKAGE_H #include "Package.h" #include "LocalChanges.h" #include "SyncMLCommand.h" #include "SyncItemKey.h" #include "SyncAgentConsts.h" #include "SyncItemPrefetcher.h" #include "datatypes.h" class LocalChangesPackageTest; namespace DataSync { class SyncMLSync; class SyncMLLocalChange; class SyncTarget; class SyncItem; /*! \brief LocalChangesPackage handles sending local modifications phase for * a single sync target * * LocalChangesPackage maintains a queue of modifications to be sent to * server. */ class LocalChangesPackage : public Package { Q_OBJECT public: /*! \brief Constructor * * @param aSyncTarget Sync target * @param aLocalChanges List of local changes in aSyncTarget * @param aLargeObjectThreshold If object size exceeds this threshold, it should be considered a large object * @param aRole The role of the session (client or server) * @param aMaxChangesPerMessage Maximum number of changes to write per one SyncML message */ LocalChangesPackage( const SyncTarget& aSyncTarget, const LocalChanges& aLocalChanges, int aLargeObjectThreshold, const Role& aRole, int aMaxChangesPerMessage); /*! \brief Destructor * */ virtual ~LocalChangesPackage(); virtual bool write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ); signals: /*! \brief Signal that has been emitted when item has been added to an outgoing message * * Information supplied in this signal can be used to track the item. * * @param aMsgId Message Id of the message where the item was written * @param aCmdId Command Id of the command where the item was written * @param aKey Key of the written item * @param aModificationType Type of modification to the item * @param aLocalDatabase Local database where item exists * @param aRemoteDatabase Remote database to which item is being sent * @param aMimeType Mime type of the item */ void newItemWritten( int aMsgId, int aCmdId, SyncItemKey aKey, ModificationType aModificationType, QString aLocalDatabase, QString aRemoteDatabase, QString aMimeType ); protected: private: struct LargeObjectState { SyncItem* iItem; qint64 iSize; qint64 iOffset; LargeObjectState() : iItem( 0 ), iSize(0), iOffset(0) {} }; bool processAddedItems( SyncMLMessage& aMessage, SyncMLSync& aSyncElement, int& aSizeThreshold, int& aItemsThatCanBeSent, bool aWBXML, const ProtocolVersion& aVersion); bool processModifiedItems( SyncMLMessage& aMessage, SyncMLSync& aSyncElement, int& aSizeThreshold, int& aItemsThatCanBeSent, bool aWBXML, const ProtocolVersion& aVersion); bool processRemovedItems( SyncMLMessage& aMessage, SyncMLSync& aSyncElement, int& aSizeThreshold, int& aItemsThatCanBeSent, bool aWBXML, const ProtocolVersion& aVersion); bool processItem( const SyncItemKey& aItemKey, SyncMLLocalChange& aParent, int aSizeThreshold, SyncMLCommand aCommand, QString& aMimeType ); int iLargeObjectThreshold; int iNumberOfChanges; const SyncTarget& iSyncTarget; LocalChanges iLocalChanges; LargeObjectState iLargeObjectState; Role iRole; int iMaxChangesPerMessage; SyncItemPrefetcher iPrefetcher; friend class ::LocalChangesPackageTest; }; } #endif // LOCALCHANGESPACKAGE_H buteo-syncml-0.5.15/src/LocalMappingsPackage.cpp000066400000000000000000000062261433763642500215460ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "LocalMappingsPackage.h" #include "SyncMLMessage.h" #include "SyncMLMap.h" #include "SyncMLMapItem.h" #include "SyncMLLogging.h" using namespace DataSync; LocalMappingsPackage::LocalMappingsPackage( const QString& aSourceDatabase, const QString& aTargetDatabase, const QList& aMappings ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iSourceDatabase = aSourceDatabase; iTargetDatabase = aTargetDatabase; iMappings = aMappings; } LocalMappingsPackage::~LocalMappingsPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool LocalMappingsPackage::write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iMappings.isEmpty() ) { int cmdId = aMessage.getNextCmdId(); SyncMLMap* map = new SyncMLMap( cmdId, iTargetDatabase, iSourceDatabase ); aSizeThreshold -= map->calculateSize(aWBXML, aVersion); // Add at least one MapItem to the Map package do { SyncMLMapItem* mapItem = new SyncMLMapItem( iMappings[0].iRemoteUID, iMappings[0].iLocalUID ); aSizeThreshold -= mapItem->calculateSize(aWBXML, aVersion); map->addChild(mapItem); iMappings.removeFirst(); } while( aSizeThreshold > 0 && !iMappings.isEmpty() ); aMessage.addToBody(map); } return iMappings.isEmpty(); } buteo-syncml-0.5.15/src/LocalMappingsPackage.h000066400000000000000000000053651433763642500212160ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LOCALMAPPINGSPACKAGE_H #define LOCALMAPPINGSPACKAGE_H #include "Package.h" #include #include #include "SyncMLGlobals.h" class LocalMappingsPackageTest; namespace DataSync { /*! \brief LocalMappingsPackage handles sending local mappings phase for * a single sync target */ class LocalMappingsPackage : public Package { Q_OBJECT public: /*! \brief Constructor * * @param aSourceDatabase Source database * @param aTargetDatabase Target database * @param aMappings UID mappings */ LocalMappingsPackage( const QString& aSourceDatabase, const QString& aTargetDatabase, const QList& aMappings ); /*! \brief Destructor * */ virtual ~LocalMappingsPackage(); virtual bool write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ); protected: private: QString iSourceDatabase; QString iTargetDatabase; QList iMappings; friend class ::LocalMappingsPackageTest; }; } #endif // LOCALMAPPINGSPACKAGE_H buteo-syncml-0.5.15/src/NonceStorage.cpp000066400000000000000000000114071433763642500201250ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "NonceStorage.h" #include #include "SyncMLLogging.h" using namespace DataSync; NonceStorage::NonceStorage( QSqlDatabase& aDbHandle, const QString& aLocalDevice, const QString& aRemoteDevice ) : iDbHandle( aDbHandle ), iLocalDevice( aLocalDevice ), iRemoteDevice( aRemoteDevice ) { } NonceStorage::~NonceStorage() { } QByteArray NonceStorage::generateNonce() const { // @todo: QByteArray nonce = QByteArray::number( QDateTime::currentDateTime().toTime_t() ); qCDebug(lcSyncML) << "Generated nonce:" << nonce; return nonce; } QByteArray NonceStorage::nonce() { FUNCTION_CALL_TRACE(lcSyncMLTrace); QByteArray nonce; if( createNonceTable() ) { const QString queryString( "SELECT nonce FROM nonces WHERE local_device = :local_device AND remote_device = :remote_device" ); QSqlQuery query( iDbHandle ); query.prepare( queryString ); query.bindValue( ":local_device", iLocalDevice ); query.bindValue( ":remote_device", iRemoteDevice ); query.exec(); if( query.lastError().isValid() ) { qCWarning(lcSyncML) << "Query failed:" << query.lastError(); } else { if( query.next() ) { nonce = query.value(0).toByteArray(); } } } return nonce; } void NonceStorage::setNonce( const QByteArray& aNonce ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !createNonceTable() ) { return; } clearNonce(); const QString insertQuery( "INSERT INTO nonces(local_device, remote_device, nonce) values(:local_device, :remote_device, :nonce)" ); QSqlQuery query( iDbHandle ); query.prepare( insertQuery ); query.bindValue( ":local_device", iLocalDevice ); query.bindValue( ":remote_device", iRemoteDevice ); query.bindValue( ":nonce", aNonce ); query.exec(); if( query.lastError().isValid() ) { qCWarning(lcSyncML) << "Query failed: " << query.lastError(); } } void NonceStorage::clearNonce() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !createNonceTable() ) { return; } // Clear existing mappings const QString deleteQuery( "DELETE FROM nonces WHERE local_device = :local_device AND remote_device = :remote_device" ); QSqlQuery query( iDbHandle ); query.prepare( deleteQuery ); query.bindValue( ":local_device", iLocalDevice ); query.bindValue( ":remote_device", iRemoteDevice ); query.exec(); if( query.lastError().isValid() ) { qCWarning(lcSyncML) << "Query failed: " << query.lastError(); } } bool NonceStorage::createNonceTable() { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString = "CREATE TABLE IF NOT EXISTS nonces(id integer primary key autoincrement, local_device varchar(512), remote_device varchar(512), nonce varchar(512))"; QSqlQuery query( iDbHandle ); query.prepare( queryString ); query.exec(); bool success = true; if (query.lastError().isValid()) { success = false; qCWarning(lcSyncML) << "Query failed: " << query.lastError(); } return success; } buteo-syncml-0.5.15/src/NonceStorage.h000066400000000000000000000061371433763642500175760ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef NONCESTORAGE_H #define NONCESTORAGE_H #include class QSqlDatabase; namespace DataSync { /*! \brief Class for storing MD5 nonces * */ class NonceStorage { public: /*! \brief Constructor * * The order of devices means, that whenever aLocalDevice authenticates with * aRemoteDevice, it should use the specified nonce * * @param aDbHandle Database handle to use * @param aLocalDevice Local device to associate with * @param aRemoteDevice Remove device to associate with */ explicit NonceStorage( QSqlDatabase& aDbHandle, const QString& aLocalDevice, const QString& aRemoteDevice ); /*! \brief Destructor * */ virtual ~NonceStorage(); /*! \brief Generates a new nonce * * @return Generated nonce */ QByteArray generateNonce() const; /*! \brief Retrieves a nonce from storage * * @return Nonce if found, otherwise empty */ QByteArray nonce(); /*! \brief Sets a new nonce to storage * * * @param aNonce Nonce to store */ void setNonce( const QByteArray& aNonce ); /*! \brief Clears a nonce from storage * */ void clearNonce(); protected: /*! \brief Ensure that database table exists for Nonces * * @return True on success, otherwise false */ bool createNonceTable(); private: QSqlDatabase& iDbHandle; QString iLocalDevice; QString iRemoteDevice; }; } #endif // NONCESTORAGE_H buteo-syncml-0.5.15/src/Package.h000066400000000000000000000055211433763642500165360ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PACKAGE_H #define PACKAGE_H #include #include "SyncAgentConsts.h" namespace DataSync { class SyncMLMessage; struct StatusParams; /*! \brief Package is a group of information that is sent to remote party * * This information can be contents of a single storage, or just a single * Alert or Final element. This information may or may not require a response * in the form of a SyncML Status element; package can handle responses by * itself, or give a signal that someone else should handle the response. * */ class Package : public QObject { Q_OBJECT; public: /*! \brief Destructor * */ virtual ~Package() {} /*! \brief Serializes content of package to the given message * * The maximum size of data to serialize is given in aSizeThreshold. If true write was completed * and package can be deleted * * @param aMessage Message to serialize to * @param aSizeThreshold Maximum number of bytes to use. Is decreased for every * byte written. * @return * */ virtual bool write( SyncMLMessage& aMessage, int& aSizeThreshold, bool aWBXML, const ProtocolVersion& aVersion ) = 0; protected: private: }; } #endif // PACKAGE_H buteo-syncml-0.5.15/src/RemoteDeviceInfo.cpp000066400000000000000000000055121433763642500207250ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "RemoteDeviceInfo.h" #include "SyncMLLogging.h" using namespace DataSync; RemoteDeviceInfo::RemoteDeviceInfo() : iUTC( false ), iSupportLargeObjs( false ), iSupportNumberOfChanges( false ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } RemoteDeviceInfo::~RemoteDeviceInfo() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } DeviceInfo& RemoteDeviceInfo::deviceInfo() { return iDeviceInfo; } const DeviceInfo& RemoteDeviceInfo::deviceInfo() const { return iDeviceInfo; } QList& RemoteDeviceInfo::datastores() { return iDatastores; } const QList& RemoteDeviceInfo::datastores() const { return iDatastores; } void RemoteDeviceInfo::setSupportsUTC( bool aUTC ) { iUTC = aUTC; } bool RemoteDeviceInfo::getSupportsUTC() const { return iUTC; } void RemoteDeviceInfo::setSupportsLargeObjs( bool aSupportsLargeObjs ) { iSupportLargeObjs = aSupportsLargeObjs; } bool RemoteDeviceInfo::getSupportsLargeObjs() const { return iSupportLargeObjs; } void RemoteDeviceInfo::setSupportsNumberOfChanges( bool aSupportsNumberOfChanges ) { iSupportNumberOfChanges = aSupportsNumberOfChanges; } bool RemoteDeviceInfo::getSupportsNumberOfChanges() const { return iSupportNumberOfChanges; } buteo-syncml-0.5.15/src/RemoteDeviceInfo.h000066400000000000000000000072431433763642500203750ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef REMOTEDEVICEINFO_H #define REMOTEDEVICEINFO_H #include "DeviceInfo.h" #include "DataStore.h" namespace DataSync { /*! \brief Describes capabilities of remote device as received from protocol * device info */ class RemoteDeviceInfo { public: /*! \brief Constructor * */ RemoteDeviceInfo(); /*! \brief Destructor * */ ~RemoteDeviceInfo(); /*! \brief Access device info * * @return */ DeviceInfo& deviceInfo(); /*! \brief Access device info * * @return */ const DeviceInfo& deviceInfo() const; /*! \brief Find index of datastore based on source URI * * @param aURI Source URI * @return */ int findDatastore( const QString& aURI ); /*! \brief Access list of datastores * * @return */ QList& datastores(); /*! \brief Access list of datastores * * @return */ const QList& datastores() const; /*! \brief Sets flag for UTC support * * @param aUTC Value to set */ void setSupportsUTC( bool aUTC ); /*! \brief Retrieve flag for UTC support * * @return */ bool getSupportsUTC() const; /*! \brief Sets flag for large object support * * @param aSupportsLargeObjs Value to set */ void setSupportsLargeObjs( bool aSupportsLargeObjs ); /*! \brief Retrieves flag for large object support * * @return */ bool getSupportsLargeObjs() const; /*! \brief Sets flag for sending number of changes support * * @param aSupportsNumberOfChanges */ void setSupportsNumberOfChanges( bool aSupportsNumberOfChanges ); /*! \brief Retrieves flag for sending number of changes support * * @return */ bool getSupportsNumberOfChanges() const; private: DeviceInfo iDeviceInfo; QList iDatastores; bool iUTC; bool iSupportLargeObjs; bool iSupportNumberOfChanges; }; } #endif // REMOTEDEVICEINFO_H buteo-syncml-0.5.15/src/RequestListener.cpp000066400000000000000000000171741433763642500207030ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "RequestListener.h" #include "SyncMLLogging.h" using namespace DataSync; RequestListener::RequestListener( QObject* aParent ) : QObject( aParent ), iTransport( 0 ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } RequestListener::~RequestListener() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qDeleteAll( iRequestData.iFragments); iRequestData.iFragments.clear(); } bool RequestListener::start( Transport* aTransport ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !aTransport ) { return false; } iTransport = aTransport; connect( iTransport, SIGNAL(sendEvent(DataSync::TransportStatusEvent, QString )), this, SLOT(transportEvent(DataSync::TransportStatusEvent , QString )) ); connect( iTransport, SIGNAL(readXMLData(QIODevice *, bool)) , &iParser, SLOT(parseResponse(QIODevice *, bool)) ); connect( &iParser, SIGNAL(parsingComplete(bool)), this, SLOT(parsingComplete(bool)) ); connect( &iParser, SIGNAL( parsingError(DataSync::ParserError)), this, SLOT(parserError(DataSync::ParserError)) ); connect( iTransport, SIGNAL(readSANData(QIODevice *)) , this, SLOT(SANPackageReceived(QIODevice *)) ); return iTransport->receive(); } void RequestListener::stop() { FUNCTION_CALL_TRACE(lcSyncMLTrace); disconnect( &iParser, 0, this, 0 ); disconnect( iTransport, SIGNAL(readXMLData(QIODevice *, bool)) , &iParser, SLOT(parseResponse(QIODevice *, bool)) ); if( iTransport ) { disconnect( iTransport, 0, this, 0 ); iTransport = 0; } } RequestListener::RequestData RequestListener::takeRequestData() { RequestData data = iRequestData; iRequestData.iFragments.clear(); return data; } void RequestListener::transportEvent( DataSync::TransportStatusEvent aEvent, QString aErrorString ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); stop(); switch (aEvent) { case TRANSPORT_CONNECTION_OPENED: case TRANSPORT_CONNECTION_CLOSED: { break; } case TRANSPORT_DATA_INVALID_CONTENT_TYPE: case TRANSPORT_DATA_INVALID_CONTENT: { emit error( INVALID_SYNCML_MESSAGE, aErrorString); break; } case TRANSPORT_CONNECTION_FAILED: case TRANSPORT_CONNECTION_TIMEOUT: case TRANSPORT_CONNECTION_ABORTED: case TRANSPORT_CONNECTION_AUTHENTICATION_NEEDED: { emit error( CONNECTION_ERROR , aErrorString ); break; } default: { qCDebug(lcSyncML) << "Unknown transport status code: " << aEvent; emit error( INTERNAL_ERROR, aErrorString ); break; } } } void RequestListener::parsingComplete( bool aLastMessageInPackage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_UNUSED( aLastMessageInPackage ); stop(); qCDebug(lcSyncML) << "SyncAgent: Received XML data, analyzing..."; QList fragments = iParser.takeFragments(); QList syncModes; for( int i = 0; i < fragments.count(); ++i ) { if( fragments[i]->fragmentType == Fragment::FRAGMENT_COMMAND ) { CommandParams* command = static_cast(fragments[i]); if( command->commandType == CommandParams::COMMAND_ALERT ) { SyncMode syncMode( command->data.toInt() ); if( syncMode.isValid() ) { syncModes.append( syncMode ); } } } } bool isValid = false; if( !syncModes.isEmpty() ) { if( syncModes[0].syncInitiator() == INIT_CLIENT ) { qCDebug(lcSyncML) << "SyncAgent: XML data recognized as sent by client"; iRequestData.iType = REQUEST_CLIENT; isValid = true; } else if( syncModes[0].syncInitiator() == INIT_SERVER ) { qCDebug(lcSyncML) << "SyncAgent: XML data recognized as sent by server"; iRequestData.iType = REQUEST_SAN_XML; isValid = true; } else { qCCritical(lcSyncML) << "Could not recognize alert code"; } } else { qCCritical(lcSyncML) << "Could not find any alerts from received XML data!"; } if( isValid ) { iRequestData.iFragments = fragments; emit newPendingRequest(); } else { qDeleteAll(fragments); fragments.clear(); emit error( INVALID_SYNCML_MESSAGE, "Invalid SyncML message" ); } } void RequestListener::parserError( DataSync::ParserError aError ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); stop(); switch (aError) { case PARSER_ERROR_INCOMPLETE_DATA: { emit error( INVALID_SYNCML_MESSAGE, "Parser error: incomplete data" ); break; } case PARSER_ERROR_UNEXPECTED_DATA: { emit error( INVALID_SYNCML_MESSAGE, "Parser error: unexpected data" ); break; } case PARSER_ERROR_INVALID_DATA: { emit error( INVALID_SYNCML_MESSAGE, "Parser error: invalid data" ); break; } default: { emit error( INVALID_SYNCML_MESSAGE, "Unspecified error" ); break; } } } void RequestListener::SANPackageReceived( QIODevice* aDevice ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "SyncAgent: Received SAN data, processing..."; QByteArray package = aDevice->readAll(); SANHandler parser; iRequestData.iType = REQUEST_SAN_PACKAGE; qDeleteAll( iRequestData.iFragments ); iRequestData.iFragments.clear(); if( parser.parseSANMessageDS( package, iRequestData.iSANData ) ) { qCDebug(lcSyncML) << "SyncAgent: SAN package processed"; emit newPendingRequest(); } else { qCCritical(lcSyncML) << "Parsing of SAN package failed"; emit error( INVALID_SYNCML_MESSAGE, "Parsing of 1.2 SAN package failed" ); } } buteo-syncml-0.5.15/src/RequestListener.h000066400000000000000000000104331433763642500203370ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef REQUESTLISTENER_H #define REQUESTLISTENER_H #include #include "SyncMLMessageParser.h" #include "ServerAlertedNotification.h" #include "Transport.h" namespace DataSync { /*! \brief Class that listens for incoming requests for server session by OMA * DS clients, or incoming server alerted notifications by OMA DS * servers */ class RequestListener : public QObject { Q_OBJECT; public: /*! \brief Constructor * * @param aParent Parent of this object */ RequestListener( QObject* aParent = 0 ); /*! \brief Destructor * */ virtual ~RequestListener(); /*! \brief Types of requests supported * */ enum RequestType { REQUEST_SAN_XML, ///< SAN notification message (usually OMA DS 1.1) REQUEST_SAN_PACKAGE, ///< SAN notification package (usually OMA DS 1.2) REQUEST_CLIENT ///< OMA DS XML initialization request sent by client }; /*! \brief Processed data of a request * */ struct RequestData { RequestType iType; ///< Type of the request SANDS iSANData; ///< Package fields of the request if SAN package QList iFragments; ///< Protocol fragments if the request was XML }; /*! \brief Start listening for incoming requests * * @param aTransport Transport to use * @return True if listening was successfully started, otherwise false */ bool start( Transport* aTransport ); /*! \brief Stop listening for incoming requests * */ void stop(); /*! \brief Retrieve data of a pending request * * @return Data of pending request. Ownership is transferred */ RequestData takeRequestData(); signals: /*! \brief Signal emitted when there's a new pending request * * Listening is automatically stopped when a new request comes */ void newPendingRequest(); /*! \brief Signal emitted when an error has occurred during listening * * Listening is automatically stopped when an error occurs * @param aState Error state * @param aErrorString Developer-oriented, human-readable description */ void error( DataSync::SyncState aState, QString aErrorString ); private slots: void transportEvent( DataSync::TransportStatusEvent aEvent, QString aErrorString ); void parsingComplete( bool aLastMessageInPackage ); void parserError( DataSync::ParserError aError ); void SANPackageReceived( QIODevice* aDevice ); private: Transport* iTransport; SyncMLMessageParser iParser; RequestData iRequestData; }; } #endif // REQUESTLISTENER_H buteo-syncml-0.5.15/src/ResponseGenerator.cpp000066400000000000000000000333751433763642500212130ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ResponseGenerator.h" #include #include "Package.h" #include "SyncMLMessage.h" #include "SyncMLStatus.h" #include "SyncMLAlert.h" #include "datatypes.h" #include "SyncMLLogging.h" using namespace DataSync; ResponseGenerator::ResponseGenerator() : iMaxMsgSize( 0 ), iMsgId( 0 ), iRemoteMsgId( 0 ), iIgnoreStatuses( false ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } ResponseGenerator::~ResponseGenerator() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qDeleteAll( iStatuses ); iStatuses.clear(); clearPackageQueue(); } const HeaderParams& ResponseGenerator::getHeaderParams() const { return iHeaderParams; } void ResponseGenerator::setHeaderParams( const HeaderParams& aHeaderParams ) { iHeaderParams = aHeaderParams; } void ResponseGenerator::setRemoteMsgId( int aRemoteMsgId ) { iRemoteMsgId = aRemoteMsgId; } int ResponseGenerator::getRemoteMsgId() const { return iRemoteMsgId; } SyncMLMessage* ResponseGenerator::generateNextMessage( int aMaxSize, const ProtocolVersion& aVersion, bool aWbXML ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool useWbXml = false; qCDebug(lcSyncML) << "MaxMsg size"<calculateSize(useWbXml, aVersion); qCDebug(lcSyncML) << "useWbxml"<( MAXMSGOVERHEADRATIO * aMaxSize), MINMSGOVERHEADBYTES ); int messageSizeThreshold = aMaxSize - overhead; int remainingBytes = messageSizeThreshold - messageSize; while( iStatuses.count() > 0 ) { StatusParams* params = iStatuses.first(); params->cmdId = message->getNextCmdId(); SyncMLStatus* statusObject = new SyncMLStatus( *params ); delete params; iStatuses.removeFirst(); message->addToBody( statusObject ); remainingBytes -= statusObject->calculateSize(useWbXml, aVersion); if( remainingBytes < 0 ) { break; } } while( ( remainingBytes > 0 ) && ( iPackages.count() > 0 ) ) { Package* package = iPackages.first(); if( package->write( *message, remainingBytes, useWbXml, aVersion ) ) { delete package; iPackages.removeFirst(); } else { break; } } qCDebug(lcSyncML) << "MessageSize:"<calculateSize(useWbXml, aVersion); qCDebug(lcSyncML) << "Message generated with following parameters:"; qCDebug(lcSyncML) << "Maximum size reported by remote device:" << aMaxSize; qCDebug(lcSyncML) << "Estimated overhead:" << overhead; qCDebug(lcSyncML) << "Message size threshold value was:" << messageSizeThreshold; qCDebug(lcSyncML) << "Remaining bytes was:" << remainingBytes; return message; } void ResponseGenerator::addPackage( Package* aPackage ) { iPackages.append( aPackage ); } void ResponseGenerator::clearPackageQueue() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qDeleteAll( iPackages ); iPackages.clear(); } bool ResponseGenerator::packageQueueEmpty() const { return iPackages.isEmpty(); } const QList& ResponseGenerator::getPackages() const { return iPackages; } void ResponseGenerator::ignoreStatuses( bool aIgnore ) { iIgnoreStatuses = aIgnore; } void ResponseGenerator::addStatus( StatusParams* aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iIgnoreStatuses ) { if( SYNCML_ELEMENT_SYNCHDR == aParams->cmd ) { // Status for SyncHdr is always in the beginning iStatuses.prepend( aParams ); } else { iStatuses.append( aParams ); } } else { delete aParams; aParams = 0; } } void ResponseGenerator::addStatus( const HeaderParams& aParams, ResponseStatusCode aStatusCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Bypass iIgnoreStatuses flag: Status for SyncHdr should always be written StatusParams* statusParams = new StatusParams; statusParams->msgRef = aParams.msgID; statusParams->cmdRef = 0; statusParams->cmd = SYNCML_ELEMENT_SYNCHDR; statusParams->targetRef = aParams.targetDevice; statusParams->sourceRef = aParams.sourceDevice; statusParams->data = aStatusCode; iStatuses.append( statusParams ); } void ResponseGenerator::addStatus( const HeaderParams& aParams, const ChalParams& aChalParams, ResponseStatusCode aStatusCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Bypass iIgnoreStatuses flag: Status for SyncHdr should always be written StatusParams* statusParams = new StatusParams; statusParams->msgRef = aParams.msgID; statusParams->cmdRef = 0; statusParams->cmd = SYNCML_ELEMENT_SYNCHDR; statusParams->targetRef = aParams.targetDevice; statusParams->sourceRef = aParams.sourceDevice; statusParams->data = aStatusCode; statusParams->chal = aChalParams; iStatuses.append( statusParams ); } void ResponseGenerator::addStatus( const CommandParams& aParams, ResponseStatusCode aStatusCode, bool aWriteItemRefs ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iIgnoreStatuses ) { return; } StatusParams* statusParams = new StatusParams; statusParams->msgRef = iRemoteMsgId; statusParams->cmdRef = aParams.cmdId; statusParams->data = aStatusCode; if( aParams.commandType == CommandParams::COMMAND_ALERT ) { statusParams->cmd = SYNCML_ELEMENT_ALERT; // @todo: this could be made better if( !aParams.items.isEmpty() ) { statusParams->nextAnchor = aParams.items.first().meta.anchor.next; } } else if( aParams.commandType == CommandParams::COMMAND_ADD ) { statusParams->cmd = SYNCML_ELEMENT_ADD; } else if( aParams.commandType == CommandParams::COMMAND_REPLACE ) { statusParams->cmd = SYNCML_ELEMENT_REPLACE; } else if( aParams.commandType == CommandParams::COMMAND_DELETE ) { statusParams->cmd = SYNCML_ELEMENT_DELETE; } else if( aParams.commandType == CommandParams::COMMAND_GET ) { statusParams->cmd = SYNCML_ELEMENT_GET; } else if( aParams.commandType == CommandParams::COMMAND_COPY ) { statusParams->cmd = SYNCML_ELEMENT_COPY; } else if( aParams.commandType == CommandParams::COMMAND_MOVE ) { statusParams->cmd = SYNCML_ELEMENT_MOVE; } else if( aParams.commandType == CommandParams::COMMAND_EXEC ) { statusParams->cmd = SYNCML_ELEMENT_EXEC; } else if( aParams.commandType == CommandParams::COMMAND_ATOMIC ) { statusParams->cmd = SYNCML_ELEMENT_ATOMIC; } else if( aParams.commandType == CommandParams::COMMAND_SEQUENCE ) { statusParams->cmd = SYNCML_ELEMENT_SEQUENCE; } else { Q_ASSERT(0); } if( aWriteItemRefs ) { if( aParams.items.count() == 1 ) { statusParams->sourceRef = aParams.items.first().source; statusParams->targetRef = aParams.items.first().target; } else { for( int i = 0; i < aParams.items.count(); ++i ) { ItemParams item; item.source = aParams.items[i].source; item.target = aParams.items[i].target; statusParams->items.append(item); } } } addStatus( statusParams ); } void ResponseGenerator::addStatus( const CommandParams& aParams, ResponseStatusCode aStatusCode, const QList& aItemIndexes ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iIgnoreStatuses ) { return; } StatusParams* statusParams = new StatusParams; statusParams->msgRef = iRemoteMsgId; statusParams->cmdRef = aParams.cmdId; statusParams->data = aStatusCode; if( aParams.commandType == CommandParams::COMMAND_ALERT ) { statusParams->cmd = SYNCML_ELEMENT_ALERT; // @todo: this could be made better if( !aParams.items.isEmpty() ) { statusParams->nextAnchor = aParams.items.first().meta.anchor.next; } } else if( aParams.commandType == CommandParams::COMMAND_ADD ) { statusParams->cmd = SYNCML_ELEMENT_ADD; } else if( aParams.commandType == CommandParams::COMMAND_REPLACE ) { statusParams->cmd = SYNCML_ELEMENT_REPLACE; } else if( aParams.commandType == CommandParams::COMMAND_DELETE ) { statusParams->cmd = SYNCML_ELEMENT_DELETE; } else if( aParams.commandType == CommandParams::COMMAND_GET ) { statusParams->cmd = SYNCML_ELEMENT_GET; } else if( aParams.commandType == CommandParams::COMMAND_COPY ) { statusParams->cmd = SYNCML_ELEMENT_COPY; } else if( aParams.commandType == CommandParams::COMMAND_MOVE ) { statusParams->cmd = SYNCML_ELEMENT_MOVE; } else if( aParams.commandType == CommandParams::COMMAND_EXEC ) { statusParams->cmd = SYNCML_ELEMENT_EXEC; } else if( aParams.commandType == CommandParams::COMMAND_ATOMIC ) { statusParams->cmd = SYNCML_ELEMENT_ATOMIC; } else if( aParams.commandType == CommandParams::COMMAND_SEQUENCE ) { statusParams->cmd = SYNCML_ELEMENT_SEQUENCE; } else { Q_ASSERT(0); } if( aItemIndexes.count() == 1 ) { statusParams->sourceRef = aParams.items[aItemIndexes.first()].source; statusParams->targetRef = aParams.items[aItemIndexes.first()].target; } else { for( int i = 0; i < aItemIndexes.count(); ++i ) { ItemParams item; item.source = aParams.items[aItemIndexes.at(i)].source; item.target = aParams.items[aItemIndexes.at(i)].target; statusParams->items.append(item); } } addStatus( statusParams ); } void ResponseGenerator::addStatus( const SyncParams& aParams, ResponseStatusCode aStatusCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iIgnoreStatuses ) { return; } StatusParams* statusParams = new StatusParams; statusParams->msgRef = iRemoteMsgId; statusParams->cmdRef = aParams.cmdId; statusParams->cmd = SYNCML_ELEMENT_SYNC; statusParams->targetRef = aParams.target; statusParams->sourceRef = aParams.source; statusParams->data = aStatusCode; addStatus( statusParams ); } void ResponseGenerator::addStatus( const MapParams& aParams, ResponseStatusCode aStatusCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iIgnoreStatuses ) { return; } StatusParams* statusParams = new StatusParams; statusParams->msgRef = iRemoteMsgId; statusParams->cmdRef = aParams.cmdId; statusParams->cmd = SYNCML_ELEMENT_MAP; statusParams->targetRef = aParams.target; statusParams->sourceRef = aParams.source; statusParams->data = aStatusCode; addStatus( statusParams ); } void ResponseGenerator::addStatus( const ResultsParams& aParams, ResponseStatusCode aStatusCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iIgnoreStatuses ) { return; } StatusParams* statusParams = new StatusParams; statusParams->msgRef = iRemoteMsgId; statusParams->cmdRef = aParams.cmdId; statusParams->cmd = SYNCML_ELEMENT_RESULTS; statusParams->data = aStatusCode; addStatus( statusParams ); } void ResponseGenerator::addStatus( const PutParams& aParams, ResponseStatusCode aStatusCode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iIgnoreStatuses ) { return; } StatusParams* statusParams = new StatusParams; statusParams->msgRef = iRemoteMsgId; statusParams->cmdRef = aParams.cmdId; statusParams->cmd = SYNCML_ELEMENT_PUT; statusParams->data = aStatusCode; statusParams->sourceRef = aParams.devInf.source; addStatus( statusParams ); } const QList& ResponseGenerator::getStatuses() const { return iStatuses; } int ResponseGenerator::getNextMsgId() { return ++iMsgId; } buteo-syncml-0.5.15/src/ResponseGenerator.h000066400000000000000000000167561433763642500206640ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef RESPONSEGENERATOR_H #define RESPONSEGENERATOR_H #include #include "SyncAgentConsts.h" #include "Fragments.h" class QString; namespace DataSync { class Package; class SyncMLMessage; struct StatusParams; /*! \brief Class that contains all of the data of one request sent to the server. * */ class ResponseGenerator { public: /*! \brief Constructor * */ ResponseGenerator(); /*! \brief Destructor * */ virtual ~ResponseGenerator(); /*! \brief Retrieve SyncML header parameters * * @return */ const HeaderParams& getHeaderParams() const; /*! \brief Set SyncML header parameters * * msgId field is ignored as this is filled by response generator * * @param aHeaderParams */ void setHeaderParams( const HeaderParams& aHeaderParams ); /*! \brief Set remote message id * * Remote message id is used when status elements are generated, as they require * msgRef field * * @param aRemoteMsgId Remote message id */ void setRemoteMsgId( int aRemoteMsgId ); /*! \brief Get remote message id * * Remote message id is used when status elements are generated, as they require * msgRef field * * @return */ int getRemoteMsgId() const; /*! \brief Generate next message * * @param aMaxSize Maximum size of the message * @param aVersion Protocol version to use * @param aWbXML If generated message will be converted to WbXML, take increased * compression into account in size calculations * @return SyncML message on success, otherwise NULL */ SyncMLMessage* generateNextMessage( int aMaxSize, const ProtocolVersion& aVersion, bool aWbXML = false ); /*! \brief Add package to package queue for sending * * @param aPackage Package. Ownership IS transferred */ void addPackage( Package* aPackage ); /*! \brief Clears the contents of package queue by removing all packages * */ void clearPackageQueue(); /*! \brief Returns true if package queue is empty * * @return */ bool packageQueueEmpty() const; /*! \brief Get list of current packages * * Ownership is NOT transferred * @return */ const QList& getPackages() const; /*! \brief Sets whether status messages added should be ignored or written * * This is used when there's noResp specified in SyncHdr and no status messages * should be sent back. Exception is status messages with challenges; they are * never ignored */ void ignoreStatuses( bool aIgnore ); /*! \brief Adds a status to the next outgoing message from already constructed Status data * * @param aParams Parameters of the status. Ownership IS transferred */ void addStatus( StatusParams* aParams ); /*! \brief Adds a status to the next outgoing message from SyncHdr data * * @param aParams SyncHdr params * @param aStatusCode Status code */ void addStatus( const HeaderParams& aParams, ResponseStatusCode aStatusCode ); /*! \brief Adds a status to the next outgoing message from SyncHdr data * * @param aParams SyncHdr params * @param aChalParams Authentication challenge params * @param aStatusCode Status code */ void addStatus( const HeaderParams& aParams, const ChalParams& aChalParams, ResponseStatusCode aStatusCode ); /*! \brief Adds a status to the next outgoing message from command data * * @param aParams Command params * @param aStatusCode Status code * @param aWriteItemRefs True if references of the Items(s) of the command should be * written to the status */ void addStatus( const CommandParams& aParams, ResponseStatusCode aStatusCode, bool aWriteItemRefs ); /*! \brief Adds a status to the next outgoing message from command data * * @param aParams Command params * @param aStatusCode Status code * @param aItemIndexes List of item indexes which should be referenced in the status */ void addStatus( const CommandParams& aParams, ResponseStatusCode aStatusCode, const QList& aItemIndexes ); /*! \brief Adds a status to the next outgoing message from Sync data * * @param aParams Sync params * @param aStatusCode Status code */ void addStatus( const SyncParams& aParams, ResponseStatusCode aStatusCode ); /*! \brief Adds a status to the next outgoing message from Map data * * @param aParams Map element parameters * @param aStatusCode Status code */ void addStatus( const MapParams& aParams, ResponseStatusCode aStatusCode ); /*! \brief Adds a status to the next outgoing message from PutParams data * * @param aParams PutParams element parameters * @param aStatusCode Status code */ void addStatus( const PutParams& aParams, ResponseStatusCode aStatusCode ); /*! \brief Adds a status to the next outgoing message from ResultsParams data * * @param aParams ResultsParams element parameters * @param aStatusCode Status code */ void addStatus( const ResultsParams& aParams, ResponseStatusCode aStatusCode ); /*! \brief Returns current list of statuses * * @return */ const QList& getStatuses() const; protected: /*! \brief Retrieve id that should be used for next message * * @return */ int getNextMsgId(); private: int iMaxMsgSize; int iMsgId; int iRemoteMsgId; HeaderParams iHeaderParams; QList iStatuses; QList iPackages; bool iIgnoreStatuses; }; } #endif // RESPONSEGENERATOR_H buteo-syncml-0.5.15/src/ServerAlertedNotification.cpp000066400000000000000000000303551433763642500226570ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ServerAlertedNotification.h" #include #include "SyncMLLogging.h" using namespace DataSync; // MD5 digest is 128 bits, which is 16 bytes #define DIGEST_SIZE 16 // SAN Header is 8 bytes (excluding server identified) #define HEADER_SIZE 8 // SyncML version 1.1 (0000001011) #define SYNCMLVERSION_1_1 0x0B // SyncML version 1.2 (0000001100) #define SYNCMLVERSION_1_2 0x0C #define UIMODE_NOT_SPECIFIED 0x00 #define UIMODE_BACKGROUND 0x10 #define UIMODE_INFORMATIVE 0x20 #define UIMODE_USER_INTERACTION 0x30 #define INITIATOR_USER 0x00 #define INITIATOR_SERVER 0x08 #define MAX_SERVERURI_LENGTH 255 #define SYNCALERT_BASE 200 // Supported WSP content types // From: http://www.wapforum.org/wina/wsp-content-type.htm #define WSP_CONTACTS_ID 0x07 #define WSP_CONTACTS_MIME "text/x-vcard" #define WSP_CALENDAR_ID 0x06 #define WSP_CALENDAR_MIME "text/x-vcalendar" #define WSP_NOTES_ID 0x03 #define WSP_NOTES_MIME "text/plain" SANHandler::SANHandler() { } SANHandler::~SANHandler() { } bool SANHandler::checkDigest( const QByteArray& aMessage, const QString& aServerIdentifier, const QString& aPassword, const QString& aNonce ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QByteArray messageDigest = aMessage.left( DIGEST_SIZE ); QByteArray messageNotification = aMessage.mid( DIGEST_SIZE ); QByteArray digest = generateDigest( aServerIdentifier, aPassword, aNonce, messageNotification ); if( digest == messageDigest ) { return true; } else { return false; } } bool SANHandler::parseSANMessageDM( const QByteArray& aMessage, SANDM& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Parsing SAN message of" << aMessage.size() << "bytes"; QByteArray notification; if( !parseCommon( aMessage, aData.iDigest, aData.iHeader, notification ) ) { return false; } if( !notification.isEmpty() ) { qCWarning(lcSyncML) << "Invalid notification body"; return false; } return true; } bool SANHandler::parseSANMessageDS( const QByteArray &aMessage, SANDS &aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Parsing SAN message of" << aMessage.size() << "bytes"; QByteArray notification; if( !parseCommon( aMessage, aData.iDigest, aData.iHeader, notification ) ) { return false; } if( notification.isEmpty() ) { qCWarning(lcSyncML) << "Invalid notification body"; return false; } int numberOfSyncs = notification[0] >> 4; if( numberOfSyncs == 0 ) { qCWarning(lcSyncML) << "Syncing of all data stores not supported"; return false; } int pos = 1; for( int i = 0; i< numberOfSyncs; ++i ) { // Check that SyncInfo is at least 5 bytes long if( notification.size() - pos < 5 ) { qCWarning(lcSyncML) << "Invalid sync info"; return false; } SANSyncInfo syncInfo; syncInfo.iSyncType = SYNCALERT_BASE + ( notification[pos++] >> 4 ); long contentType = notification[pos] << 16 | notification[pos+1] << 8 | notification[pos+2]; pos += 3; // WSP Content type mapping if( contentType == WSP_CONTACTS_ID ){ syncInfo.iContentType = WSP_CONTACTS_MIME; } else if( contentType == WSP_CALENDAR_ID ) { syncInfo.iContentType = WSP_CALENDAR_MIME; } else if( contentType == WSP_NOTES_ID ) { syncInfo.iContentType = WSP_NOTES_MIME; } else if( contentType != 0 ) { qCWarning(lcSyncML) << "Unsupported WSP Content type:" << contentType; } char serverURILength = notification[pos++]; QByteArray serverURI = notification.mid( pos, serverURILength ); if( serverURI.length() != serverURILength ) { qCWarning(lcSyncML) << "Invalid server URI"; return false; } syncInfo.iServerURI = serverURI; pos += serverURILength; aData.iSyncInfo.append( syncInfo ); } return true; } bool SANHandler::generateSANMessageDS( const SANDS &aData, const QString &aPassword, const QString &aNonce, QByteArray &aMessage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QByteArray notification; // Write version, UI-mode, initiator unsigned char highByte = 0; unsigned char lowByte = 0; if( aData.iHeader.iVersion == SYNCML_1_1 ) { highByte = SYNCMLVERSION_1_1 >> 2; lowByte = (unsigned char)(SYNCMLVERSION_1_1 << 8); } else if( aData.iHeader.iVersion == SYNCML_1_2 ) { highByte = SYNCMLVERSION_1_2 >> 2; lowByte = (unsigned char)(SYNCMLVERSION_1_2 << 8); } else { qCWarning(lcSyncML) << "Unsupported version: " << aData.iHeader.iVersion; return false; } if( aData.iHeader.iUIMode == SANUIMODE_NOT_SPECIFIED ) { lowByte |= UIMODE_NOT_SPECIFIED; } else if( aData.iHeader.iUIMode == SANUIMODE_BACKGROUND ) { lowByte |= UIMODE_BACKGROUND; } else if( aData.iHeader.iUIMode == SANUIMODE_INFORMATIVE ) { lowByte |= UIMODE_INFORMATIVE; } else if( aData.iHeader.iUIMode == SANUIMODE_USER_INTERACTION ) { lowByte |= UIMODE_USER_INTERACTION; } else { qCWarning(lcSyncML) << "Unsupported user interaction mode:" << aData.iHeader.iUIMode; return false; } if( aData.iHeader.iInitiator == SANINITIATOR_USER ) { lowByte |= INITIATOR_USER; } else if( aData.iHeader.iInitiator == SANINITIATOR_SERVER ) { lowByte |= INITIATOR_SERVER; } else { qCWarning(lcSyncML) << "Unsupported initiator of the notification:" << aData.iHeader.iInitiator; return false; } notification.fill( 0, HEADER_SIZE ); notification[0] = highByte; notification[1] = lowByte; int serverIdentifierLength = aData.iHeader.iServerIdentifier.size(); if( serverIdentifierLength > MAX_SERVERURI_LENGTH ) { qCWarning(lcSyncML) << "Server identifier lenght more than 255 characters"; return false; } notification[7] = (unsigned char)serverIdentifierLength; notification.append( aData.iHeader.iServerIdentifier.toLatin1() ); // Special case for syncing all data storages if no sync infos were specified unsigned char numSync = 0; if( aData.iSyncInfo.count() > 0 ) { numSync = aData.iSyncInfo.count() << 4; } notification.append( numSync ); for( int i = 0; i < aData.iSyncInfo.count(); ++i ) { const SANSyncInfo& info = aData.iSyncInfo[i]; unsigned char syncType = (info.iSyncType - SYNCALERT_BASE) << 4; qint32 contentType = 0; if( info.iContentType == WSP_CONTACTS_MIME ) { contentType = WSP_CONTACTS_ID; } else if( info.iContentType == WSP_CALENDAR_MIME ) { contentType = WSP_CALENDAR_ID; } else if( info.iContentType == WSP_NOTES_MIME ) { contentType = WSP_NOTES_ID; } else if( !info.iContentType.isEmpty() ) { qCWarning(lcSyncML) << "Unsupported WSP Content type:" << info.iContentType; } notification.append( syncType ); notification.append( ( contentType & 0x00FF0000 ) >> 16 ); notification.append( ( contentType & 0x0000FF00 ) >> 8 ); notification.append( contentType & 0x000000FF ); notification.append( info.iServerURI.length() ); notification.append( info.iServerURI.toLatin1() ); } aMessage = generateDigest( aData.iHeader.iServerIdentifier, aPassword, aNonce, notification ); aMessage.append( notification ); return true; } bool SANHandler::parseCommon( const QByteArray& aMessage, QByteArray& aDigest, SANHeader& aHeader, QByteArray& aBody ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); aDigest = aMessage.left( DIGEST_SIZE ); QByteArray header = aMessage.mid( DIGEST_SIZE, HEADER_SIZE ); if( aDigest.size() != DIGEST_SIZE ) { qCWarning(lcSyncML) << "Invalid digest"; return false; } if( header.size() != HEADER_SIZE ) { qCWarning(lcSyncML) << "Invalid header"; return false; } qCDebug(lcSyncML) << "SAN digest:" << aDigest.toHex(); qCDebug(lcSyncML) << "SAN header:" << header.toHex(); int version = ( header[0] << 2 ) | ( header[1] >> 6 ); char uimode = ( header[1] >> 4 ) & 0x03; bool initiator = ( header[1] >> 3 ) & 0x01; qint16 sessionId = ( header[5] << 8 ) | header[6]; if( version == SYNCMLVERSION_1_1 ) { aHeader.iVersion = SYNCML_1_1; } else if( version == SYNCMLVERSION_1_2 ) { aHeader.iVersion = SYNCML_1_2; } else { qCWarning(lcSyncML) << "Unsupported SyncML version"; return false; } aHeader.iUIMode = static_cast( uimode ); aHeader.iInitiator = static_cast( initiator ); aHeader.iSessionId = sessionId; int serverIdentifierLength = header[7]; QString serverIdentifier = aMessage.mid( DIGEST_SIZE + HEADER_SIZE, serverIdentifierLength ); if( serverIdentifier.length() != serverIdentifierLength ) { qCWarning(lcSyncML) << "Invalid server identifier"; return false; } aHeader.iServerIdentifier = serverIdentifier; aBody = aMessage.mid( DIGEST_SIZE + HEADER_SIZE + serverIdentifierLength ); return true; } // Digest = H(B64(H(server-identifier:password)):nonce:B64(H(notification))) // See SyncML Server Alerted Notification and DS Protocol specifications for more information QByteArray SANHandler::generateDigest( const QString& aServerIdentifier, const QString& aPassword, const QString& aNonce, const QByteArray& aNotification ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString colon( ":" ); QByteArray digest; QByteArray first; first.append( aServerIdentifier.toLatin1() ); first.append( colon ); first.append( aPassword.toLatin1() ); QByteArray second = QCryptographicHash::hash( first, QCryptographicHash::Md5 ).toBase64(); second.append( colon ); second.append( aNonce.toLatin1() ); second.append( colon ); second.append( QCryptographicHash::hash( aNotification, QCryptographicHash::Md5 ).toBase64() ); digest = QCryptographicHash::hash( second, QCryptographicHash::Md5 ); return digest; } buteo-syncml-0.5.15/src/ServerAlertedNotification.h000066400000000000000000000131621433763642500223210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SERVERALERTEDNOTIFICATION_H #define SERVERALERTEDNOTIFICATION_H #include #include #include "SyncMode.h" #include "SyncAgentConsts.h" namespace DataSync { /*! \brief SAN UI Mode * */ enum SANUIMode { SANUIMODE_NOT_SPECIFIED = 0, /*!< Not specified*/ SANUIMODE_BACKGROUND = 1, /*!< Background*/ SANUIMODE_INFORMATIVE = 2, /*!< Informative*/ SANUIMODE_USER_INTERACTION = 3 /*!< User interaction*/ }; /*! \brief SAN Initiator * */ enum SANInitiator { SANINITIATOR_USER = 0, /*!< User initiated action*/ SANINITIATOR_SERVER = 1 /*!< Server initiated action*/ }; /*! \brief SAN header * */ struct SANHeader { ProtocolVersion iVersion; /*!< Protocol version*/ SANUIMode iUIMode; /*!< User interaction mode*/ SANInitiator iInitiator; /*!< Notification initiator*/ qint16 iSessionId; /*!< Session ID*/ QString iServerIdentifier; /*!< Server identifier*/ }; /*! \brief SAN message specific to DM * */ struct SANDM { QByteArray iDigest; /*!< MD5 digest*/ SANHeader iHeader; /*!< Message header*/ }; /*! \brief SAN sync information * */ struct SANSyncInfo { int iSyncType; /*!< Sync type to user*/ QString iContentType; /*!< Content type*/ QString iServerURI; /*!< Remote database URI*/ }; /*! \brief SAN message specific to DS * */ struct SANDS { QByteArray iDigest; /*!< MD5 digest*/ SANHeader iHeader; /*!< Message header*/ QList iSyncInfo; /*!< Message sync info payload*/ }; /*! \brief Class for parsing and generating OMA DS 1.2 Server Alerted * Notification (SAN) message */ class SANHandler { public: /*! \brief Constructor * */ SANHandler(); /*! \brief Destructor * */ ~SANHandler(); /*! \brief Check MD5 digest of a SAN message * * @param aMessage Message to check * @param aServerIdentifier Identifier of the server * @param aPassword Password * @param aNonce Nonce * @return True if digest check passes, otherwise false */ bool checkDigest( const QByteArray& aMessage, const QString& aServerIdentifier, const QString& aPassword, const QString& aNonce ); /*! \brief Parse SAN message specific to DM * * @param aMessage Message to parse * @param aData Parsed message data on success * @return True on success, otherwise false */ bool parseSANMessageDM( const QByteArray& aMessage, SANDM& aData ); /*! \brief Parse SAN message specific to DS * * @param aMessage Message to parse * @param aData Parsed message data on success * @return True on success, otherwise false */ bool parseSANMessageDS( const QByteArray& aMessage, SANDS& aData ); /*! \brief Generate SAN message specific to DS * * @param aData Message data to use * @param aPassword Password for MD5 Digest * @param aNonce Nonce for MD5 Digest * @param aMessage Generated message on success * @return True on success, otherwise false */ bool generateSANMessageDS( const SANDS& aData, const QString& aPassword, const QString& aNonce, QByteArray& aMessage ); protected: private: bool parseCommon( const QByteArray& aMessage, QByteArray& aDigest, SANHeader& aHeader, QByteArray& aBody ); QByteArray generateDigest( const QString& aServerIdentifier, const QString& aPassword, const QString& aNonce, const QByteArray& aNotification ); }; } #endif // SERVERALERTEDNOTIFICATION_H buteo-syncml-0.5.15/src/SessionAuthentication.cpp000066400000000000000000000467321433763642500220720ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SessionAuthentication.h" #include "ResponseGenerator.h" #include "DatabaseHandler.h" #include "NonceStorage.h" #include "AuthenticationPackage.h" #include "AuthHelper.h" #include "SyncMLLogging.h" using namespace DataSync; SessionAuthentication::SessionAuthentication() : iAuthedToRemote( false ), iRemoteAuthPending( false ), iRemoteAuthed( false ), iLocalAuthPending( false ) { } SessionAuthentication::~SessionAuthentication() { } void SessionAuthentication::setSessionParams( AuthType aAuthType, const QString& aRemoteUsername, const QString& aRemotePassword, const QString& aRemoteNonce, const QString& aLocalUsername, const QString& aLocalPassword, const QString& aLocalNonce ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iAuthType = aAuthType; iRemoteUsername = aRemoteUsername; iRemotePassword = aRemotePassword; iRemoteNonce = aRemoteNonce; iLocalUsername = aLocalUsername; iLocalPassword = aLocalPassword; iLocalNonce = aLocalNonce; if( iAuthType == AUTH_NONE ) { iAuthedToRemote = true; iRemoteAuthPending = false; iRemoteAuthed = true; iLocalAuthPending = false; } else if( aLocalUsername.isEmpty() || aLocalPassword.isEmpty() ) { iAuthedToRemote = false; iRemoteAuthPending = false; iRemoteAuthed = true; iLocalAuthPending = false; } else { iAuthedToRemote = false; iRemoteAuthPending = false; iRemoteAuthed = false; iLocalAuthPending = false; } } bool SessionAuthentication::remoteIsAuthed() const { return iRemoteAuthed; } bool SessionAuthentication::authedToRemote() const { return iAuthedToRemote; } SessionAuthentication::HeaderStatus SessionAuthentication::analyzeHeader( const HeaderParams& aHeader, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName, ResponseGenerator& aResponseGenerator ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); HeaderStatus status = HEADER_NOT_HANDLED; if( !aHeader.cred.data.isEmpty() ) { // Remote device wants to authenticate to us if( !iRemoteAuthed ) { // Remote device is not yet authenticated to us status = handleAuthentication( aHeader, aDbHandler, aLocalDeviceName, aRemoteDeviceName, aResponseGenerator ); } else { // Remote device is already authenticated to us. This shouldn't happen as we don't do continuous authentication. iLastError = "Remote device attempted authentication when not expected"; status = HEADER_HANDLED_ABORT; } } return status; } SessionAuthentication::StatusStatus SessionAuthentication::analyzeHeaderStatus( const StatusParams& aStatus, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); StatusStatus status = STATUS_NOT_HANDLED; if( aStatus.data == SUCCESS ) { iAuthedToRemote = true; iRemoteAuthPending = false; status = STATUS_HANDLED_OK; } else if( aStatus.data == AUTH_ACCEPTED || aStatus.data == INVALID_CRED || aStatus.data == MISSING_CRED ) { // Clear possible nonce, because it was intended only for auth in this session NonceStorage nonces( aDbHandler.getDbHandle(), aLocalDeviceName, aRemoteDeviceName ); nonces.clearNonce(); // If remote party sent us a next nonce, save it QByteArray nonce = decodeNonce( aStatus.chal ); if( !nonce.isEmpty() ) { nonces.setNonce( nonce ); } if( aStatus.data == AUTH_ACCEPTED ) { // Authentication was accepted iAuthedToRemote = true; iRemoteAuthPending = false; status = STATUS_HANDLED_OK; } else { // Authentication was rejected iAuthedToRemote = false; if( iAuthType == AUTH_NONE ) { status = SessionAuthentication::STATUS_HANDLED_ABORT; iLastError = "Authentication required"; } else if( aStatus.hasChal ) { // Handle challenge status = handleChallenge( aStatus.chal, aDbHandler, aLocalDeviceName, aRemoteDeviceName ); } else { status = STATUS_HANDLED_ABORT; iLastError = "Authentication failed"; } } } return status; } void SessionAuthentication::composeAuthentication( ResponseGenerator& aResponseGenerator, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iAuthType == AUTH_BASIC ) { aResponseGenerator.addPackage( new AuthenticationPackage( iAuthType, iRemoteUsername, iRemotePassword ) ); iRemoteAuthPending = true; } else if( iAuthType == AUTH_MD5 ) { QByteArray remoteNonce = iRemoteNonce.toUtf8(); if( remoteNonce.isEmpty() ) { NonceStorage nonces( aDbHandler.getDbHandle(), aLocalDeviceName, aRemoteDeviceName ); remoteNonce = nonces.nonce(); } aResponseGenerator.addPackage( new AuthenticationPackage( iAuthType, iRemoteUsername, iRemotePassword, remoteNonce ) ); if( !remoteNonce.isEmpty() ) { iRemoteAuthPending = true; } else { // We didn't have a nonce, so authentication will probably fail. We need to hope that // remote device challenges us with a nonce, so don't put auth pending flag up. qCWarning(lcSyncML) << "MD5 authentication requested but no nonce found"; } } } QString SessionAuthentication::getLastError() const { return iLastError; } SessionAuthentication::HeaderStatus SessionAuthentication::handleAuthentication( const HeaderParams& aHeader, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName, ResponseGenerator& aResponseGenerator ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( iAuthType != AUTH_NONE ); // Check that format of the Cred data is something we can understand if( aHeader.cred.meta.format != SYNCML_FORMAT_ENCODING_B64 && !aHeader.cred.meta.format.isEmpty() ) { iLastError = "Unsupported format in Cred:" + aHeader.cred.meta.format; return HEADER_HANDLED_ABORT; } HeaderStatus status = HEADER_NOT_HANDLED; if( aHeader.cred.meta.type == SYNCML_FORMAT_AUTH_MD5 ) { // * If remote device wants to authenticate with MD5, always bump up to MD5 as it's more secure iAuthType = AUTH_MD5; // * Check if credentials are OK NonceStorage nonces( aDbHandler.getDbHandle(), aRemoteDeviceName, aLocalDeviceName ); QByteArray localNonce = iLocalNonce.toUtf8(); iLocalNonce.clear(); if( localNonce.isEmpty() ) { localNonce = nonces.nonce(); } AuthHelper helper; QByteArray md5 = helper.encodeMD5Auth( iLocalUsername, iLocalPassword, localNonce ); if( aHeader.cred.meta.format == SYNCML_FORMAT_ENCODING_B64 ) { md5 = md5.toBase64(); } if( md5 == aHeader.cred.data ) { // * Credentials OK, accept authentication qCDebug(lcSyncML) << "Authentication accepted"; iLocalAuthPending = false; iRemoteAuthed = true; ChalParams challenge = generateChallenge( nonces ); aResponseGenerator.addStatus( aHeader, challenge, AUTH_ACCEPTED ); status = HEADER_HANDLED_OK; } else if( iLocalAuthPending ) { // * Credentials not OK and we have already sent a challenge, fail authentication qCWarning(lcSyncML) << "Authentication failed"; iLastError = "Authentication failed"; iLocalAuthPending = false; iRemoteAuthed = false; aResponseGenerator.addStatus( aHeader, INVALID_CRED ); status = HEADER_HANDLED_ABORT; } else { // * Credentials not OK but we haven't yet sent a challenge, so send one qCWarning(lcSyncML) << "Authentication failed, sending challenge"; iLocalAuthPending = true; iRemoteAuthed = false; // Send challenge ChalParams challenge = generateChallenge( nonces ); aResponseGenerator.addStatus( aHeader, challenge, INVALID_CRED ); status = HEADER_HANDLED_OK; } } // If basic is explicitly specified, or if no type is specified, use basic else if( aHeader.cred.meta.type == SYNCML_FORMAT_AUTH_BASIC || aHeader.cred.meta.type.isEmpty() ) { if( iAuthType == AUTH_MD5 ) { // * Remote side wants to authenticate with BASIC when MD5 is enforced. if( iLocalAuthPending ) { // * Fail authentication as we have already sent a challenge for MD5 qCWarning(lcSyncML) << "Authentication failed"; iLastError = "Authentication failed"; iLocalAuthPending = false; iRemoteAuthed = false; aResponseGenerator.addStatus( aHeader, INVALID_CRED ); status = HEADER_HANDLED_ABORT; } else { // * Challenge remote device to use MD5 qCWarning(lcSyncML) << "MD5 authentication required, sending challenge"; iLocalAuthPending = true; iRemoteAuthed = false; // Send challenge ChalParams challenge = generateChallenge(); aResponseGenerator.addStatus( aHeader, challenge, INVALID_CRED ); status = HEADER_HANDLED_OK; } } else { AuthHelper helper; QByteArray basic = helper.encodeBasicB64Auth( iLocalUsername, iLocalPassword ); if( basic == aHeader.cred.data ) { // * Credentials OK, accept authentication qCDebug(lcSyncML) << "Authentication accepted"; iLocalAuthPending = false; iRemoteAuthed = true; aResponseGenerator.addStatus( aHeader, AUTH_ACCEPTED ); status = HEADER_HANDLED_OK; } else if( iLocalAuthPending ) { // * Credentials not OK and we have already sent a challenge, fail authentication qCWarning(lcSyncML) << "Authentication failed"; iLastError = "Authentication failed"; iLocalAuthPending = false; iRemoteAuthed = false; aResponseGenerator.addStatus( aHeader, INVALID_CRED ); status = HEADER_HANDLED_ABORT; } else { // * Credentials not OK but we haven't yet sent a challenge, so send one qCWarning(lcSyncML) << "Authentication failed, sending challenge"; iLocalAuthPending = true; iRemoteAuthed = false; // Send challenge ChalParams challenge = generateChallenge(); aResponseGenerator.addStatus( aHeader, challenge, INVALID_CRED ); status = HEADER_HANDLED_OK; } } } else { status = HEADER_HANDLED_ABORT; iLastError = "Unsupported authentication type encountered:" + aHeader.cred.meta.type; } return status; } SessionAuthentication::StatusStatus SessionAuthentication::handleChallenge( const ChalParams& aChallenge, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); StatusStatus status = STATUS_NOT_HANDLED; NonceStorage nonces( aDbHandler.getDbHandle(), aLocalDeviceName, aRemoteDeviceName ); if( aChallenge.meta.type == SYNCML_FORMAT_AUTH_MD5 ) { if( iAuthType == AUTH_MD5 ) { // Configured to use MD5, so check if we have already sent auth info. // If we have, they were rejected and we must abort. // If we have not, we'll send auth info if we have a nonce. Otherwise we must abort. if( iRemoteAuthPending ) { status = STATUS_HANDLED_ABORT; iLastError = "Authentication failed"; } else { QByteArray nonce = nonces.nonce(); if( !nonce.isEmpty() ) { status = STATUS_HANDLED_RESEND; } else { status = STATUS_HANDLED_ABORT; iLastError = "Challenged for MD5 authentication, but do not have a nonce!"; } } } else if( iAuthType == AUTH_BASIC ) { // Configured to use Basic authentication, so retry if we have a nonce QByteArray nonce = nonces.nonce(); if( !nonce.isEmpty() ) { iAuthType = AUTH_MD5; status = STATUS_HANDLED_RESEND; } else { status = STATUS_HANDLED_ABORT; iLastError = "Challenged for MD5 authentication, but do not have a nonce!"; } } else { status = STATUS_HANDLED_ABORT; iLastError = "Authentication required"; } } // If basic is explicitly specified, or if no type is specified, use basic else if( aChallenge.meta.type == SYNCML_FORMAT_AUTH_BASIC || aChallenge.meta.type.isEmpty() ) { if( iRemoteAuthPending && iAuthType == AUTH_BASIC ) { // We have already sent auth using basic authentication, re-challenge // means authentication has failed status = STATUS_HANDLED_ABORT; iLastError = "Authentication failed"; } else if( iAuthType == AUTH_MD5 ) { // We are to use MD5 authentication, so don't allow revertion to a more // unsafe authentication scheme status = STATUS_HANDLED_ABORT; iLastError = "Received Basic authentication challenge when MD5 is reinforced"; } else { iAuthType = AUTH_BASIC; status = STATUS_HANDLED_RESEND; } } else { status = STATUS_HANDLED_ABORT; iLastError = "Unsupported authentication type encountered:" + aChallenge.meta.type; } return status; } QByteArray SessionAuthentication::decodeNonce( const ChalParams& aChallenge ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QByteArray nonce; if( aChallenge.meta.format == SYNCML_FORMAT_ENCODING_B64 ) { nonce = QByteArray::fromBase64( aChallenge.meta.nextNonce.toUtf8() ); } else if( aChallenge.meta.format.isEmpty() ) { nonce = aChallenge.meta.nextNonce.toUtf8(); } else { qCWarning(lcSyncML) << "Unknown format" << aChallenge.meta.format << "specified for NextNonce, ignoring"; } return nonce; } ChalParams SessionAuthentication::generateChallenge() { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( iAuthType == AUTH_BASIC ); ChalParams challenge; challenge.meta.type = SYNCML_FORMAT_AUTH_BASIC; challenge.meta.format = SYNCML_FORMAT_ENCODING_B64; return challenge; } ChalParams SessionAuthentication::generateChallenge( NonceStorage& aNonces ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( iAuthType == AUTH_MD5 ); ChalParams challenge; challenge.meta.type = SYNCML_FORMAT_AUTH_MD5; QByteArray nonce = iLocalNonce.toUtf8(); iLocalNonce.clear(); if( nonce.isEmpty() ) { nonce = aNonces.generateNonce(); } // @todo: wouldn't necessarily have to B64-encode NextNonce over WbXML challenge.meta.format = SYNCML_FORMAT_ENCODING_B64; challenge.meta.nextNonce = nonce.toBase64(); aNonces.setNonce( nonce ); return challenge; } buteo-syncml-0.5.15/src/SessionAuthentication.h000066400000000000000000000172151433763642500215310ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SESSIONAUTHENTICATION_H #define SESSIONAUTHENTICATION_H #include "SyncAgentConsts.h" #include "Fragments.h" namespace DataSync { class ResponseGenerator; class DatabaseHandler; class NonceStorage; /*! \brief Manages session authentication happening over SyncML protocol * */ class SessionAuthentication { public: /*! \brief Describes analysis result of SyncML header * */ enum HeaderStatus { HEADER_HANDLED_OK, ///< Header was handled, all OK HEADER_HANDLED_ABORT, ///< Header was handled, should abort session HEADER_NOT_HANDLED ///< Header was not handled }; /*! \brief Describes analysis result of Status of SyncML header * */ enum StatusStatus { STATUS_HANDLED_OK, ///< Status was handled, all OK STATUS_HANDLED_ABORT, ///< Status was handled, should abort session STATUS_HANDLED_RESEND, ///< Status was handled, should resend last message STATUS_NOT_HANDLED ///< Status was not handled }; /*! \brief Constructor * */ SessionAuthentication(); /*! \brief Destructor * */ ~SessionAuthentication(); /*! \brief Sets parameters to use for this session * * If remote authentication is not required, aAuthType of AUTH_NONE should be used, * and empty QStrings should be passed. If remote device is not required to authenticate * with local device, empty QStrings should be passed to aLocalUsername and aLocalPassword. * * @param aAuthType Authentication type to use when authenticating * @param aRemoteUsername Username to use when authenticating with remote device * @param aRemotePassword Password to use when authenticating with remote device * @param aRemoteNonce Explicitly defined nonce that should be used when authenticating with remote device * @param aLocalUsername Username that remote device should use when authenticating * @param aLocalPassword Password that remote device should use when authenticating * @param aLocalNonce Explicitly defined nonce that remote device should use when authenticating */ void setSessionParams( AuthType aAuthType, const QString& aRemoteUsername, const QString& aRemotePassword, const QString& aRemoteNonce, const QString& aLocalUsername, const QString& aLocalPassword, const QString& aLocalNonce ); /*! \brief Returns whether remote device has been authenticated to us * * @return True if remote device has been authenticatied, otherwise false */ bool remoteIsAuthed() const; /*! \brief Returns whether we have been authenticated to the remote device * */ bool authedToRemote() const; /*! \brief Analyze SyncML header sent by remote device * * @param aHeader Header to analyze * @param aDbHandler DatabaseHandler to utilize * @param aLocalDeviceName Local device name * @param aRemoteDeviceName Remote device name * @param aResponseGenerator Response generator to utilize */ HeaderStatus analyzeHeader( const HeaderParams& aHeader, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName, ResponseGenerator& aResponseGenerator ); /*! \brief Analyze Status sent by remote device in response to SyncML header sent by us * * @param aStatus Status to analyze * @param aDbHandler DatabaseHandler to utilize * @param aLocalDeviceName Local device name * @param aRemoteDeviceName Remote device name */ StatusStatus analyzeHeaderStatus( const StatusParams& aStatus, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName ); /*! \brief Compose authentication to be sent in the next message * * @param aResponseGenerator Response generator to use * @param aDbHandler DatabaseHandler to utilize * @param aLocalDeviceName Local device name * @param aRemoteDeviceName Remote device name */ void composeAuthentication( ResponseGenerator& aResponseGenerator, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName ); /*! \brief Return human-readable description of the last occurred error * * @return */ QString getLastError() const; protected: private: HeaderStatus handleAuthentication( const HeaderParams& aHeader, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName, ResponseGenerator& aResponseGenerator ); StatusStatus handleChallenge( const ChalParams& aChallenge, DatabaseHandler& aDbHandler, const QString& aLocalDeviceName, const QString& aRemoteDeviceName ); QByteArray decodeNonce( const ChalParams& aChallenge ) const; ChalParams generateChallenge(); ChalParams generateChallenge( NonceStorage& aNonces ); bool iAuthedToRemote; bool iRemoteAuthPending; bool iRemoteAuthed; bool iLocalAuthPending; AuthType iAuthType; QString iRemoteUsername; QString iRemotePassword; QString iRemoteNonce; QString iLocalUsername; QString iLocalPassword; QString iLocalNonce; QString iLastError; }; } #endif // SESSIONAUTHENTICATION_H buteo-syncml-0.5.15/src/SessionHandler.cpp000066400000000000000000001242151433763642500204610ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SessionHandler.h" #include "ChangeLog.h" #include "SyncAgentConfig.h" #include "SyncAgentConfigProperties.h" #include "CommandHandler.h" #include "AlertPackage.h" #include "SyncTarget.h" #include "LocalChangesPackage.h" #include "FinalPackage.h" #include "StoragePlugin.h" #include "ConflictResolver.h" #include "AuthHelper.h" #include "StorageProvider.h" #include "SyncMLLogging.h" using namespace DataSync; SessionHandler::SessionHandler( const SyncAgentConfig* aConfig, const Role& aRole, QObject* aParent ) : QObject( aParent ), iDatabaseHandler( aConfig->getDatabaseFilePath() ), iCommandHandler( aRole ), iDevInfHandler( aConfig->getDeviceInfo() ), iConfig(aConfig), iSyncState( NOT_PREPARED ), iSyncWithoutInitPhase( false ), iSyncFinished( false ), iSessionClosed(false) , iProcessing( false ), iProtocolVersion( SYNCML_1_2 ), iRemoteReportedBusy(false), iRole( aRole ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT(iConfig != NULL); // Set session handler for the storage provider, so that it can ask // properties like protocol version from the session handler. StorageProvider *storageProvider = iConfig->getStorageProvider(); if (storageProvider != 0) { storageProvider->setSessionHandler(this); } } SessionHandler::~SessionHandler() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Make sure that all allocated objects are released. releaseStoragesAndTargets(); } bool SessionHandler::prepareSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iDatabaseHandler.isValid() ) { abortSync( INTERNAL_ERROR, "Could not open database file" ); return false; } // Check for credentials if authentication is to be used. Don't // allow empty username, allow empty password if( iConfig->getAuthType() != AUTH_NONE && iConfig->getUsername().isEmpty() ) { qCCritical(lcSyncML) << "Authentication requested to be used, but no credentials provided"; abortSync( AUTHENTICATION_FAILURE, "Authentication requested to be used, but no credentials provided" ); return false; } // Compose session authentication information. Currently there is no use-cases in DS // where remote device should authenticate to us AuthType authType = getConfig()->getAuthType(); const QString& remoteUsername = getConfig()->getUsername(); const QString& remotePassword = getConfig()->getPassword(); const QString& remoteNonce = getConfig()->getNonce(); QString localUsername; QString localPassword; QString localNonce; authentication().setSessionParams( authType, remoteUsername, remotePassword, remoteNonce, localUsername, localPassword, localNonce ); int localMaxMsgSize = DEFAULT_MAX_MESSAGESIZE; int confValue = getConfig()->getAgentProperty( MAXMESSAGESIZEPROP ).toInt(); if( confValue > 0 ) { localMaxMsgSize = confValue; } params().setLocalMaxMsgSize( localMaxMsgSize ); params().setRemoteMaxMsgSize( localMaxMsgSize ); // Set up transport Transport& transport = getTransport(); connect( &transport, SIGNAL(sendEvent(DataSync::TransportStatusEvent, QString )), this, SLOT(setTransportStatus(DataSync::TransportStatusEvent , QString ))); connect( &transport, SIGNAL(readXMLData(QIODevice *, bool)) , &iParser, SLOT(parseResponse(QIODevice *, bool))); connect( &transport, SIGNAL(readSANData(QIODevice *)) , this, SLOT(SANPackageReceived(QIODevice *))); connect( this, SIGNAL(purgeAndResendBuffer()) , &transport, SLOT(purgeAndResendBuffer())); setLocalNextAnchor( QString::number( QDateTime::currentDateTime().toTime_t() ) ); connectSignals(); iItemReferences.clear(); setSyncState( PREPARED ); return true; } void SessionHandler::abortSync( SyncState aSyncState, const QString& aDescription ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iSessionClosed ) { qCDebug(lcSyncML) << "Aborting sync with state" << aSyncState << ", Reason:" << aDescription; iSyncState = aSyncState; iSyncFinished = true; iSyncError = aDescription; // If we are processing a message, we must wait until the whole message has been processed // (and in server mode response has been sent). If we are not processing a message, we can // abort right away. if( !iProcessing ) { exitSync(); } } } bool SessionHandler::syncFinished() { return iSyncFinished; } void SessionHandler::setSyncState( SyncState aSyncState ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iSyncState != aSyncState ) { iSyncState = aSyncState; qCDebug(lcSyncML) << "Sync state changed to " << iSyncState; emit syncStateChanged( iSyncState ); } } SyncState SessionHandler::getSyncState() const { return iSyncState; } void SessionHandler::finishSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Finishing sync"; iSyncState = SYNC_FINISHED; iSyncFinished = true; } void SessionHandler::setTransportStatus(DataSync::TransportStatusEvent aEvent , QString aErrorString ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); switch (aEvent) { case TRANSPORT_CONNECTION_OPENED: case TRANSPORT_CONNECTION_CLOSED: { break; } case TRANSPORT_DATA_INVALID_CONTENT_TYPE: case TRANSPORT_DATA_INVALID_CONTENT: { abortSync( INVALID_SYNCML_MESSAGE, aErrorString); break; } case TRANSPORT_CONNECTION_FAILED: case TRANSPORT_CONNECTION_TIMEOUT: case TRANSPORT_CONNECTION_AUTHENTICATION_NEEDED: { abortSync( CONNECTION_ERROR , aErrorString ); break; } case TRANSPORT_CONNECTION_ABORTED: { qCDebug(lcSyncML) << "Connection Error"; abortSync( CONNECTION_ERROR , aErrorString ); break; } case TRANSPORT_SESSION_REJECTED: { // Remote aborted after receiving the first message from us, likely // candidate for unsupported sync type. if( cmdRespMap.isEmpty() ) { qCDebug(lcSyncML) << "Unsupported sync type"; abortSync( UNSUPPORTED_SYNC_TYPE , "Unsupported sync type" ); } else { qCDebug(lcSyncML) << "Connection Error"; abortSync( CONNECTION_ERROR , aErrorString ); } break; } default: { qCDebug(lcSyncML) << "Unknown transport status code: " << aEvent; abortSync( INTERNAL_ERROR, aErrorString ); break; } } } void SessionHandler::handleParsingComplete( bool aLastMessageInPackage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QList fragments = iParser.takeFragments(); processMessage( fragments, aLastMessageInPackage ); } void SessionHandler::processMessage( QList& aFragments, bool aLastMessageInPackage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Beginning to process received message..."; iProcessing = true; while( !aFragments.isEmpty() ) { DataSync::Fragment* fragment = aFragments.takeFirst(); if( fragment->fragmentType == Fragment::FRAGMENT_HEADER ) { HeaderParams* header = static_cast(fragment); handleHeaderElement(header); } else if( fragment->fragmentType == Fragment::FRAGMENT_STATUS ) { StatusParams* status = static_cast(fragment); handleStatusElement(status); } else if( fragment->fragmentType == Fragment::FRAGMENT_SYNC ) { SyncParams* sync = static_cast(fragment); handleSyncElement(sync); } else if( fragment->fragmentType == Fragment::FRAGMENT_MAP ) { MapParams* map = static_cast(fragment); handleMapElement(map); } else if( fragment->fragmentType == Fragment::FRAGMENT_PUT ) { PutParams* put = static_cast(fragment); handlePutElement( put ); } else if( fragment->fragmentType == Fragment::FRAGMENT_RESULTS ) { ResultsParams* results = static_cast(fragment); handleResultsElement(results); } else if( fragment->fragmentType == Fragment::FRAGMENT_COMMAND ) { CommandParams* command = static_cast(fragment); if( command->commandType == CommandParams::COMMAND_ALERT ) { handleAlertElement( command ); } else if( command->commandType == CommandParams::COMMAND_GET ) { handleGetElement( command ); } else { qCWarning(lcSyncML) << "Unsupported command. Command Id:" << command->cmdId; iCommandHandler.rejectCommand( *command, getResponseGenerator(), NOT_IMPLEMENTED ); delete command; command = 0; } } else { Q_ASSERT(0); } } if( aLastMessageInPackage ) { handleFinal(); } iProcessing = false; qCDebug(lcSyncML) << "Received message processed"; handleEndOfMessage(); } void SessionHandler::handleParserErrors( DataSync::ParserError aError ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); switch (aError) { case PARSER_ERROR_INCOMPLETE_DATA: { abortSync( INVALID_SYNCML_MESSAGE, "Parser error: incomplete data" ); break; } case PARSER_ERROR_UNEXPECTED_DATA: { abortSync( INVALID_SYNCML_MESSAGE, "Parser error: unexpected data" ); break; } case PARSER_ERROR_INVALID_DATA: { abortSync( INVALID_SYNCML_MESSAGE, "Parser error: invalid data" ); break; } case PARSER_ERROR_INVALID_CHARS: { // Emit signal to transport to remove any invalid characters // from the buffer emit purgeAndResendBuffer(); break; } default: { abortSync( INVALID_SYNCML_MESSAGE, "Unspecified error" ); break; } } } void SessionHandler::SANPackageReceived( QIODevice* aDevice ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_UNUSED( aDevice ); // SAN packages should never be received in-session! They are allowed // only when listening for request, which is before any session has been // established. qCCritical(lcSyncML) << "Received unexpected 1.2 SAN message, aborting..."; abortSync( INVALID_SYNCML_MESSAGE, "Received unexpected 1.2 SAN message" ); } void SessionHandler::handleHeaderElement( DataSync::HeaderParams* aHeaderParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Common handling for header parameters // Save message id of the remote party getResponseGenerator().setRemoteMsgId( aHeaderParams->msgID ); // If remote party sent max message size, save it. // If remote partys max message size is smaller than ours, reduce our // max message size to match if( aHeaderParams->meta.maxMsgSize > 0 ) { params().setRemoteMaxMsgSize( aHeaderParams->meta.maxMsgSize ); if( params().remoteMaxMsgSize() < params().localMaxMsgSize() ) { params().setLocalMaxMsgSize( params().remoteMaxMsgSize() ); } } // Ignore sending of all command statuses if we are instructed so getResponseGenerator().ignoreStatuses( aHeaderParams->noResp ); // Dedicated handling for server/client messageReceived( *aHeaderParams ); SessionAuthentication::HeaderStatus status = authentication().analyzeHeader( *aHeaderParams, getDatabaseHandler(), params().localDeviceName(), params().remoteDeviceName(), getResponseGenerator() ); if( status == SessionAuthentication::HEADER_HANDLED_ABORT ) { abortSync( AUTHENTICATION_FAILURE, authentication().getLastError() ); } else if( status == SessionAuthentication::HEADER_NOT_HANDLED ) { // Everything OK getResponseGenerator().addStatus( *aHeaderParams, SUCCESS ); } // else: SessionAuthentication::HEADER_HANDLED_OK // If remote party sent redirect URI, set it to transport // and also modify the target LocURI if( !aHeaderParams->respURI.isEmpty() ) { setRemoteLocURI( aHeaderParams->respURI ); HeaderParams headerParams = getLocalHeaderParams(); headerParams.targetDevice = aHeaderParams->respURI; setLocalHeaderParams( headerParams ); } delete aHeaderParams; aHeaderParams = NULL; } void SessionHandler::handleStatusElement( StatusParams* aStatusParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Add the response from this status to the command we sent to our map // cmd here corresponds to the syncml command for which we are handling this // status element sent by the remote device, which would have the response. QString cmd = (aStatusParams->cmd).toLower(); cmdRespMap[cmd] = aStatusParams->data; qCDebug(lcSyncML) << "Remote device responded with " << aStatusParams->data << " for cmd " << cmd; // Common status handling if( aStatusParams->cmdRef == 0 ) { SessionAuthentication::StatusStatus status = authentication().analyzeHeaderStatus( *aStatusParams, getDatabaseHandler(), params().localDeviceName(), params().remoteDeviceName() ); if( status == SessionAuthentication::STATUS_HANDLED_ABORT ) { abortSync( AUTHENTICATION_FAILURE, authentication().getLastError() ); } else if( status == SessionAuthentication::STATUS_HANDLED_RESEND ) { resendPackage(); } else if( status == SessionAuthentication::STATUS_NOT_HANDLED ) { if( aStatusParams->data == SUCCESS ) { // @todo: should we handle SUCCESS with auths where we should resend auth in every syncml message? } else if ( aStatusParams->data == IN_PROGRESS ){ // remote reported busy // request for the results iRemoteReportedBusy = true; } else { // Unknown code for header, abort abortSync( INTERNAL_ERROR, "Unknown status code received for SyncHdr" ); } } // else: SessionAuthentication::STATUS_HANDLED_OK } else { // Support only server-layer authentication, do not allow // challenges anywhere else but header status if( !aStatusParams->chal.meta.type.isEmpty() ) { abortSync( AUTHENTICATION_FAILURE, "Database-layer authentication is not supported" ); } else if( aStatusParams->cmd == SYNCML_ELEMENT_ALERT ){ // Reverting to slow sync occured if( aStatusParams->data == REFRESH_REQUIRED ) { QString sourceDb = aStatusParams->sourceRef; SyncTarget* target = getSyncTarget( sourceDb ); if( target ) { target->revertSyncMode(); } } } else { iCommandHandler.handleStatus( aStatusParams ); } } delete aStatusParams; aStatusParams = NULL; } void SessionHandler::handleSyncElement( SyncParams* aSyncParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QSharedPointer params( aSyncParams ); // Don't process Sync elements if remote device has not authenticated if( !authentication().remoteIsAuthed() ) { iCommandHandler.rejectSync( *aSyncParams, iResponseGenerator, INVALID_CRED ); return; } if( !syncReceived() ) { iCommandHandler.rejectSync( *aSyncParams, iResponseGenerator, COMMAND_NOT_ALLOWED ); return; } SyncTarget* target = getSyncTarget( aSyncParams->target ); if( !target ) { iCommandHandler.rejectSync( *aSyncParams, iResponseGenerator,NOT_FOUND ); return; } if( !target->discoverLocalChanges( iRole ) ) { qCCritical(lcSyncML) << "Failed to discover local changes for source db" << target->getSourceDatabase(); iCommandHandler.rejectSync( *aSyncParams, iResponseGenerator, COMMAND_FAILED ); return; } ConflictResolutionPolicy policy = PREFER_LOCAL_CHANGES; ConflictResolutionPolicy confValue = static_cast( getConfig()->getAgentProperty( CONFLICTRESOLUTIONPOLICYPROP ).toInt() ); if( confValue > 0 ) { policy = confValue; } ConflictResolver conflictResolver( *target->getLocalChanges(), policy ); bool fastMapsSend = false; int configValue = getConfig()->getAgentProperty( FASTMAPSSENDPROP ).toInt(); if( configValue > 0 ) { fastMapsSend = true; } iCommandHandler.handleSync( *aSyncParams, *target, iStorageHandler, iResponseGenerator, conflictResolver, fastMapsSend ); } void SessionHandler::handleAlertElement( CommandParams* aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status; if( authentication().remoteIsAuthed() ) { SyncMode syncMode( aAlertParams->data.toInt() ); if( syncMode.isValid() ) { status = syncAlertReceived( syncMode, *aAlertParams ); } else { status = handleInformativeAlert( *aAlertParams ); } } else { status = INVALID_CRED; } if( !aAlertParams->noResp ) { getResponseGenerator().addStatus( *aAlertParams, status, true ); } delete aAlertParams; aAlertParams = NULL; } void SessionHandler::handleGetElement( DataSync::CommandParams* aGetParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode code = NOT_IMPLEMENTED; if( !authentication().remoteIsAuthed() ) { code = INVALID_CRED; } else if( aGetParams->meta.type == SYNCML_CONTTYPE_DEVINF_XML ) { code = getDevInfHandler().handleGet( *aGetParams, getProtocolVersion(), getStorages(), iRole, getResponseGenerator() ); } else { code = NOT_IMPLEMENTED; } if( !aGetParams->noResp ) { getResponseGenerator().addStatus( *aGetParams, code, true ); } delete aGetParams; aGetParams = NULL; } void SessionHandler::handlePutElement( DataSync::PutParams* aPutParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode code = NOT_IMPLEMENTED; if( !authentication().remoteIsAuthed() ) { code = INVALID_CRED; } else if( aPutParams->meta.type == SYNCML_CONTTYPE_DEVINF_XML ) { code = getDevInfHandler().handlePut( *aPutParams, getProtocolVersion() ); } else { code = NOT_IMPLEMENTED; } if( !aPutParams->noResp ) { getResponseGenerator().addStatus( *aPutParams, code ); } delete aPutParams; aPutParams = NULL; } void SessionHandler::handleResultsElement(DataSync::ResultsParams* aResults) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode code = NOT_IMPLEMENTED; if( !authentication().remoteIsAuthed() ) { code = INVALID_CRED; } else if( aResults->meta.type == SYNCML_CONTTYPE_DEVINF_XML ) { code = getDevInfHandler().handleResults( *aResults, getProtocolVersion() ); } else { code = NOT_IMPLEMENTED; } // noResp cannot be specified with RESULTS, so always send back status getResponseGenerator().addStatus( *aResults, code ); delete aResults; aResults = NULL; } void SessionHandler::handleMapElement( DataSync::MapParams* aMapParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status = NOT_FOUND; SyncTarget* target = NULL; if (!authentication().remoteIsAuthed() ) { status = INVALID_CRED; } else if (!mapReceived()) { status = COMMAND_NOT_ALLOWED; } else { target = getSyncTarget( aMapParams->target ); } if( target != NULL ) { status = iCommandHandler.handleMap( *aMapParams, *target ); } // no else // Maps do not have noResp getResponseGenerator().addStatus( *aMapParams, status ); delete aMapParams; aMapParams = NULL; } void SessionHandler::handleFinal() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( authentication().authedToRemote() ) { finalReceived(); } } void SessionHandler::handleEndOfMessage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); messageParsed(); if( iSyncFinished ) { exitSync(); } } void SessionHandler::sendNextMessage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Sending next message..."; // If have nothing to send in response other than status codes, we must // request remote side to send data by using alert 222 ( NEXT MESSAGE ) if( iResponseGenerator.packageQueueEmpty() ) { foreach( const SyncTarget* syncTarget, getSyncTargets() ) { iResponseGenerator.addPackage( new AlertPackage( NEXT_MESSAGE, syncTarget->getSourceDatabase(), syncTarget->getTargetDatabase() ) ); } } // @todo: what if message generation fails? SyncMLMessage* message = iResponseGenerator.generateNextMessage( params().remoteMaxMsgSize(), getProtocolVersion(), getTransport().usesWbXML() ); // @todo: what if sending fails? getTransport().sendSyncML( message ); if( getConfig()->extensionEnabled( EMITAGSEXTENSION ) ) { clearEMITags(); } qCDebug(lcSyncML) << "Next message sent"; } ProtocolVersion SessionHandler::getProtocolVersion() const { return iProtocolVersion; } void SessionHandler::setProtocolVersion( const ProtocolVersion& aProtocolVersion ) { iProtocolVersion = aProtocolVersion; } const QString& SessionHandler::getLocalNextAnchor() const { return iLocalNextAnchor; } void SessionHandler::setLocalNextAnchor( const QString& aLocalNextAnchor ) { iLocalNextAnchor = aLocalNextAnchor; } void SessionHandler::exitSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if(!iSessionClosed) { iSessionClosed = true; // Transport can be closed before doing cleaning getTransport().close(); // In case of successful session, save sync anchors if( iSyncState == SYNC_FINISHED ) { saveSession(); } // Clear package queue in case we have active packages. For example // LocalChangesPackage might attempt to do item prefetching after storages are cleared // and before event about sync exiting reaches user. getResponseGenerator().clearPackageQueue(); // Release storages releaseStoragesAndTargets(); emit syncFinished( params().remoteDeviceName(), iSyncState, iSyncError); } } void SessionHandler::releaseStoragesAndTargets() { FUNCTION_CALL_TRACE(lcSyncMLTrace); StorageProvider* provider = NULL; if (iConfig != NULL) { provider = iConfig->getStorageProvider(); } if (provider != NULL) { for( int i = 0; i < iStorages.count(); ++i ) { provider->releaseStorage( iStorages[i] ); } iStorages.clear(); } qDeleteAll( iSyncTargets ); iSyncTargets.clear(); } void DataSync::SessionHandler::connectSignals() { FUNCTION_CALL_TRACE(lcSyncMLTrace); connect( &iParser, SIGNAL(parsingComplete(bool)), this, SLOT(handleParsingComplete(bool)), Qt::QueuedConnection ); connect( &iParser, SIGNAL( parsingError(DataSync::ParserError)), this, SLOT(handleParserErrors(DataSync::ParserError))); connect( &iCommandHandler, SIGNAL( itemAcknowledged( int, int, SyncItemKey ) ), this, SLOT( processItemStatus( int, int, SyncItemKey ) ) ); connect( &iStorageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString ,QString, int ) ), this, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString ,QString, int) ) ); } ResponseStatusCode SessionHandler::handleInformativeAlert( const CommandParams& aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status; // Do not implement: RESULT_ALERT, DISPLAY // @todo: implement NO_END_OF_DATA, ALERT_SUSPEND, ALERT_RESUME qint32 alertCode = aAlertParams.data.toInt(); switch( alertCode ) { case DISPLAY: case RESULT_ALERT: { status = NOT_IMPLEMENTED; break; } case NEXT_MESSAGE: { status = SUCCESS; break; } default: { status = NOT_IMPLEMENTED; break; } } return status; } bool SessionHandler::anchorMismatch( const SyncMode& aSyncMode, const SyncTarget& aTarget, const QString& aRemoteLastAnchor ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aSyncMode.syncType() != TYPE_FAST ) { qCDebug(lcSyncML) << "Slow sync mode, not checking anchors of remote database" << aTarget.getTargetDatabase(); return false; } qCDebug(lcSyncML) << "Fast sync mode, checking anchors of remote database" << aTarget.getTargetDatabase(); qCDebug(lcSyncML) << "Stored LAST anchor:" << aTarget.getRemoteLastAnchor(); qCDebug(lcSyncML) << "LAST anchor reported by remote device:" << aRemoteLastAnchor; if( aRemoteLastAnchor.isEmpty() || aTarget.getRemoteLastAnchor() != aRemoteLastAnchor ) { qCDebug(lcSyncML) << "Anchor mismatch!"; return true; } else { qCDebug(lcSyncML) << "Anchors match"; return false; } } void SessionHandler::composeLocalChanges() { FUNCTION_CALL_TRACE(lcSyncMLTrace); int maxChangesPerMessage = DEFAULT_MAX_CHANGES_TO_SEND; int configValue = getConfig()->getTransportProperty( MAXCHANGESPERMESSAGEPROP ).toInt(); if( configValue > 0 ) { maxChangesPerMessage = configValue; } qCDebug(lcSyncML) << "Setting number of changes to send per message to" << maxChangesPerMessage; int largeObjectThreshold = qMax( static_cast( MAXMSGOVERHEADRATIO * params().remoteMaxMsgSize()), MINMSGOVERHEADBYTES ); const QList& targets = getSyncTargets(); foreach( const SyncTarget* syncTarget, targets ) { const LocalChanges* localChanges = syncTarget->getLocalChanges(); LocalChangesPackage* localChangesPackage = new LocalChangesPackage( *syncTarget, *localChanges, largeObjectThreshold, iRole, maxChangesPerMessage ); iResponseGenerator.addPackage(localChangesPackage); connect( localChangesPackage, SIGNAL( newItemWritten( int, int, SyncItemKey, ModificationType, QString, QString, QString ) ), this, SLOT( newItemReference( int, int, SyncItemKey, ModificationType, QString, QString, QString ) ) ); } } void SessionHandler::setupSession( HeaderParams& aHeaderParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); params().setSessionId( aHeaderParams.sessionID ); // If remote party sent unknown device id, identify ourselves in the response if( aHeaderParams.targetDevice == SYNCML_UNKNOWN_DEVICE ) { if( !getConfig()->getLocalDeviceName().isEmpty() ) { aHeaderParams.targetDevice = getConfig()->getLocalDeviceName(); } else { aHeaderParams.targetDevice = getDevInfHandler().getLocalDeviceInfo().getDeviceID(); } } params().setLocalDeviceName( aHeaderParams.targetDevice ); params().setRemoteDeviceName( aHeaderParams.sourceDevice ); QString verDTD; QString verProto; if( aHeaderParams.verDTD == SYNCML_DTD_VERSION_1_1 ) { qCDebug(lcSyncML) << "Setting SyncML 1.1 protocol version"; setProtocolVersion( SYNCML_1_1 ); verDTD = SYNCML_DTD_VERSION_1_1; verProto = DS_VERPROTO_1_1; } else if( aHeaderParams.verDTD == SYNCML_DTD_VERSION_1_2 ) { qCDebug(lcSyncML) << "Setting SyncML 1.2 protocol version"; setProtocolVersion( SYNCML_1_2 ); verDTD = SYNCML_DTD_VERSION_1_2; verProto = DS_VERPROTO_1_2; } HeaderParams headerParams; headerParams.verDTD = verDTD; headerParams.verProto = verProto; headerParams.sessionID = params().sessionId(); headerParams.sourceDevice = params().localDeviceName(); headerParams.targetDevice = params().remoteDeviceName(); headerParams.meta.maxMsgSize = params().localMaxMsgSize(); if( getConfig()->extensionEnabled( EMITAGSEXTENSION ) ) { handleEMITags( aHeaderParams, headerParams ); } setLocalHeaderParams( headerParams ); } void SessionHandler::setupSession( const QString& aSessionId ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); params().setSessionId( aSessionId ); if( !getConfig()->getLocalDeviceName().isEmpty() ) { params().setLocalDeviceName( getConfig()->getLocalDeviceName() ); } else { params().setLocalDeviceName( getDevInfHandler().getLocalDeviceInfo().getDeviceID() ); } if( !getConfig()->getRemoteDeviceName().isEmpty() ) { params().setRemoteDeviceName( getConfig()->getRemoteDeviceName() ); } else { params().setRemoteDeviceName( SYNCML_UNKNOWN_DEVICE ); } setProtocolVersion( getConfig()->getProtocolVersion() ); if( getConfig()->extensionEnabled( SYNCWITHOUTINITPHASEEXTENSION ) ) { setSyncWithoutInitPhase( true ); } QString verDTD; QString verProto; if( getProtocolVersion() == SYNCML_1_1 ) { qCDebug(lcSyncML) << "Setting SyncML 1.1 protocol version"; verDTD = SYNCML_DTD_VERSION_1_1; verProto = DS_VERPROTO_1_1; } else if( getProtocolVersion() == SYNCML_1_2 ) { qCDebug(lcSyncML) << "Setting SyncML 1.2 protocol version"; verDTD = SYNCML_DTD_VERSION_1_2; verProto = DS_VERPROTO_1_2; } HeaderParams headerParams; headerParams.verDTD = verDTD; headerParams.verProto = verProto; headerParams.sessionID = params().sessionId(); headerParams.sourceDevice = params().localDeviceName(); headerParams.targetDevice = params().remoteDeviceName(); headerParams.meta.maxMsgSize = params().localMaxMsgSize(); if( getConfig()->extensionEnabled( EMITAGSEXTENSION ) ) { insertEMITagsToken(headerParams); } setLocalHeaderParams( headerParams ); } void SessionHandler::saveSession() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Store last sync time with accuracy of 1 second, ceiling it to the // next full second. QDateTime dateTime = QDateTime::currentDateTime(); QTime time = dateTime.time(); time.addSecs( 1 ); time.setHMS( time.hour(), time.minute(), time.second() , 0 ); dateTime.setTime( time ); DatabaseHandler& handler = getDatabaseHandler(); foreach( SyncTarget* syncTarget, getSyncTargets()) { syncTarget->saveSession( handler, dateTime ); } } StoragePlugin* SessionHandler::createStorageByURI( const QString& aURI ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); StoragePlugin* plugin = NULL; for( int i = 0; i < iStorages.count(); ++i ) { if( iStorages[i]->getSourceURI() == aURI ) { plugin = iStorages[i]; break; } } if( plugin == NULL ) { const SyncAgentConfig* config = getConfig(); StorageProvider* storageProvider = NULL; if (config != NULL) { storageProvider = config->getStorageProvider(); } if (storageProvider != NULL) { plugin = storageProvider->acquireStorageByURI( aURI ); } if (plugin != NULL) { iStorages.append( plugin ); emit storageAccquired (plugin->getFormatInfo().getPreferredTx().iType); } } return plugin; } StoragePlugin* SessionHandler::createStorageByMIME( const QString& aMIME ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); StoragePlugin* plugin = NULL; for( int i = 0; i < iStorages.count(); ++i ) { if( iStorages[i]->getFormatInfo().getPreferredRx().iType == aMIME ) { plugin = iStorages[i]; break; } } if( !plugin ) { plugin = getConfig()->getStorageProvider()->acquireStorageByMIME( aMIME ); if (plugin) { iStorages.append( plugin ); emit storageAccquired (aMIME); } } return plugin; } const QList& SessionHandler::getStorages() const { return iStorages; } SyncTarget* SessionHandler::createSyncTarget( StoragePlugin& aPlugin, const SyncMode& aSyncMode ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncTarget* target = getSyncTarget( aPlugin.getSourceURI() ); if( !target ) { ChangeLog* changelog = new ChangeLog( params().remoteDeviceName(), aPlugin.getSourceURI(), aSyncMode.syncDirection() ); if( !changelog->load( getDatabaseHandler().getDbHandle() ) ) { qCWarning(lcSyncML) << "Could not load change log information"; } target = new SyncTarget( changelog, &aPlugin, aSyncMode, getLocalNextAnchor() ); } return target; } void SessionHandler::addSyncTarget( SyncTarget* aTarget ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iSyncTargets.contains( aTarget ) ) { iSyncTargets.append( aTarget ); } } SyncTarget* SessionHandler::getSyncTarget( const QString& aSourceURI ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncTarget* target = NULL; for( int i = 0; i < iSyncTargets.count(); ++i ) { if( aSourceURI.compare(iSyncTargets[i]->getSourceDatabase(),Qt::CaseInsensitive) == 0 ) { target = iSyncTargets[i]; break; } } return target; } const QList& SessionHandler::getSyncTargets() const { return iSyncTargets; } void SessionHandler::setLocalHeaderParams( const HeaderParams& aHeaderParams ) { iResponseGenerator.setHeaderParams(aHeaderParams); } const HeaderParams& SessionHandler::getLocalHeaderParams() const { return iResponseGenerator.getHeaderParams(); } void SessionHandler::setRemoteLocURI( const QString& aURI ) { getTransport().setRemoteLocURI(aURI); } SessionAuthentication& SessionHandler::authentication() { return iSessionAuth; } SessionParams& SessionHandler::params() { return iSessionParams; } const SyncAgentConfig* SessionHandler::getConfig() const { return iConfig; } Transport& SessionHandler::getTransport() { return *iConfig->getTransport(); } ResponseGenerator& SessionHandler::getResponseGenerator() { return iResponseGenerator; } DatabaseHandler& SessionHandler::getDatabaseHandler() { return iDatabaseHandler; } void SessionHandler::newItemReference( int aMsgId, int aCmdId, SyncItemKey aKey, ModificationType aModificationType, QString aLocalDatabase, QString aRemoteDatabase, QString aMimeType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ItemReference reference; reference.iMsgId = aMsgId; reference.iCmdId = aCmdId; reference.iKey = aKey; reference.iModificationType = aModificationType; reference.iLocalDatabase = aLocalDatabase; reference.iRemoteDatabase = aRemoteDatabase; reference.iMimeType = aMimeType; iItemReferences.append( reference ); qCDebug(lcSyncML) << "Adding reference to item:" << aKey; } void SessionHandler::processItemStatus( int aMsgRef, int aCmdRef, SyncItemKey aKey ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); quint32 count = iItemReferences.count(); for( int i = 0; i < iItemReferences.count(); ++i ) { const ItemReference& reference = iItemReferences[i]; if( reference.iMsgId == aMsgRef && reference.iCmdId == aCmdRef && reference.iKey == aKey ) { emit itemProcessed( reference.iModificationType, MOD_REMOTE_DATABASE, reference.iLocalDatabase, reference.iMimeType, count ); iItemReferences.removeAt( i ); break; } } } bool DataSync::SessionHandler::isRemoteBusyStatusSet() const { return iRemoteReportedBusy; } void DataSync::SessionHandler::resetRemoteBusyStatus() { iRemoteReportedBusy = false; } DevInfHandler& SessionHandler::getDevInfHandler() { return iDevInfHandler; } void SessionHandler::insertEMITagsToken( HeaderParams& aLocalHeader ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QVariant data = getConfig()->getExtensionData( EMITAGSEXTENSION ); QStringList tags = data.toStringList(); qCDebug(lcSyncML) << "EMI tags extension: adding token" << tags[0]; aLocalHeader.meta.EMI.append( tags[0] ); } void SessionHandler::handleEMITags( const HeaderParams& aRemoteHeader, HeaderParams& aLocalHeader ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QVariant data = getConfig()->getExtensionData( EMITAGSEXTENSION ); QStringList tags = data.toStringList(); if( aRemoteHeader.meta.EMI.contains( tags[0] ) ) { qCDebug(lcSyncML) << "EMI tags extension: responding to" << tags[0] << "with" << tags[1]; aLocalHeader.meta.EMI.append( tags[1] ); } } void SessionHandler::clearEMITags() { FUNCTION_CALL_TRACE(lcSyncMLTrace); QVariant data = getConfig()->getExtensionData( EMITAGSEXTENSION ); QStringList tags = data.toStringList(); HeaderParams headerParams = getLocalHeaderParams(); for( int i = 0; i < tags.count(); ++i ) { headerParams.meta.EMI.removeOne( tags[i] ); } setLocalHeaderParams( headerParams ); } void SessionHandler::setSyncWithoutInitPhase( bool aSyncWithoutInitPhase ) { iSyncWithoutInitPhase = aSyncWithoutInitPhase; } bool SessionHandler::isSyncWithoutInitPhase() const { return iSyncWithoutInitPhase; } QString SessionHandler::generateSessionID() { // A common way to create unique session ID is to use UNIX timestamp. // However, it needs to be converted to string format and for compatibility // reasons only 4 rightmost digits are used. uint timeStamp = QDateTime::currentDateTime().toTime_t(); QString sessionId = QString::number(timeStamp).right( 4 ); return sessionId; } SyncState SessionHandler::getLastError( QString &aErrorMsg ) { // Try to figure out the last erroneous sync state, if any SyncState state = iSyncState; aErrorMsg = ""; if( iSyncState != SYNC_FINISHED ) { // Check alerts first - checking if the remote device responded with an error // for the sync alert that we sent last. switch(cmdRespMap["alert"]) { case NOT_SUPPORTED: { state = UNSUPPORTED_SYNC_TYPE; aErrorMsg = "Unsupported sync type"; break; } case NOT_FOUND: { state = UNSUPPORTED_STORAGE_TYPE; aErrorMsg = "Unsupported storage type"; break; } default: { //TODO Do we check more codes state = INTERNAL_ERROR; aErrorMsg = "Internal error"; break; } } //TODO Do we check responses to messages other than alerts? } return state; } buteo-syncml-0.5.15/src/SessionHandler.h000066400000000000000000000520211433763642500201210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SESSIONHANDLER_H #define SESSIONHANDLER_H #include #include "SyncAgentConsts.h" #include "Transport.h" #include "SessionAuthentication.h" #include "SessionParams.h" #include "CommandHandler.h" #include "DatabaseHandler.h" #include "StorageHandler.h" #include "ResponseGenerator.h" #include "SyncMLMessageParser.h" #include "DevInfHandler.h" class ServerSessionHandlerTest; class ClientSessionHandlerTest; class SessionHandlerTest; namespace DataSync { class SyncAgentConfig; class SyncMode; class SyncTarget; /*! \brief Structure to hold reference to an item * */ struct ItemReference { int iMsgId; /*!& aFragments, bool aLastMessageInPackage ); /*! \brief Sets current state of the sync * * @param aSyncState New status to set */ void setSyncState( SyncState aSyncState ); /*! * \brief Returns current state of the sync * * @return */ SyncState getSyncState() const; /*! \brief Finish a successful sync session * * Sync state will be set to SYNC_FINISHED and no further messages * will be sent */ void finishSync(); /** * \brief Sends next pending message */ void sendNextMessage(); /*! \brief Adds local changes to the outgoing message * */ void composeLocalChanges(); /*! \brief Set up session based on header received from remote party ( remote * side is initiating sync ) * * @param aHeaderParams Header parameters */ void setupSession( HeaderParams& aHeaderParams ); /*! \brief Set up session based on SyncAgentConfig( local side is initiating sync ) * * @param aSessionId Session Id to use */ void setupSession( const QString& aSessionId ); /*! \brief Saves current session (anchors etc) to change log * */ void saveSession(); /*! \brief Sets protocol version of this session * * @param aProtocolVersion Protocol version */ void setProtocolVersion( const ProtocolVersion& aProtocolVersion ); /*! \brief Returns local NEXT anchor * * @return Local NEXT anchor */ const QString& getLocalNextAnchor() const; /*! \brief Sets local NEXT anchor * * @param aLocalNextAnchor Local NEXT anchor */ void setLocalNextAnchor( const QString& aLocalNextAnchor ); /*! \brief Checks for last anchor mismatch * * @param aSyncMode Proposed sync mode * @param aTarget Target to check * @param aRemoteLastAnchor Last anchor to check * @return True if anchor mismatch, otherwise false */ bool anchorMismatch( const SyncMode& aSyncMode, const SyncTarget& aTarget, const QString& aRemoteLastAnchor ) const; /*! \brief Creates a new storage based on URI * * @param aURI URI of the storage * @return Storage plugin on success, otherwise NULL */ StoragePlugin* createStorageByURI( const QString& aURI ); /*! \brief Creates a new storage based on MIME * * @param aMIME MIME of the storage * @return Storage plugin on success, otherwise NULL */ StoragePlugin* createStorageByMIME( const QString& aMIME ); /*! \brief Get list of all storages * * @return */ const QList& getStorages() const; /*! \brief Creates a new sync target * * Sync target is NOT added to the list of sync targets, addSyncTarget() should be called * separately * * @param aPlugin Storage plugin representing local database * @param aSyncMode Sync mode to use */ SyncTarget* createSyncTarget( StoragePlugin& aPlugin, const SyncMode& aSyncMode ); /*! \brief Adds a new sync target to the list of available sync targets * * @param aTarget Sync target to add */ void addSyncTarget( SyncTarget* aTarget ); /*! \brief Searches for existing sync target * * @param aSourceURI Source URI * @return Sync target if found, otherwise NULL */ SyncTarget* getSyncTarget( const QString& aSourceURI ) const; /*! \brief Get list of all sync targets * * @return List containing sync targets */ const QList& getSyncTargets() const; /*! \brief Set SyncML header parameters for messages going out * * msgId field is ignored as this is filled by response generator * * @param aHeaderParams Header parameters */ void setLocalHeaderParams( const HeaderParams& aHeaderParams ); /*! \brief Retrieve SyncML header parameters for messages going out * * @return Header parameters */ const HeaderParams& getLocalHeaderParams() const; /*! \brief Sets the URI to use in next send operation * * @param aURI New URI to remote side */ void setRemoteLocURI( const QString& aURI ); /*! \brief Access session authentication object * * @return */ SessionAuthentication& authentication(); /*! \brief Access session parameters * * @return */ SessionParams& params(); /*! \brief Returns pointer to configuration object * * @return A pointer to configuration object */ const SyncAgentConfig* getConfig() const; /*! \brief Returns reference to transport * */ Transport& getTransport(); /*! \brief Returns reference to response generator * * @return */ ResponseGenerator& getResponseGenerator(); /*! \brief Returns reference to database handler * * @return */ DatabaseHandler& getDatabaseHandler(); /** * \brief Generates a new session ID * @return Formatted session ID string */ QString generateSessionID(); /*! \brief used to check the status sent by the server when we send local modifications * * @return Returns true if server reported Busy */ bool isRemoteBusyStatusSet() const; /*! \brief resets the server busy status once it is handled * * @return */ void resetRemoteBusyStatus(); /*! \brief Retrieves device info handler * */ DevInfHandler& getDevInfHandler(); /*! \brief Adds EMI tags token to the message * */ void insertEMITagsToken( HeaderParams& aLocalHeader ); /*! \brief Adds EMI tags response to the message * * @param aRemoteHeader Header sent by remote side * @param aLocalHeader Header to be sent by local side */ void handleEMITags( const HeaderParams& aRemoteHeader, HeaderParams& aLocalHeader ); /*! \brief Clears EMI tags from local headers * */ void clearEMITags(); /*! \brief Sets sync-without-initialization-phase flag * * @param aSyncWithoutInitPhase */ void setSyncWithoutInitPhase( bool aSyncWithoutInitPhase ); /*! \brief Returns sync-without-initialization-phase flag * */ bool isSyncWithoutInitPhase() const; /*! \brief Tries to report the error encountered for the last syncml message we sent * * @param aErrorMsg Human readable error message * @return Returns sync state mapped to the last syncml error */ SyncState getLastError( QString &aErrorMsg ); private: // functions void exitSync(); void releaseStoragesAndTargets(); /** * \brief A helper function used to conenect signal in constructor */ void connectSignals(); ResponseStatusCode handleInformativeAlert( const CommandParams& aAlertParams ); private: // data DatabaseHandler iDatabaseHandler; ///< Handler for database operations SessionAuthentication iSessionAuth; ///< Handles authentication of the session SessionParams iSessionParams; ///< Maintains important parameters of the session CommandHandler iCommandHandler; ///< A pointer to command handler object StorageHandler iStorageHandler; ///< Handles sync item storage operations DevInfHandler iDevInfHandler; ///< Handles device info related things ResponseGenerator iResponseGenerator; ///< Response generator object SyncMLMessageParser iParser; ///< XML parser const DataSync::SyncAgentConfig* iConfig; ///< A pointer to configuration QList iStorages; ///< A list of reserved storages QList iSyncTargets; ///< A list of sync targets SyncState iSyncState; ///< State of the synchronization session QString iLocalNextAnchor; ///< Local NEXT anchor of this session QString iSyncError; ///< Human-readable description upon sync abort bool iSyncWithoutInitPhase; ///< Perform synchronization without init phase QList iItemReferences; ///< Keeps track which status refers to which item in which database bool iSyncFinished; ///< Set to true when sync has ended bool iSessionClosed; ///< Set to true when Session tearing down started. bool iProcessing; ///< Set to true when we are processing a message ProtocolVersion iProtocolVersion; ///< Protocol version in use in current session bool iRemoteReportedBusy; ///< indicates that server reported busy Role iRole; ///< Role in use ///< A quick way to get the response a remote party sent to the last "cmd" command we sent QMap cmdRespMap; friend class ::ServerSessionHandlerTest; friend class ::ClientSessionHandlerTest; friend class ::SessionHandlerTest; }; } #endif // SESSIONHANDLER_H buteo-syncml-0.5.15/src/SessionParams.cpp000066400000000000000000000053221433763642500203240ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SessionParams.h" using namespace DataSync; SessionParams::SessionParams() : iLocalMaxMsgSize( -1 ), iRemoteMaxMsgSize( -1 ) { } SessionParams::~SessionParams() { } void SessionParams::setSessionId( const QString& aSessionId ) { iSessionId = aSessionId; } const QString& SessionParams::sessionId() const { return iSessionId; } void SessionParams::setLocalDeviceName( const QString& aLocalDeviceName ) { iLocalDeviceName = aLocalDeviceName; } const QString& SessionParams::localDeviceName() { return iLocalDeviceName; } void SessionParams::setRemoteDeviceName( const QString& aRemoteDeviceName ) { iRemoteDeviceName = aRemoteDeviceName; } const QString& SessionParams::remoteDeviceName() { return iRemoteDeviceName; } void SessionParams::setLocalMaxMsgSize( qint32 aLocalMaxMsgSize ) { iLocalMaxMsgSize = aLocalMaxMsgSize; } qint32 SessionParams::localMaxMsgSize() { return iLocalMaxMsgSize; } void SessionParams::setRemoteMaxMsgSize( qint32 aRemoteMaxMsgSize ) { iRemoteMaxMsgSize = aRemoteMaxMsgSize; } qint32 SessionParams::remoteMaxMsgSize() { return iRemoteMaxMsgSize; } buteo-syncml-0.5.15/src/SessionParams.h000066400000000000000000000071441433763642500177750ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SESSIONPARAMS_H #define SESSIONPARAMS_H #include namespace DataSync { /*! \brief Holds global parameters of SyncML session * */ class SessionParams { public: /*! \brief Constructor * */ SessionParams(); /*! \brief Destructor * */ ~SessionParams(); /*! \brief Sets Id of the session * * @param aSessionId Id of the session */ void setSessionId( const QString& aSessionId ); /*! \brief Returns Id of the session * * @return */ const QString& sessionId() const; /*! \brief Sets name of the local device * * @param aLocalDeviceName Name of the local device */ void setLocalDeviceName( const QString& aLocalDeviceName ); /*! \brief Returns the name of the local device * * @return */ const QString& localDeviceName(); /*! \brief Sets the name of the remote device * * @param aRemoteDeviceName Name of the remote device */ void setRemoteDeviceName( const QString& aRemoteDeviceName ); /*! \brief Returns the name of the remote device * * @return */ const QString& remoteDeviceName(); /*! \brief Sets the maximum message size for local device * * @param aLocalMaxMsgSize Maximum message size for local device */ void setLocalMaxMsgSize( qint32 aLocalMaxMsgSize ); /*! \brief Returns the maximum message size for local device * * @return */ qint32 localMaxMsgSize(); /*! \brief Sets the maximum message size for remote device * * @param aRemoteMaxMsgSize Maximum message size for remote device */ void setRemoteMaxMsgSize( qint32 aRemoteMaxMsgSize ); /*! \brief Returns the maximum message size for remote device * * @return */ qint32 remoteMaxMsgSize(); protected: private: QString iSessionId; QString iLocalDeviceName; QString iRemoteDeviceName; qint32 iLocalMaxMsgSize; qint32 iRemoteMaxMsgSize; }; } #endif // SESSIONPARAMS_H buteo-syncml-0.5.15/src/StorageContentFormatInfo.cpp000066400000000000000000000047501433763642500224650ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "StorageContentFormatInfo.h" using namespace DataSync; StorageContentFormatInfo::StorageContentFormatInfo() { } StorageContentFormatInfo::~StorageContentFormatInfo() { } void StorageContentFormatInfo::setPreferredRx( const ContentFormat& aFormat ) { iRxPref = aFormat; } const ContentFormat& StorageContentFormatInfo::getPreferredRx() const { return iRxPref; } void StorageContentFormatInfo::setPreferredTx( const ContentFormat& aFormat ) { iTxPref = aFormat; } const ContentFormat& StorageContentFormatInfo::getPreferredTx() const { return iTxPref; } const QList& StorageContentFormatInfo::rx() const { return iRx; } QList& StorageContentFormatInfo::rx() { return iRx; } const QList& StorageContentFormatInfo::tx() const { return iTx; } QList& StorageContentFormatInfo::tx() { return iTx; } buteo-syncml-0.5.15/src/StorageContentFormatInfo.h000066400000000000000000000066041433763642500221320ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef STORAGECONTENTFORMATINFO_H #define STORAGECONTENTFORMATINFO_H #include #include namespace DataSync { /*! \brief Information about a content format * */ struct ContentFormat { QString iType; /*!< MIME type of the content, for example "text/x-vcard"*/ QString iVersion; /*!< Version of the supported MIME type*/ }; /*! \brief Describes general information about content formats supported by * a storage */ class StorageContentFormatInfo { public: /*! \brief Constructor * */ StorageContentFormatInfo(); /*! \brief Destructor * */ ~StorageContentFormatInfo(); /*! \brief Set preferred receive format * * @param aFormat Format to set */ void setPreferredRx( const ContentFormat& aFormat ); /*! \brief Retrieve preferred receive format * * @return */ const ContentFormat& getPreferredRx() const; /*! \brief Set preferred transmit format * * @param aFormat */ void setPreferredTx( const ContentFormat& aFormat ); /*! \brief Retrieve preferred transmit format * * @return */ const ContentFormat& getPreferredTx() const; /*! \brief Access receive formats * * @return */ const QList& rx() const; /*! \brief Access receive formats * * @return */ QList& rx(); /*! \brief Access transmit formats * * @return */ const QList& tx() const; /*! \brief Access transmit formats * * @return */ QList& tx(); private: ContentFormat iRxPref; ContentFormat iTxPref; QList iRx; QList iTx; }; } #endif // STORAGECONTENTFORMATINFO_H buteo-syncml-0.5.15/src/StorageHandler.cpp000066400000000000000000000510351433763642500204410ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "StorageHandler.h" #include #include "StoragePlugin.h" #include "SyncItem.h" #include "ConflictResolver.h" #include "SyncMLLogging.h" using namespace DataSync; StorageHandler::StorageHandler() : iLargeObject( NULL ), iLargeObjectSize(0) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } StorageHandler::~StorageHandler() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qDeleteAll(iAddList); qDeleteAll(iReplaceList); delete iLargeObject; iLargeObject = NULL; } bool StorageHandler::addItem( const ItemId& aItemId, StoragePlugin& aPlugin, const SyncItemKey& aLocalKey, const SyncItemKey& aParentKey, const QString& aType, const QString& aFormat, const QString& aVersion, const QString& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Processing item for add:" << aItemId.iCmdId <<"/" << aItemId.iItemIndex; if( iLargeObject ) { qCCritical(lcSyncML) << "Already processing large object, aborting"; return false; } SyncItem* newItem = aPlugin.newItem(); if( !newItem ) { qCCritical(lcSyncML) << "Could not create new item"; return false; } //Setting empty string as we dont have any local key for it. newItem->setKey( aLocalKey ); newItem->setParentKey( aParentKey ); newItem->setType( aType ); newItem->setFormat( aFormat ); newItem->setVersion( aVersion ); if( !newItem->write( 0, aData.toUtf8() ) ) { delete newItem; qCCritical(lcSyncML) << "Could not write to item"; return false; } iAddList.insert( aItemId, newItem ); qCDebug(lcSyncML) << "Item queued for addition"; return true; } bool StorageHandler::replaceItem( const ItemId& aItemId, StoragePlugin& aPlugin, const QString& aLocalKey, const SyncItemKey& aParentKey, const QString& aType, const QString& aFormat, const QString& aVersion, const QString& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Processing item for replace:" << aItemId.iCmdId <<"/" << aItemId.iItemIndex; if( iLargeObject ) { qCCritical(lcSyncML) << "Already processing large object, aborting"; return false; } SyncItem* item = NULL; // If local key is empty, this Replace should be handled as Add (this is allowed by the protocol) if( !aLocalKey.isEmpty() ) { item = aPlugin.getSyncItem( aLocalKey ); } if( !item ) { qCDebug(lcSyncML) << "Could not find item, processing as Add"; return addItem( aItemId, aPlugin, aLocalKey, aParentKey, aType, aFormat, aVersion, aData ); } item->setParentKey( aParentKey ); item->setType( aType ); item->setFormat( aFormat ); item->setVersion( aVersion ); if( !item->write( 0, aData.toUtf8() ) ) { delete item; qCCritical(lcSyncML) << "Could not write to item"; return false; } iReplaceList.insert( aItemId, item ); qCDebug(lcSyncML) << "Item queued for replace"; return true; } bool StorageHandler::deleteItem( const ItemId& aItemId, const SyncItemKey& aLocalKey ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Processing item for delete:" << aItemId.iCmdId <<"/" << aItemId.iItemIndex; if( iLargeObject ) { qCCritical(lcSyncML) << "Already processing large object, aborting"; return false; } iDeleteList.insert( aItemId, aLocalKey ); qCDebug(lcSyncML) << "Item queued for delete"; return true; } bool StorageHandler::startLargeObjectAdd( StoragePlugin& aPlugin, const QString& aRemoteKey, const SyncItemKey& aParentKey, const QString& aType, const QString& aFormat, const QString& aVersion, qint64 aSize ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iLargeObject ) { qCCritical(lcSyncML) << "Already processing large object, aborting"; return false; } SyncItem* newItem = aPlugin.newItem(); if( !newItem ) { qCCritical(lcSyncML) << "Could not create new item for large object"; return false; } //Setting empty string as we dont have any local key for it. newItem->setKey(QString()); newItem->setParentKey( aParentKey ); newItem->setType( aType ); newItem->setFormat( aFormat ); newItem->setVersion( aVersion ); iLargeObject = newItem; iLargeObjectSize = aSize; iLargeObjectKey = aRemoteKey; qCDebug(lcSyncML) << "Large object created for addition"; return true; } bool StorageHandler::startLargeObjectReplace( StoragePlugin& aPlugin, const QString& aLocalKey, const SyncItemKey& aParentKey, const QString& aType, const QString& aFormat, const QString& aVersion, qint64 aSize ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iLargeObject ) { qCCritical(lcSyncML) << "Already processing large object, aborting"; return false; } SyncItem* item = NULL; // If local key is empty, this Replace should be handled as Add (this is allowed by the protocol) if( !aLocalKey.isEmpty() ) { item = aPlugin.getSyncItem( aLocalKey ); } if( !item ) { qCCritical(lcSyncML) << "Could not find item, processing as Add"; return startLargeObjectAdd( aPlugin, aLocalKey, aParentKey, aType, aFormat, aVersion, aSize ); } item->setParentKey( aParentKey ); item->setType( aType ); item->setFormat( aFormat ); item->setVersion( aVersion ); iLargeObject = item; iLargeObjectSize = aSize; iLargeObjectKey = aLocalKey; if( !iLargeObject->resize(0) ) { qCDebug(lcSyncML) << "Large object created for replace couldn't be resized"; } qCDebug(lcSyncML) << "Large object created for replace"; return true; } bool StorageHandler::buildingLargeObject() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iLargeObject ) { return true; } else { return false; } } bool StorageHandler::matchesLargeObject( const QString& aKey ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aKey == iLargeObjectKey ) { return true; } else { delete iLargeObject; iLargeObject = NULL; iLargeObjectSize = 0; iLargeObjectKey.clear(); return false; } } bool StorageHandler::appendLargeObjectData( const QString& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iLargeObject ) { qCCritical(lcSyncML) << "Not building large object, aborting"; return false; } if( iLargeObject->write( iLargeObject->getSize(), aData.toUtf8() ) ) { return true; } else { delete iLargeObject; iLargeObject = NULL; iLargeObjectSize = 0; iLargeObjectKey.clear(); qCCritical(lcSyncML) << "Could not write to large object"; return false; } } bool StorageHandler::finishLargeObject( const ItemId& aItemId ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iLargeObject ) { qCCritical(lcSyncML) << "Not building large object, aborting"; return false; } if(iLargeObject->getKey()->isEmpty()) { qCDebug(lcSyncML) << "Queuing large object for addition"; iLargeObject->setKey(iLargeObjectKey); iAddList.insert( aItemId, iLargeObject ); } else { qCDebug(lcSyncML) << "Queuing large object for replace"; iLargeObject->setKey(iLargeObjectKey); iReplaceList.insert( aItemId, iLargeObject ); } iLargeObject = NULL; iLargeObjectSize = 0; iLargeObjectKey.clear(); return true; } QMap StorageHandler::resolveConflicts( ConflictResolver* aConflictResolver, QMap &aMap, CommitStatus aStatus ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QMutableMapIterator i(aMap); QMap results; ItemId iId; while( i.hasNext() ) { i.next(); CommitResult result; result.iItemKey = i.value(); result.iStatus = aStatus; iId.iCmdId = i.key().iCmdId; iId.iItemIndex = i.key().iItemIndex; qCDebug(lcSyncML) << "Checking item" << iId.iCmdId <<"/" << iId.iItemIndex << "for conflict"; if( aConflictResolver && aConflictResolver->isConflict( result.iItemKey, false ) ) { qCDebug(lcSyncML) << "Conflict detected"; if( aConflictResolver->localSideWins() ) { qCDebug(lcSyncML) << "Conflict resolved, local side wins"; result.iConflict = CONFLICT_LOCAL_WIN; aConflictResolver->revertLocalChange ( result.iItemKey, CR_MODIFY_TO_ADD ); i.remove(); } else { qCDebug(lcSyncML) << "Conflict resolved, remote side wins"; result.iConflict = CONFLICT_REMOTE_WIN; aConflictResolver->revertLocalChange ( result.iItemKey, CR_REMOVE_LOCAL ); } } else { qCDebug(lcSyncML) << "No conflict detected"; result.iConflict = CONFLICT_NO_CONFLICT; } results.insert( iId, result ); } return results; } QMap StorageHandler::resolveConflicts( ConflictResolver* aConflictResolver, QMap &aMap, CommitStatus aStatus ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QMap results; ItemId iId; QMutableMapIterator i(aMap); while( i.hasNext() ) { i.next(); CommitResult result; result.iItemKey = *i.value()->getKey(); result.iStatus = aStatus; iId.iCmdId = i.key().iCmdId; iId.iItemIndex = i.key().iItemIndex; qCDebug(lcSyncML) << "Checking item" << iId.iCmdId <<"/" << iId.iItemIndex << "for conflict"; if( aConflictResolver && aConflictResolver->isConflict( result.iItemKey, false ) ) { qCDebug(lcSyncML) << "Conflict detected"; if( aConflictResolver->localSideWins() ) { qCDebug(lcSyncML) << "Conflict resolved, local side wins"; result.iConflict = CONFLICT_LOCAL_WIN; delete i.value(); i.remove(); } else { qCDebug(lcSyncML) << "Conflict resolved, remote side wins"; result.iConflict = CONFLICT_REMOTE_WIN; aConflictResolver->revertLocalChange ( result.iItemKey, CR_REMOVE_LOCAL ); } } else { qCDebug(lcSyncML) << "No conflict detected"; result.iConflict = CONFLICT_NO_CONFLICT; } results.insert( iId, result ); } return results; } QMap StorageHandler::commitAddedItems( StoragePlugin& aPlugin, ConflictResolver* aConflictResolver ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QMap results = resolveConflicts (aConflictResolver, iAddList, COMMIT_INIT_ADD); QList addIds = iAddList.keys(); QList addItems = iAddList.values(); qCDebug(lcSyncML) << "Committing" << addItems.count() << "added items"; QList addStatus = aPlugin.addItems( addItems ); for( int i = 0; i < addStatus.count(); ++i ) { CommitResult& result = results[addIds[i]]; result.iItemKey = *addItems[i]->getKey(); qCDebug(lcSyncML) << "Item" << addIds[i].iCmdId << "/" << addIds[i].iItemIndex << "committed"; switch( addStatus[i] ) { case StoragePlugin::STATUS_OK: { qCDebug(lcSyncML) << "Commit result: COMMIT_ADDED"; result.iStatus = COMMIT_ADDED; emit itemProcessed( MOD_ITEM_ADDED, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() , addItems[i]->getType(), addItems.count() ); break; } case StoragePlugin::STATUS_DUPLICATE: { qCDebug(lcSyncML) << "Commit result: COMMIT_DUPLICATE"; result.iStatus = COMMIT_DUPLICATE; emit itemProcessed( MOD_ITEM_ADDED, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() , addItems[i]->getType(), addItems.count() ); break; } default: { result.iStatus = generalStatus( addStatus[i] ); emit itemProcessed( MOD_ITEM_ERROR, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() , addItems[i]->getType(), addItems.count() ); break; } } results.insert( addIds[i], result ); } qDeleteAll( addItems ); iAddList.clear(); return results; } QMap StorageHandler::commitReplacedItems( StoragePlugin& aPlugin, ConflictResolver* aConflictResolver ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QMap results = resolveConflicts (aConflictResolver, iReplaceList, COMMIT_INIT_REPLACE); QList replaceIds = iReplaceList.keys(); QList replaceItems = iReplaceList.values(); qCDebug(lcSyncML) << "Committing" << replaceItems.count() << "replaced items"; QList replaceStatus = aPlugin.replaceItems( replaceItems ); for( int i = 0; i < replaceStatus.count(); ++i ) { CommitResult& result = results[replaceIds[i]]; qCDebug(lcSyncML) << "Item" << replaceIds[i].iCmdId << "/" << replaceIds[i].iItemIndex << "committed"; switch( replaceStatus[i] ) { case StoragePlugin::STATUS_OK: { qCDebug(lcSyncML) << "Commit result: COMMIT_REPLACED"; result.iStatus = COMMIT_REPLACED; emit itemProcessed( MOD_ITEM_MODIFIED, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() , replaceItems[i]->getType(), replaceItems.count() ); break; } case StoragePlugin::STATUS_DUPLICATE: { qCDebug(lcSyncML) << "Commit result: COMMIT_DUPLICATE"; result.iStatus = COMMIT_DUPLICATE; emit itemProcessed( MOD_ITEM_MODIFIED, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() , replaceItems[i]->getType(), replaceItems.count() ); break; } default: { result.iStatus = generalStatus( replaceStatus[i] ); emit itemProcessed( MOD_ITEM_ERROR, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() , replaceItems[i]->getType(), replaceItems.count() ); break; } } } qDeleteAll( iReplaceList ); iReplaceList.clear(); return results; } QMap StorageHandler::commitDeletedItems( StoragePlugin& aPlugin, ConflictResolver* aConflictResolver ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QMap results = resolveConflicts (aConflictResolver, iDeleteList, COMMIT_INIT_DELETE); QList deleteIds = iDeleteList.keys(); QList deleteItems = iDeleteList.values(); qCDebug(lcSyncML) << "Committing" << deleteItems.count() << "deleted items"; QList deleteStatus = aPlugin.deleteItems( deleteItems ); for( int i = 0; i < deleteStatus.count(); ++i ) { CommitResult& result = results[deleteIds[i]]; qCDebug(lcSyncML) << "Item" << deleteIds[i].iCmdId << "/" << deleteIds[i].iItemIndex << "committed"; switch( deleteStatus[i] ) { case StoragePlugin::STATUS_OK: { qCDebug(lcSyncML) << "Commit result: COMMIT_DELETED"; result.iStatus = COMMIT_DELETED; emit itemProcessed( MOD_ITEM_DELETED, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() ,aPlugin.getFormatInfo().getPreferredRx().iType, deleteItems.count() ); break; } case StoragePlugin::STATUS_NOT_FOUND: { qCDebug(lcSyncML) << "Commit result: COMMIT_NOT_DELETED"; result.iStatus = COMMIT_NOT_DELETED; emit itemProcessed( MOD_ITEM_DELETED, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() ,aPlugin.getFormatInfo().getPreferredRx().iType, deleteItems.count() ); break; } default: { result.iStatus = generalStatus( deleteStatus[i] ); emit itemProcessed( MOD_ITEM_ERROR, MOD_LOCAL_DATABASE, aPlugin.getSourceURI() ,aPlugin.getFormatInfo().getPreferredRx().iType, deleteItems.count() ); break; } } } iDeleteList.clear(); return results; } CommitStatus StorageHandler::generalStatus( StoragePlugin::StoragePluginStatus aStatus ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); CommitStatus status; switch( aStatus ) { case StoragePlugin::STATUS_OBJECT_TOO_BIG: { qCDebug(lcSyncML) << "Commit result: COMMIT_ITEM_TOO_BIG"; status = COMMIT_ITEM_TOO_BIG; break; } case StoragePlugin::STATUS_STORAGE_FULL: { qCDebug(lcSyncML) << "Commit result: COMMIT_NOT_ENOUGH_SPACE"; status = COMMIT_NOT_ENOUGH_SPACE; break; } case StoragePlugin::STATUS_INVALID_FORMAT: { qCDebug(lcSyncML) << "Commit result: COMMIT_UNSUPPORTED_FORMAT"; status = COMMIT_UNSUPPORTED_FORMAT; break; } default: { qCDebug(lcSyncML) << "Commit result: COMMIT_GENERAL_ERROR"; status = COMMIT_GENERAL_ERROR; break; } } return status; } buteo-syncml-0.5.15/src/StorageHandler.h000066400000000000000000000301141433763642500201010ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef STORAGEHANDLER_H #define STORAGEHANDLER_H #include #include #include #include "SyncAgentConsts.h" #include "SyncItemKey.h" #include "StoragePlugin.h" namespace DataSync { class SyncItem; class ConflictResolver; /*! \brief Item commit status * */ enum CommitStatus { COMMIT_ADDED, /*! resolveConflicts( ConflictResolver* aConflictResolver, QMap &aList, CommitStatus aStatus); /*! \brief Same as above but takes QMap with SyncItemKey as input * called in case of delete o/p when we have only the item key. */ QMap resolveConflicts( ConflictResolver* aConflictResolver, QMap &aList, CommitStatus aStatus); /*! \brief Commits added items to local database * * @param aPlugin Local storage plugin * @param aConflictResolver If conflict resolution is to be done, conflict resolver. * Otherwise NULL * @return Commit results */ QMap commitAddedItems( StoragePlugin& aPlugin, ConflictResolver* aConflictResolver ); /*! \brief Commits replaced items to local database * * @param aPlugin Local storage plugin * @param aConflictResolver If conflict resolution is to be done, conflict resolver. * Otherwise NULL * @return Commit results */ QMap commitReplacedItems( StoragePlugin& aPlugin, ConflictResolver* aConflictResolver ); /*! \brief Commits deleted items to local database * * @param aPlugin Local storage plugin * @param aConflictResolver If conflict resolution is to be done, conflict resolver. * Otherwise NULL * @return Commit results */ QMap commitDeletedItems( StoragePlugin& aPlugin, ConflictResolver* aConflictResolver ); signals: /*! \brief Signal indicating that an item has been processed * * @param aModificationType Type of modification made to the item (addition, modification or delete) * @param aModifiedDatabase Database that was modified (local or remote) * @param aDatabase Identifier of the database that was modified * @param aMimeType Mime type of the item being processed * @param aCommittedItems No. of items committed for this operation (addition, modification or delete) */ void itemProcessed( DataSync::ModificationType aModificationType, DataSync::ModifiedDatabase aModifiedDatabase, const QString aDatabase,const QString aMimeType, int aCommittedItems); private: CommitStatus generalStatus( StoragePlugin::StoragePluginStatus aStatus ) const; QMap iAddList; QMap iReplaceList; QMap iDeleteList; SyncItem* iLargeObject; qint64 iLargeObjectSize; QString iLargeObjectKey; friend class StorageHandlerTest; }; } #endif // STORAGEHANDLER_H buteo-syncml-0.5.15/src/StoragePlugin.h000066400000000000000000000155711433763642500177740ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef STORAGEPLUGIN_H #define STORAGEPLUGIN_H #include #include #include "SyncItemKey.h" #include "SyncAgentConsts.h" #include "StorageContentFormatInfo.h" namespace DataSync { class SyncItem; /*! \brief Describes one storage backend in a synchronization process * * StoragePlugin is an entity which provides an interface for adding, removing * a SyncItem (like an email or bookmark), and read or write data to it. * The actual writing of data to an item is done via the SyncItem class methods. */ class StoragePlugin { public: /*! \brief Status of operation performed by storage plugin * */ enum StoragePluginStatus { STATUS_INVALID_FORMAT = -6, /*!< Operation failed because data is in invalid format*/ STATUS_STORAGE_FULL = -5, /*!< Operation failed because storage is full*/ STATUS_OBJECT_TOO_BIG = -4, /*!< Operation failed because object is too big*/ STATUS_ERROR = -3, /*!< General error occurred during operation*/ STATUS_DUPLICATE = -2, /*!< Operation was not performed as object was duplicate*/ STATUS_NOT_FOUND = -1, /*!< Operation failed as object was not found*/ STATUS_OK = 0 /*!< Operation was completed successfully*/ }; /*! \brief Destructor * */ virtual ~StoragePlugin() {} /*! \brief Returns the URI of the storage plugin. * * @return */ virtual const QString& getSourceURI() const = 0; /*! \brief Returns content format information of the storage plugin * */ virtual const StorageContentFormatInfo& getFormatInfo() const = 0; /*! \brief Returns the maximum size of items supported by the storage plugin * * @return */ virtual qint64 getMaxObjSize() const = 0; /*! \brief Returns SyncML Device Information CTCaps of this plugin * * MUST be in XML format with SyncML CTCap as root element * * @param aVersion Protocol version * @return */ virtual QByteArray getPluginCTCaps( ProtocolVersion aVersion ) const = 0; /*! \brief Returns SyncMl extensions supported by this plugin * * MUST be in XML format with Ext as root element * */ virtual QByteArray getPluginExts() const = 0; /*! \brief Get the id's of all stored items * * @param aKeys Array to which store item id's * @return True on success, otherwise false */ virtual bool getAll( QList& aKeys ) = 0; /*! \brief Get the id's of all items that have been modified after timestamp * * @param aNewKeys Array to which store item id's of new items * @param aReplacedKeys Array to which stora item id's of replaced items * @param aDeletedKeys Array to which stora item id's of deleted * @param aTimeStamp Timestamp * @return True on success, otherwise false */ virtual bool getModifications( QList& aNewKeys, QList& aReplacedKeys, QList& aDeletedKeys, const QDateTime& aTimeStamp ) = 0; /*! \brief Creates a new sync item * * This function generates a new sync item and returns it. The returned item * is temporary, which means it is not guaranteed that it has a key assigned, * and it is guaranteed that it has no data. * * @return New SyncItem instance on success, otherwise NULL */ virtual SyncItem* newItem() = 0; /*! \brief Returns a specific sync item identified by SyncItemKey * * @param aKey Key of the sync item * @return Sync item. If matching sync item is not found, NULL is returned */ virtual SyncItem* getSyncItem( const SyncItemKey& aKey ) = 0; /*! \brief Returns a list of sync items identified by sync item keys * * This function takes the advantage of batch fetches from storage plug-in's * that do support this. * * @param aKeyList Keys of the sync items * @return Sync item list. */ virtual QList getSyncItems( const QList& aKeyList ) = 0; /*! \brief Adds new items * * Items must NOT have their keys set before calling this function. After successful * addition, storage plugin sets the item id to it's allocated value * * @param aItems List of items to add * @return List of status codes corresponding to each item */ virtual QList addItems( const QList& aItems ) = 0; /*! \brief Replaces existing items * * Items must have their keys set before calling this function * * @param aItems List of items to replace * @return List of status codes corresponding to each item */ virtual QList replaceItems( const QList& aItems ) = 0; /*! \brief Deletes existing items * * @param aKeys List of items to delete * @return List of status codes corresponding to each key */ virtual QList deleteItems( const QList& aKeys ) = 0; #if 0 /*! \brief Delete all existing items * * @return true if all items were deleted, false otherwise. */ virtual bool deleteAllItems() = 0; #endif }; } #endif buteo-syncml-0.5.15/src/StorageProvider.h000066400000000000000000000071701433763642500203240ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef STORAGEPROVIDER_H #define STORAGEPROVIDER_H class QString; #include "StorageContentFormatInfo.h" namespace DataSync { class StoragePlugin; class SessionHandler; /*! \brief Storage provider interface for SyncAgent * */ class StorageProvider { public: /*! \brief Constructor * */ StorageProvider() : iSessionHandler(0) { } /*! \brief Destructor * */ virtual ~StorageProvider() { } /*! \brief Sets session handler * * \param aSessionHandler Pointer to session handler. Pointer should be valid * as long as this object is alive. */ void setSessionHandler(const SessionHandler *aSessionHandler) { iSessionHandler = aSessionHandler; } /*! \brief Provides content format information based on storage URI * * This is used by SyncAgent to examine content information of a storage * plugin before acquiring it. * * @param aURI Source URI of the storage * @param aInfo Content information of the storage (if successful) * @return True if the storage was found, otherwise false */ virtual bool getStorageContentFormatInfo( const QString& aURI, StorageContentFormatInfo& aInfo ) = 0; /*! \brief Provides a storage based on URI * * @param aURI Local URI of the storage to retrieve * @return Storage plugin if success, otherwise NULL */ virtual StoragePlugin* acquireStorageByURI( const QString& aURI ) = 0; /*! \brief Provides a storage based on MIME * * @param aMIME MIME of the storage to retrieve * @return Storage plugin if success, otherwise NULL */ virtual StoragePlugin* acquireStorageByMIME( const QString& aMIME ) = 0; /*! \brief Releases a storage * * @param aStorage Storage to release */ virtual void releaseStorage( StoragePlugin* aStorage ) = 0; protected: const SessionHandler *iSessionHandler; /*! * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SuspendLog.h" #include "SyncMLLogging.h" using namespace DataSync; SuspendLog::SuspendLog( QSqlDatabase& aDbHandle, const QString& aRemoteDevice, const QString& aSourceDbURI, const QString& aTargetDbURI ) : iDbHandle( aDbHandle ), iRemoteDevice( aRemoteDevice ), iSourceDbURI( aSourceDbURI ), iTargetDbURI( aTargetDbURI ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } SuspendLog::~SuspendLog() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } /* bool DataSync::ChangeLogHandler::createItemTrackingTable() { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString = "CREATE TABLE if not exists localchanges(id integer primary key autoincrement, remote_device varchar(512), local_database varchar(512), remote_database varchar(512), syncitemkey varchar(512), syncitemcmd integer)"; QSqlQuery query(queryString, iDbHandle); query.exec(); bool success = true; if (query.lastError().isValid()) { qCWarning(lcSyncML) << "Error found: " << query.lastError(); success = false; } return success; } bool DataSync::ChangeLogHandler::createMappingTrackingTable() { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString = "CREATE TABLE if not exists localmappings(id integer primary key autoincrement, remote_device varchar(512), local_database varchar(512), remote_database varchar(512), localkey varchar(512), remotekey varchar(512), msgref integer, cmdref interger)"; QSqlQuery query(queryString, iDbHandle); query.exec(); bool success = true; if (query.lastError().isValid()) { qCWarning(lcSyncML) << "Error found: " << query.lastError(); success = false; } return success; } void DataSync::ChangeLog::addPendingSyncItem(QString aRemoteDevice, QString aLocalDatabase, QString aRemoteDatabase, SyncItemKey aSyncItemKey, SyncMLCommand aSyncCmd) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString = "INSERT INTO localchanges(remote_device, local_database, remote_database, syncitemkey, syncitemcmd) VALUES (:remote_device, :local_database, :remote_database, :syncitemkey, :syncitemcmd)"; QSqlQuery query(iDbHandle); query.prepare( queryString ); query.bindValue(":remote_device", aRemoteDevice); query.bindValue(":local_database", aLocalDatabase); query.bindValue(":remote_database", aRemoteDatabase); query.bindValue(":syncitemkey", aSyncItemKey); query.bindValue(":syncitemcmd", aSyncCmd); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << "Query Error" << query.lastError(); } } void DataSync::ChangeLog::removePendingSyncItem(QString aRemoteDevice, QString aLocalDatabase, QString aRemoteDatabase, SyncItemKey aSyncItemKey) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString = "DELETE FROM localchanges WHERE remote_device = :remote_device AND local_database = :local_database AND remote_database = :remote_database AND syncitemkey = :syncitemkey"; QSqlQuery query(iDbHandle); query.prepare( queryString ); query.bindValue(":remote_device", aRemoteDevice); query.bindValue(":local_database", aLocalDatabase); query.bindValue(":remote_database", aRemoteDatabase); query.bindValue(":syncitemkey", aSyncItemKey); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << "Query Error" << query.lastError(); } } QList DataSync::ChangeLog::getPendingLocalChanges(QString aRemoteDevice, QString aLocalDatabase, QString aRemoteDatabase, SyncMLCommand aSyncCmd) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString( "SELECT syncitemkey FROM localchanges WHERE remote_device = :remote_device AND local_database = :local_database AND remote_database = :remote_database AND syncitemcmd = :syncitemcmd" ); QSqlQuery query( iDbHandle ); query.bindValue(":remote_device", aRemoteDevice); query.bindValue(":local_database", aLocalDatabase); query.bindValue(":remote_database", aRemoteDatabase); query.bindValue(":syncitemcmd", aSyncCmd); query.prepare( queryString ); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << query.lastError(); } SyncItemKey syncItemKey = ""; QList changelist; while(query.next()) { syncItemKey = query.value(0).toString(); changelist.append(syncItemKey); } return changelist; } int DataSync::ChangeLog::getLastSyncMode() { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString( "SELECT sync_mode FROM change_logs WHERE id=:id" ); QSqlQuery query( iDbHandle ); query.prepare( queryString ); query.bindValue(":id", iChangeLogId); query.exec(); int syncMode; if( query.lastError().isValid()) { qCDebug(lcSyncML) << "Query Error" << query.lastError(); syncMode = 0; } else if (query.next()) { syncMode = query.value(0).toInt(); } else { qCDebug(lcSyncML) << "Could not find sync mode"; syncMode = 0; } return syncMode; } void DataSync::ChangeLog::addPendingMapping(QString aRemoteDevice, QString aLocalDatabase, QString aRemoteDatabase, SyncItemKey aLocalKey, SyncItemKey aRemoteKey, int aMsgRef, int aCmdRef) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString = "INSERT INTO localmappings(remote_device, local_database, remote_database, localkey, remotekey, msgref, cmdref) VALUES (:remote_device, :local_database, :remote_database, :localkey, :remotekey, :msgref, :cmdref)"; QSqlQuery query(iDbHandle); query.prepare( queryString ); query.bindValue(":remote_device", aRemoteDevice); query.bindValue(":local_database", aLocalDatabase); query.bindValue(":remote_database", aRemoteDatabase); query.bindValue(":localkey", aLocalKey); query.bindValue(":remotekey", aRemoteKey); query.bindValue(":msgref", aMsgRef); query.bindValue(":cmdref", aCmdRef); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << "Query Error" << query.lastError(); } } void DataSync::ChangeLog::removePendingMappings(QString aRemoteDevice, QString aLocalDatabase, QString aRemoteDatabase, int aMsgRef, int aCmdRef) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString = "DELETE FROM localmappings WHERE remote_device = :remote_device AND local_database = :local_database AND remote_database = :remote_database AND msgref = :msgref AND cmdref = :cmdref"; QSqlQuery query(iDbHandle); query.prepare( queryString ); query.bindValue(":remote_device", aRemoteDevice); query.bindValue(":local_database", aLocalDatabase); query.bindValue(":remote_database", aRemoteDatabase); query.bindValue(":msgref", aMsgRef); query.bindValue(":cmdref", aCmdRef); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << "Query Error" << query.lastError(); } } QList DataSync::ChangeLog::getPendingLocalMappings(QString aRemoteDevice, QString aLocalDatabase, QString aRemoteDatabase) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString( "SELECT localkey, remotekey FROM localmappings WHERE remote_device = :remote_device AND local_database = :local_database AND remote_database = :remote_database" ); QSqlQuery query( iDbHandle ); query.bindValue(":remote_device", aRemoteDevice); query.bindValue(":local_database", aLocalDatabase); query.bindValue(":remote_database", aRemoteDatabase); query.prepare( queryString ); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << query.lastError(); } SyncItemKey localKey; SyncItemKey remoteKey; QList mappingList; while(query.next()) { localKey = query.value(0).toString(); remoteKey = query.value(1).toString(); UIDMapping mapping = {remoteKey, localKey}; mappingList.append( mapping ); } return mappingList; } bool DataSync::ChangeLog::getIntentionallySuspended() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool intentionalSuspension = false; const QString queryString( "SELECT intentional_suspension FROM change_logs WHERE id=:id" ); QSqlQuery query( iDbHandle ); query.prepare( queryString ); query.bindValue(":id", iChangeLogId); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << "Query Error" << query.lastError(); } else { if (query.next()) { intentionalSuspension = query.value(0).toInt(); } } return intentionalSuspension; } void ChangeLog::setIntentionallySuspended( bool aIntentionallySuspended) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString queryString( "UPDATE change_logs SET intentional_suspension=:intentional_suspension WHERE id =:id" ); QSqlQuery query(iDbHandle); query.prepare( queryString ); query.bindValue(":id", iChangeLogId); query.bindValue(":intentional_suspension", aIntentionallySuspended); query.exec(); if (query.lastError().isValid()) { qCDebug(lcSyncML) << query.lastError(); } } */ buteo-syncml-0.5.15/src/SuspendLog.h000066400000000000000000000047561433763642500172770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SUSPENDLOG_H #define SUSPENDLOG_H #include class QSqlDatabase; // @todo: properly implement this class in HSYML-380 task namespace DataSync { /*! \brief Stores the suspend-related information of different devices * */ class SuspendLog { public: /*! \brief Constructor * * @param aDbHandle Database handle to use * @param aRemoteDevice Remote device * @param aSourceDbURI URI of the local database * @param aTargetDbURI URI of the remote database */ SuspendLog( QSqlDatabase& aDbHandle, const QString& aRemoteDevice, const QString& aSourceDbURI, const QString& aTargetDbURI ); /*! \brief Destructor * */ ~SuspendLog(); private: QSqlDatabase& iDbHandle; QString iRemoteDevice; QString iSourceDbURI; QString iTargetDbURI; }; } #endif // SUSPENDLOG_H buteo-syncml-0.5.15/src/SyncAgent.cpp000066400000000000000000000446771433763642500174500ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncAgent.h" #include #include "ChangeLog.h" #include "SyncAgentConfig.h" #include "SyncResults.h" #include "ClientSessionHandler.h" #include "ServerSessionHandler.h" #include "RequestListener.h" #include "SyncMLLogging.h" using namespace DataSync; SyncAgent::SyncAgent(QObject* aParent) : QObject(aParent), iListener(0), iHandler(0), iConfig(0) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Register the struct as a type for the signals qRegisterMetaType("DataSync::SyncState"); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); } SyncAgent::~SyncAgent() { FUNCTION_CALL_TRACE(lcSyncMLTrace); abortListen(); cleanSession(); } // Bindings for dynamic linking extern "C" { SyncAgent* createSyncAgent(QObject* aParent) { return new SyncAgent(aParent); } void destroySyncAgent(SyncAgent* aObj) { delete aObj; aObj = 0; } } bool SyncAgent::startSync( const SyncAgentConfig& aConfig ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iHandler && !iListener) { return initiateSession( aConfig ); } else { qCCritical(lcSyncML) << "SyncAgent: Listening for requests, or synchronization in progress"; return false; } } bool SyncAgent::isSyncing() const { if( iHandler ) { return true; } else { return false; } } bool SyncAgent::listen( const SyncAgentConfig& aConfig ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iHandler && !iListener ) { return initiateListen( aConfig ); } else { qCCritical(lcSyncML) << "SyncAgent: Already listening for requests, or synchronization in progress"; return false; } } bool SyncAgent::isListening() const { if( iListener ) { return true; } else { return false; } } bool SyncAgent::pauseSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iHandler ) { QTimer::singleShot( 0, iHandler, SLOT(suspendSync()) ); return true; } else { qCCritical(lcSyncML) << "SyncAgent: Nothing to pause!"; return false; } } bool SyncAgent::resumeSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iHandler ) { QTimer::singleShot( 0, iHandler, SLOT(resumeSync()) ); return true; } else { qCCritical(lcSyncML) << "SyncAgent: Nothing to resume!"; return false; } } bool SyncAgent::abort(DataSync::SyncState aState) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iHandler ) { abortSession(aState); return true; } else if( iListener ) { abortListen(); return true; } else { qCCritical(lcSyncML) << "SyncAgent: Nothing to abort!"; return false; } } const SyncResults& SyncAgent::getResults() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); return iResults; } bool SyncAgent::cleanUp(const SyncAgentConfig* aConfig) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QList sourceDBs = aConfig->getSourceDbs(); sourceDBs.append (aConfig->getDisabledSourceDbs()); SyncDirection iDirection = aConfig->getSyncMode().syncDirection(); const QString remoteId = aConfig->getRemoteDeviceName(); QString dbPath = aConfig->getDatabaseFilePath(); qCDebug(lcSyncML) << "SyncAgent: Remote Id: " << remoteId; qCDebug(lcSyncML) << "SyncAgent: DB Path : " << dbPath; if (remoteId.isEmpty() || dbPath.isEmpty()) { return false; } qCDebug(lcSyncML) << "SyncAgent: Sync Direction: " << iDirection; bool success = true; for (int i = 0; i < sourceDBs.size(); ++i) { qCDebug(lcSyncML) << "SyncAgent: Removing anchors for source DB: " << sourceDBs.at(i); ChangeLog changeLog(remoteId, sourceDBs.at(i), iDirection); success = changeLog.remove (dbPath); if (!success){ qCWarning(lcSyncML) << "SyncAgent: Error Removing anchors for source DB: " << sourceDBs.at(i); } } return success; } void SyncAgent::receiveStateChanged( DataSync::SyncState aState ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "SyncAgent: Synchronization status changed to:" << aState; iResults.setState( aState ); emit stateChanged( aState ); } void SyncAgent::receiveSyncFinished( const QString& aDevId, DataSync::SyncState aState, const QString& aErrorString ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iResults.setRemoteDeviceId( aDevId ); cleanSession(); finishSync( aState, aErrorString ); } void SyncAgent::accquiredStorage( const QString& aStorageMimeType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "SyncAgent:Mime Type acquired : " << aStorageMimeType; emit storageAccquired(aStorageMimeType ); } void SyncAgent::receiveItemProcessed( DataSync::ModificationType aModificationType, DataSync::ModifiedDatabase aModifiedDatabase, const QString aLocalDatabase, const QString aMimeType, int aCommittedItems ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "SyncAgent: Item processed"; if( (aModifiedDatabase == MOD_LOCAL_DATABASE) || ( aModifiedDatabase == MOD_REMOTE_DATABASE )) { iResults.addProcessedItem( aModificationType, aModifiedDatabase, aLocalDatabase ); emit itemProcessed( aModificationType, aModifiedDatabase, aLocalDatabase , aMimeType, aCommittedItems ); } else { Q_ASSERT( 0 ); } } void SyncAgent::finishSync( DataSync::SyncState aState, const QString& aErrorString ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iResults.setState( aState ); iResults.setErrorString( aErrorString ); qCDebug(lcSyncML) << "SyncAgent: Synchronization finished with state:" << aState; emit syncFinished( aState ); } bool SyncAgent::initiateSession( const SyncAgentConfig& aConfig ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( !iHandler ); qCDebug(lcSyncML) << "SyncAgent: Preparing for synchronization..."; // * Validate critical configuration if( !aConfig.getTransport() ) { qCCritical(lcSyncML) << "SyncAgent: Invalid configuration, transport is NULL"; return false; } if( !aConfig.getStorageProvider() ) { qCCritical(lcSyncML) << "SyncAgent: Invalid configuration, storage provider is NULL"; return false; } if( aConfig.getSourceDbs().isEmpty() ) { qCCritical(lcSyncML) << "SyncAgent: Invalid configuration, could not find any source databases to sync"; return false; } // * Clear results of previous sync iResults.reset(); // * Determine type of sync const SyncMode& syncMode = aConfig.getSyncMode(); if( syncMode.syncInitiator() == INIT_CLIENT ) { // * Start client-initiated sync session return startClientInitiatedSession( aConfig ); } else if( syncMode.syncInitiator() == INIT_SERVER ) { // * Start server-initiated sync session return startServerInitiatedSession( aConfig ); } else { qCCritical(lcSyncML) << "SyncAgent: Invalid configuration, could not interpret SyncMode"; return false; } } bool SyncAgent::startClientInitiatedSession( const SyncAgentConfig& aConfig ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( !iHandler ); ClientSessionHandler* handler = new ClientSessionHandler( &aConfig, this ); connect( handler, SIGNAL(syncStateChanged(DataSync::SyncState )), this, SLOT(receiveStateChanged(DataSync::SyncState)), Qt::QueuedConnection ); connect( handler, SIGNAL(syncFinished(QString, DataSync::SyncState, QString )), this, SLOT(receiveSyncFinished(QString, DataSync::SyncState, QString)), Qt::QueuedConnection ); connect( handler, SIGNAL(storageAccquired(QString )), this, SLOT(accquiredStorage(QString)), Qt::QueuedConnection ); connect( handler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), this, SLOT( receiveItemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), Qt::QueuedConnection ); qCDebug(lcSyncML) << "SyncAgent: Everything OK, starting synchronization..."; // * Begin synchronization session QTimer::singleShot(0, handler, SLOT(initiateSync())); iHandler = handler; iConfig = &aConfig; return true; } bool SyncAgent::startServerInitiatedSession( const SyncAgentConfig& aConfig ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( !iHandler ); ServerSessionHandler* handler = new ServerSessionHandler( &aConfig, this ); connect( handler, SIGNAL(syncStateChanged(DataSync::SyncState )), this, SLOT(receiveStateChanged(DataSync::SyncState)), Qt::QueuedConnection ); connect( handler, SIGNAL(syncFinished(QString, DataSync::SyncState, QString )), this, SLOT(receiveSyncFinished(QString, DataSync::SyncState, QString)), Qt::QueuedConnection ); connect( handler, SIGNAL(storageAccquired(QString )), this, SLOT(accquiredStorage(QString)), Qt::QueuedConnection ); connect( handler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), this, SLOT( receiveItemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), Qt::QueuedConnection ); qCDebug(lcSyncML) << "SyncAgent: Everything OK, starting synchronization..."; // * Begin synchronization session QTimer::singleShot(0, handler, SLOT(initiateSync())); iHandler = handler; iConfig = &aConfig; return true; } void SyncAgent::abortSession(DataSync::SyncState aState) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( iHandler ); QMetaObject::invokeMethod( iHandler, "abortSync", Q_ARG( DataSync::SyncState, aState ), Q_ARG( QString, "User aborted synchronization" ) ); } void SyncAgent::cleanSession() { FUNCTION_CALL_TRACE(lcSyncMLTrace); delete iHandler; iHandler = NULL; } bool SyncAgent::initiateListen( const SyncAgentConfig& aConfig ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( !iListener ); qCDebug(lcSyncML) << "SyncAgent: Preparing for listening requests..."; // * Validate critical configuration if( !aConfig.getTransport() ) { qCCritical(lcSyncML) << "SyncAgent: Invalid configuration, transport is NULL"; return false; } if( !aConfig.getStorageProvider() ) { qCCritical(lcSyncML) << "SyncAgent: Invalid configuration, storage provider is NULL"; return false; } if( !aConfig.getTransport()->init() ) { qCCritical(lcSyncML) << "SyncAgent: Could not initiate transport"; return false; } // * Create & start request listener object RequestListener* listener = new RequestListener(this); connect( listener, SIGNAL(newPendingRequest()), this, SLOT(listenEvent()) ); connect( listener, SIGNAL(error(DataSync::SyncState,QString)), this, SLOT(listenError(DataSync::SyncState,QString)) ); if( listener->start( aConfig.getTransport() ) ) { qCDebug(lcSyncML) << "SyncAgent: Now listening for requests"; iListener = listener; iConfig = &aConfig; return true; } else { qCCritical(lcSyncML) << "SyncAgent: Could not start listening for requests"; delete listener; listener = 0; return false; } } void SyncAgent::listenEvent() { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( iListener ); qCDebug(lcSyncML) << "SyncAgent: Processing incoming request..."; RequestListener::RequestData data = iListener->takeRequestData(); iListener->stop(); cleanListenLater(); if( data.iType == RequestListener::REQUEST_CLIENT ) { qCDebug(lcSyncML) << "SyncAgent: Remote client requesting session with server"; ServerSessionHandler* handler = new ServerSessionHandler( iConfig, this ); connect( handler, SIGNAL(syncStateChanged(DataSync::SyncState )), this, SLOT(receiveStateChanged(DataSync::SyncState)), Qt::QueuedConnection ); connect( handler, SIGNAL(syncFinished(QString, DataSync::SyncState, QString )), this, SLOT(receiveSyncFinished(QString, DataSync::SyncState, QString)), Qt::QueuedConnection ); connect( handler, SIGNAL(storageAccquired(QString )), this, SLOT(accquiredStorage(QString)), Qt::QueuedConnection ); connect( handler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), this, SLOT( receiveItemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), Qt::QueuedConnection ); qCDebug(lcSyncML) << "SyncAgent: Everything OK, starting synchronization..."; // * Begin synchronization session handler->serveRequest( data.iFragments ); iHandler = handler; } else if( data.iType == RequestListener::REQUEST_SAN_XML ) { qCDebug(lcSyncML) << "SyncAgent: Remote server notifying client with OMA DS XML message"; ClientSessionHandler* handler = new ClientSessionHandler( iConfig, this ); connect( handler, SIGNAL(syncStateChanged(DataSync::SyncState )), this, SLOT(receiveStateChanged(DataSync::SyncState)), Qt::QueuedConnection ); connect( handler, SIGNAL(syncFinished(QString, DataSync::SyncState, QString )), this, SLOT(receiveSyncFinished(QString, DataSync::SyncState, QString)), Qt::QueuedConnection ); connect( handler, SIGNAL(storageAccquired(QString )), this, SLOT(accquiredStorage(QString)), Qt::QueuedConnection ); connect( handler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), this, SLOT( receiveItemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), Qt::QueuedConnection ); qCDebug(lcSyncML) << "SyncAgent: Everything OK, starting synchronization..."; // * Begin synchronization session handler->handleNotificationXML( data.iFragments ); iHandler = handler; } else if( data.iType == RequestListener::REQUEST_SAN_PACKAGE ) { qCDebug(lcSyncML) << "SyncAgent: Remote server notifying client with OMA DS SAN package"; ClientSessionHandler* handler = new ClientSessionHandler( iConfig, this ); connect( handler, SIGNAL(syncStateChanged(DataSync::SyncState )), this, SLOT(receiveStateChanged(DataSync::SyncState)), Qt::QueuedConnection ); connect( handler, SIGNAL(syncFinished(QString, DataSync::SyncState, QString )), this, SLOT(receiveSyncFinished(QString, DataSync::SyncState, QString)), Qt::QueuedConnection ); connect( handler, SIGNAL(storageAccquired(QString )), this, SLOT(accquiredStorage(QString)), Qt::QueuedConnection ); connect( handler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), this, SLOT( receiveItemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase,QString,QString,int ) ), Qt::QueuedConnection ); qCDebug(lcSyncML) << "SyncAgent: Everything OK, starting synchronization..."; // * Begin synchronization session handler->handleNotificationPackage( data.iSANData ); iHandler = handler; } else { qCCritical(lcSyncML) << "SyncAgent: Unknown listen event"; finishSync( INTERNAL_ERROR, "Unknown listen event" ); } } void SyncAgent::listenError( DataSync::SyncState aState, QString aErrorString ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_ASSERT( iListener ); abortListen(); qCCritical(lcSyncML) << "SyncAgent: Error while listening for incoming requests"; finishSync( aState, aErrorString ); } void SyncAgent::abortListen() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iListener ) { iListener->stop(); } cleanListen(); } void SyncAgent::cleanListen() { FUNCTION_CALL_TRACE(lcSyncMLTrace); delete iListener; iListener = NULL; } void SyncAgent::cleanListenLater() { FUNCTION_CALL_TRACE(lcSyncMLTrace); iListener->deleteLater(); iListener = NULL; } buteo-syncml-0.5.15/src/SyncAgent.h000066400000000000000000000760751433763642500171120ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ /*! \mainpage libbuteosyncml * * \section intro_sec Library overview * * Libbuteosyncml implements Open Mobile Alliance Data Synchronization protocol * (OMA DS), formerly known as SyncML. This library offers: * - Support for OMA DS 1.1.2 and 1.2.1 * - Both OMA DS Client and Server functionality * - Bindings for HTTP and OBEX * - WbXML support using libwbxml2 * * \section guides_sec Guides * * \li \ref whatis\n * \li \ref howtouse\n * \li \ref creatingstorageplugin\n * \li \ref otherconsiderations\n * * \section example_sec Examples * \li \ref example1\n * * \section other_sec Other * \li \ref conformance\n * * \page whatis What is libbuteosyncml? * Libbuteosyncml is a protocol stack that implements OMA DS standard. It is based * on Qt and provides easy-to-use and easy-to-understand interface for synchronizing * data between devices and services. * * It should be noted libbuteosyncml it is not a complete synchronization solution, * because in addition to the protocol stack, a total solution would include at least: * - Integration to storage backends. Libbuteosyncml has been designed to be * generic enough to allow synchronization of practically any kind of data * ranging from simple PIM data to large files. It does not understand anything * about the data it is synchronizing; this is the responsibility of 'storage * plugins' which are written by the developers interested in synchronizing some * specific data type, for example contacts. * - Detection of changes in a storage. SyncML protocol supports fast synchronization * that is achieved by sending only modifications occurred in a storage since last * synchronization session, instead of exchanging all the items. Implementation of * this detection of changes (additions, modifications and deletion of items) is * the responsibility of developers writing the 'storage plugins'. * - User interface. Libbuteosyncml includes Qt signals that provide information about * an ongoing synchronization sessions, but it is the responsibility of the developers * to act on these signals. * * \page howtouse How to use it * * Synchronization session is governed by SyncAgent. SyncAgent support two types of * operation: * - Initiating a synchronization towards another device or service * - Responding to synchronization request sent by another device or service * * SyncAgent must be configured by passing a SyncAgentConfig object to it. SyncAgentConfig * includes a number of parameters and properties that can be used to specify what should * be synchronized and how. These parameters and properties can be configured run-time, * or by specifying an XML file that corresponds to the defined configuration schema. * * The most critical configuration parameters include: * * - Storage provider. Developers using libbuteosyncml must implement StorageProvider * interface that SyncAgent uses to query storage backends when required. These storage * backends are abstracted by StoragePlugin interface, which developers also must implement * for each type of data they wish to synchronize. Libbuteosyncml does not provide readymade * StoragePlugin implementations, as these are highly dependant on the underlying storage * backend. * - Transport. Libbuteosyncml includes readymade transport for HTTP. For OBEX, SyncML bindings * are provided. Users must provide an implementation for OBEXConnection interface to * to use whatever transport layer is wanted ( for example Bluetooth, USB, IrDA, etc ). Creation * of totally custom transports is also supported, they can be implemented by inheriting from * Transport interface (or from BaseTransport abstract class that includes WbXML support). * - Location of database. Libbuteosyncml maintains an SQL database that includes SyncML sync * anchors, item ID mappings, MD5 nonces and suspend/resume information. By default this * database is placed to /etc/sync/, but is highly recommended that synchronization applications * specify their own location for this database. * - Information necessary to initiate a synchronization. For example in order to initiate a synchronization, * information is required what storage backends should be synchronized, should authentication * be used (and if so, which authentication scheme to use) and what protocol version to use. * * SyncAgent must be run in a thread that has an event loop. Synchronization is started by calling * either startSync() or listen(), after which status updates concerning the state of the * synchronization session can be received with signals stateChanged() and itemProcessed(). When * synchronization session is finished, syncFinished() signal is emitted and results of the * synchronization can be retrieved with getResults(). * * * \page creatingstorageplugin Creating a storage plugin * * Developers using libbuteosyncml must implement StorageProvider callback interface. This interface is * used by SyncAgent to reserve and release storage backends, based on either storage database URI or MIME type. * Individual storage backends are abstracted by StoragePlugin interface. This interface includes all the necessary * callback functions that SyncAgent needs to synchronize the database. This involves functionality related * to the following topics: * * - Metadata of the storage. SyncAgent must be able to access for example the source database URI, the list of * supported MIME types, maximum supported item size and SyncML CTCaps of the storage. * - Accessing storage items. SyncAgent must be able to access individual items of a storage backend. These items * are called 'sync items' that are represented by SyncItem class. Each 'sync item' is identified with a unique * ID that is reinforced by the StoragePlugin. * - Manipulation of storage items. The purpose of SyncML is synchronization, and this is achieved by adding new * items to a storage backend, and/or by modifying and deleting existing items of the storage backend. * - Sync analysis. In order to achieve fast synchronization, StoragePlugin implementations must be able to analyze * changes that have occurred in the storage backend since last synchronization. * * \page otherconsiderations Other considerations * * \page conformance Protocol conformance * * \section client12 OMA DS 1.2 Client features * * \subsection client12protocolsupported Supported conformance requirements * \li SCR-DS-CLIENT-001: Support of 'two-way sync' sync type * \li SCR-DS-CLIENT-002: Support of 'slow two-way sync' sync type * \li SCR-DS-CLIENT-003: Support of 'one-way sync from client only' sync type * \li SCR-DS-CLIENT-005: Support of 'one-way sync from server only' sync type * \li SCR-DS-CLIENT-007: Support of 'sync alert' * \li SCR-DS-CLIENT-008: Support of 'Sync Without Separate Initialization' * \li SCR-DS-CLIENT-009: Support of sending 'Large Objects' * \li SCR-DS-CLIENT-010: Support of receiving 'Large Objects' * \li SCR-DS-CLIENT-011: Support of 'Busy signaling' * \li SCR-DS-CLIENT-012: Support of suspend/resume * \li SCR-DS-CLIENT-014: Support for hierarchical synchronization * \li SCR-DS-CLIENT-LO-R-001: Indicate support for receiving Large Object in the DevInf * \li SCR-DS-CLIENT-LO-R-002: Sending MaxObjSize and MaxMsgSize * \li SCR-DS-CLIENT-LO-R-003: Sync Commands inside Large Object is handles as Atomic * \li SCR-DS-CLIENT-LO-S-004: Data chunks must be sent in continuous order without any new commands * \li SCR-DS-CLIENT-LO-S-005: Include Size in the first data chunk * \li SCR-DS-CLIENT-LO-S-006: All chunks except the last one must include "MoreData" tag * \li SCR-DS-CLIENT-LO-S-007: Repeat Meta and Item information in each chunk * * * \subsection client12protocolunsupported Unsupported conformance requirements * \li SCR-DS-CLIENT-004: Support of 'refresh sync from client only' sync type * \li SCR-DS-CLIENT-006: Support of 'refresh sync from server only' sync type * \li SCR-DS-CLIENT-013: Support for filtering * \li SCR-DS-CLIENT-015: Support WAP PUSH operation * \li SCR-DS-CLIENT-016: Support of 'sync alert' by WAP Push method * * * \subsection client12reprosupported Supported representation protocol requirements * \li SCR-DS-CUE-C-002: Support for Chal element (database-level authentication not supported) * \li SCR-DS-CUE-C-003: Support for Cmd element * \li SCR-DS-CUE-C-004: Support for CmdId element * \li SCR-DS-CUE-C-005: Support for CmdRef element * \li SCR-DS-CUE-C-006: Support for Cred element (database-level authentication not supported) * \li SCR-DS-CUE-C-010: Support for Final element * \li SCR-DS-CUE-C-013: Support for LocURI element * \li SCR-DS-CUE-C-014: Support for MoreData element * \li SCR-DS-CUE-C-015: Support for MsgID element * \li SCR-DS-CUE-C-016: Support for MsgRef element * \li SCR-DS-CUE-C-017: Support for NoResp element * \li SCR-DS-CUE-C-019: Support for NumberOfChanges element * \li SCR-DS-CUE-C-021: Support for RespURI element * \li SCR-DS-CUE-C-022: Support for SessionID element * \li SCR-DS-CUE-C-024: Support for Source element * \li SCR-DS-CUE-C-025: Support for SourceParent element * \li SCR-DS-CUE-C-026: Support for SourceRef element * \li SCR-DS-CUE-C-027: Support for Target element * \li SCR-DS-CUE-C-028: Support for TargetParent element * \li SCR-DS-CUE-C-029: Support for TargetRef element * \li SCR-DS-CUE-C-030: Support for VerDTD element * \li SCR-DS-CUE-C-031: Support for VerProto element * \li SCR-DS-MCE-C-001: Support for SyncML element * \li SCR-DS-MCE-C-002: Support for SyncHdr element * \li SCR-DS-MCE-C-003: Support for SyncBody element * \li SCR-DS-DDE-C-001: Support for Data element * \li SCR-DS-DDE-C-002: Support for Item element * \li SCR-DS-DDE-C-003: Support for Meta element * \li SCR-DS-PME-C-001: Support for Status element * \li SCR-DS-PCE-C-001: Support for Add element * \li SCR-DS-PCE-C-002: Support for Alert element * \li SCR-DS-PCE-C-005: Support for Delete element * \li SCR-DS-PCE-C-007: Support for Get element (Only for device info) * \li SCR-DS-PCE-C-008: Support for Map element * \li SCR-DS-PCE-C-009: Support for MapItem element * \li SCR-DS-PCE-C-011: Support for Put element (Only for device info) * \li SCR-DS-PCE-C-012: Support for Replace element * \li SCR-DS-PCE-C-013: Support for Result element (Only for device info) * \li SCR-DS-PCE-C-016: Support for Sync element * * * \subsection client12reprounsupported Unsupported representation protocol requirements * \li SCR-DS-CUE-C-001: Support for Archive element * \li SCR-DS-CUE-C-007: Support for Field element * \li SCR-DS-CUE-C-008: Support for Filter element * \li SCR-DS-CUE-C-009: Support for FilterType element * \li SCR-DS-CUE-C-011: Support for Lang element * \li SCR-DS-CUE-C-012: Support for LocName element * \li SCR-DS-CUE-C-018: Support for NoResults element * \li SCR-DS-CUE-C-020: Support for Record element * \li SCR-DS-CUE-C-023: Support for SftDel element * \li SCR-DS-PCE-C-003: Support for Atomic element * \li SCR-DS-PCE-C-004: Support for Copy element * \li SCR-DS-PCE-C-006: Support for Exec element * \li SCR-DS-PCE-C-010: Support for Move element * \li SCR-DS-PCE-C-014: Support for Search element * \li SCR-DS-PCE-C-015: Support for Sequence element * * * \section server12 OMA DS 1.2 Server features * \subsection server12protocolsupported Supported conformance requirements * \li SCR-DS-SERVER-001: Support of 'two-way sync' sync type * \li SCR-DS-SERVER-002: Support of 'slow two-way sync' sync type * \li SCR-DS-SERVER-003: Support of 'one-way sync from client only' sync type * \li SCR-DS-SERVER-005: Support of 'one-way sync from server only' sync type * \li SCR-DS-SERVER-007: Support of 'sync alert' * \li SCR-DS-SERVER-008: Support of 'Sync Without Separate Initialization' * \li SCR-DS-SERVER-009: Support of sending 'Large Objects' * \li SCR-DS-SERVER-010: Support of receiving 'Large Objects' * \li SCR-DS-SERVER-012: Support of suspend/resume * \li SCR-DS-SERVER-014: Support for hierarchical synchronization * \li SCR-DS-SERVER-LO-R-001: Indicate support for receiving Large Object in the DevInf * \li SCR-DS-SERVER-LO-R-002: Sending MaxObjSize and MaxMsgSize * \li SCR-DS-SERVER-LO-R-003: Sync Commands inside Large Object is handles as Atomic * \li SCR-DS-SERVER-LO-S-004: Data chunks must be sent in continuous order without any new commands * \li SCR-DS-SERVER-LO-S-005: Include Size in the first data chunk * \li SCR-DS-SERVER-LO-S-006: All chunks except the last one must include "MoreData" tag * \li SCR-DS-SERVER-LO-S-007: Repeat Meta and Item information in each chunk * * * \subsection server12protocolunsupported Unupported conformance requirements * \li SCR-DS-SERVER-004: Support of 'refresh sync from client only' sync type * \li SCR-DS-SERVER-006: Support of 'refresh sync from server only' sync type * \li SCR-DS-SERVER-011: Support of 'Busy signaling' * \li SCR-DS-SERVER-013: Support for filtering * * * \subsection server12reprosupported Supported representation protocol requirements * \li SCR-DS-CUE-S-002: Support for Chal element (database-level authentication not supported) * \li SCR-DS-CUE-S-003: Support for Cmd element * \li SCR-DS-CUE-S-004: Support for CmdId element * \li SCR-DS-CUE-S-005: Support for CmdRef element * \li SCR-DS-CUE-S-006: Support for Cred element (database-level authentication not supported) * \li SCR-DS-CUE-S-010: Support for Final element * \li SCR-DS-CUE-S-013: Support for LocURI element * \li SCR-DS-CUE-S-014: Support for MoreData element * \li SCR-DS-CUE-S-015: Support for MsgID element * \li SCR-DS-CUE-S-016: Support for MsgRef element * \li SCR-DS-CUE-S-017: Support for NoResp element * \li SCR-DS-CUE-S-019: Support for NumberOfChanges element * \li SCR-DS-CUE-S-021: Support for RespURI element * \li SCR-DS-CUE-S-022: Support for SessionID element * \li SCR-DS-CUE-S-024: Support for Source element * \li SCR-DS-CUE-S-025: Support for SourceParent element * \li SCR-DS-CUE-S-026: Support for SourceRef element * \li SCR-DS-CUE-S-027: Support for Target element * \li SCR-DS-CUE-S-028: Support for TargetParent element * \li SCR-DS-CUE-S-029: Support for TargetRef element * \li SCR-DS-CUE-S-030: Support for VerDTD element * \li SCR-DS-CUE-S-031: Support for VerProto element * \li SCR-DS-MCE-S-001: Support for SyncML element * \li SCR-DS-MCE-S-002: Support for SyncHdr element * \li SCR-DS-MCE-S-003: Support for SyncBody element * \li SCR-DS-DDE-S-001: Support for Data element * \li SCR-DS-DDE-S-002: Support for Item element * \li SCR-DS-DDE-S-003: Support for Meta element * \li SCR-DS-PME-S-001: Support for Status element * \li SCR-DS-PCE-S-001: Support for Add element * \li SCR-DS-PCE-S-002: Support for Alert element * \li SCR-DS-PCE-S-005: Support for Delete element * \li SCR-DS-PCE-S-007: Support for Get element (Only for device info) * \li SCR-DS-PCE-S-008: Support for Map element * \li SCR-DS-PCE-S-009: Support for MapItem element * \li SCR-DS-PCE-S-011: Support for Put element (Only for device info) * \li SCR-DS-PCE-S-012: Support for Replace element * \li SCR-DS-PCE-S-013: Support for Result element (Only for device info) * \li SCR-DS-PCE-S-016: Support for Sync element * * * \subsection server12reprounsupported Unsupported representation protocol requirements * \li SCR-DS-CUE-S-001: Support for Archive element * \li SCR-DS-CUE-S-007: Support for Field element * \li SCR-DS-CUE-S-008: Support for Filter element * \li SCR-DS-CUE-S-009: Support for FilterType element * \li SCR-DS-CUE-S-011: Support for Lang element * \li SCR-DS-CUE-S-012: Support for LocName element * \li SCR-DS-CUE-S-018: Support for NoResults element * \li SCR-DS-CUE-S-020: Support for Record element * \li SCR-DS-CUE-S-023: Support for SftDel element * \li SCR-DS-PCE-S-003: Support for Atomic element * \li SCR-DS-PCE-S-004: Support for Copy element * \li SCR-DS-PCE-S-006: Support for Exec element * \li SCR-DS-PCE-S-010: Support for Move element * \li SCR-DS-PCE-S-014: Support for Search element * \li SCR-DS-PCE-S-015: Support for Sequence element * * * \section client11 OMA DS 1.1 Client features * \subsection client11protocolsupported Supported conformance requirements * \li Support of 'two-way sync' * \li Support of 'slow two-way sync' * \li Support of 'one-way sync from client only' * \li Support of 'one-way sync from server only' * \li Support of 'sync alert' * * * \subsection client11protocolunsupported Unupported conformance requirements * \li Support of 'refresh sync from client only' * \li Support of 'refresh sync from server only' * * * \subsection client11reprosupported Supported representation protocol requirements * \li Chal (database-level authentication not supported) * \li Cmd * \li CmdID * \li CmdRef * \li Cred (database-level authentication not supported) * \li Final * \li LocURI * \li MoreData * \li MsgID * \li MsgRef * \li NoResp * \li NumberOfChanges * \li RespURI * \li SessionID * \li Source * \li SourceRef * \li Target * \li TargetRef * \li VerDTD * \li VerProto * \li SyncML * \li SyncHdr * \li SyncBody * \li Data * \li Item * \li Meta * \li Add * \li Alert * \li Delete * \li Get (Only for device info) * \li Map * \li MapItem * \li Put (Only for device info) * \li Replace * \li Result (Only for device info) * \li Status * \li Sync * * * \subsection client11reprounsupported Unsupported representation protocol requirements * \li Archive * \li Lang * \li LocName * \li NoResults * \li SftDel * \li Atomic * \li Copy * \li Exec * \li Search * \li Sequence * * * \section server11 OMA DS 1.1 Server features * \subsection server11protocolsupported Supported conformance requirements * \li Support of 'two-way sync' * \li Support of 'slow two-way sync' * \li Support of 'one-way sync from client only' * \li Support of 'one-way sync from server only' * \li Support of 'sync alert' * * * \subsection server11protocolunsupported Unupported conformance requirements * \li Support of 'refresh sync from client only' * \li Support of 'refresh sync from server only' * \li Support of 'busy signaling' * * * \subsection server11reprosupported Supported representation protocol requirements * \li Chal (database-level authentication not supported) * \li Cmd * \li CmdID * \li CmdRef * \li Cred (database-level authentication not supported) * \li Final * \li LocURI * \li MoreData * \li MsgID * \li MsgRef * \li NoResp * \li NumberOfChanges * \li RespURI * \li SessionID * \li Source * \li SourceRef * \li Target * \li TargetRef * \li VerDTD * \li VerProto * \li SyncML * \li SyncHdr * \li SyncBody * \li Data * \li Item * \li Meta * \li Add * \li Alert * \li Delete * \li Get (Only for device info) * \li Map * \li MapItem * \li Put (Only for device info) * \li Replace * \li Result (Only for device info) * \li Status * \li Sync * * * \subsection server11reprounsupported Unsupported representation protocol requirements * \li Archive * \li Lang * \li LocName * \li NoResults * \li SftDel * \li Atomic * \li Copy * \li Exec * \li Search * \li Sequence * * * * \page example1 Initiating a synchronization over HTTP * * The following code initiates a two-way synchronization with an online synchronization service * over HTTP. * \code * QT += core network * QT -= gui * TARGET = example1 * LIBS += -lbuteosyncml * TEMPLATE = app * SOURCES += main.cpp * * ------------------------------------- * * #include * * #include * #include * #include * * #include "MyStorageProvider.h" * * class SyncHandler : public QObject * { * public: * SyncHandler() * { * } * virtual ~SyncHandler() * { * } * * void start() * { * iConfig.fromFile( "MyConfig.xml" ); * iTransport.init(); * iTransport.setRemoteLocURI( "https://my.sync.service.com:443" ); * iConfig.setStorageProvider( &iProvider ); * iConfig.setTransport( &iTransport ); * iConfig.setSyncParams( "MySyncService", DataSync::DS_1_2, DataSync::SyncMode( DataSync::DIRECTION_TWO_WAY, * DataSync::INIT_CLIENT ) ); * iConfig.setAuthParams( DataSync::AUTH_BASIC, "MyUsername", "MyPassword"); * iConfig.addSyncTarget( "./contacts", "./contacts" ); * connect( &iAgent, SIGNAL(syncFinished(DataSync::SyncState)), * this, SLOT(syncFinished(DataSync::SyncState)) ); * iAgent.startSync( iConfig ); * } * * protected slots: * * void syncFinished( DataSync::SyncState aState ) * { * Q_UNUSED( aState ); * QCoreApplication::instance()->exit(); * } * * * private: * MyStorageProvider iProvider; * DataSync::HTTPTransport iTransport; * DataSync::SyncAgentConfig iConfig; * DataSync::SyncAgent iAgent; * }; * * int main(int argc, char *argv[]) * { * QCoreApplication a(argc, argv); * * SyncHandler handler; * handler.start(); * * return a.exec(); * } * \endcode */ #ifndef SYNCAGENT_H #define SYNCAGENT_H #include #include "SyncAgentConsts.h" #include "SyncResults.h" class SyncAgentTest; namespace DataSync { class SyncAgentConfig; class RequestListener; class SessionHandler; /*! \brief SyncAgent is the base API for using the synchronization library * An entity which provides the interface for synchronization to the application. * * SyncAgent entity which provides the interface for synchronization to the * application. It creates the synchronization thread for a specific connection * and fills up data the the protocol handler. * * As per Qt's Documentation on Threads, "The child of a QObject must always be * created in the thread where the parent was created. This implies, among other * things, that you should never pass the QThread object (this) as the parent of * an object created in the thread (since the QThread object itself was created * in another thread)." So, all actions pertaining to SyncAgent should be done * in one single thread. If the Agent is created in one thread and subsequent * commands are issued in another thread, Qt's parent child relationship between * multiple threads prevents the Signals to be emitted to parents in another thread. * * The behavior for "Issuing the same command twice" is unsupported and undefined. * */ class SyncAgent : public QObject { Q_OBJECT public: /*! \brief Constructor * * @param aParent QObject parent * */ explicit SyncAgent( QObject* aParent = 0 ); /*! \brief Destructor * */ virtual ~SyncAgent(); /*! \brief Initiate a synchronization session * * Prepare and initiate a synchronization session using the supplied * configuration. During preparation the supplied configuration is validated. * If configuration is not valid, false is returned and no actions will be made. * If configuration is valid, start event will be posted to event queue and this * function returns true. This function does not block execution for the duration * of the synchronization session. Progress of the synchronization session can be * observed with stateChanged() signal. When synchronization session finishes due * to success or failure, syncFinished() signal is emitted. Synchronization session * can be aborted by calling abort() function. * * @param aConfig Configuration to use when initiating synchronization. Ownership is * not transferred. * @return True if synchronization was successfully started and subsequent signals * can be expected to be emitted. False if synchronization could not be * started, and no subsequent signals will be emitted. */ bool startSync( const SyncAgentConfig& aConfig ); /*! \brief Returns whether synchronization is in progress * * @return True if synchronization is in progress, otherwise false */ bool isSyncing() const; /*! \brief Listen for incoming synchronization requests * * Prepare and listen for incoming synchronization request using the supplied * configuration. During preparation the supplied configuration is validated. * If configuration is not valid, false is returned and no actions will be made. * If configuration is valid, listen event will be posted to event queue and this * function returns true. Upon first synchronization request, the request will be * automatically served and synchronization session will be established. * This function does not block execution for the duration of the listening, nor * during the possible synchronization session. Progress of the synchronization * session can be observed with stateChanged() signal. When synchronization session * finishes due to success or failure, syncFinished() signal is emitted. Listening * can be aborted by calling abort() function. * * @param aConfig Configuration to use when initiating synchronization. Ownership is * not transferred. * @return True if listening was successfully started and subsequent signals * can be expected to be emitted. False if listening was not started, and * no subsequent signals will be emitted. */ bool listen( const SyncAgentConfig& aConfig ); /*! \brief Return whether listening is in progress * * @return True if listening is in progress, otherwise false */ bool isListening() const; /*! \ brief Aborts listening for requests or an ongoing synchronization * \param abort state * * @return True if there was some operation ongoing which was aborted, otherwise false */ bool abort(DataSync::SyncState aState = DataSync::ABORTED); /*! \brief Pause synchronization * * This method pauses an ongoing sync. The command will be processed and the * application will get a callback when the command has been executed successful * or with an error. * * @return */ bool pauseSync(); /*! \brief Resume synchronization * * This method resumes a suspended sync. The command will be * processed and the application will get a callback when the command * has been executed successful or with an error. * * @return */ bool resumeSync(); /*! \brief Cleans up any stored data of a profile which is deleted * * @return true on success. */ bool cleanUp (const SyncAgentConfig* aConfig); /*! \brief Returns results of the latest sync session * * @return Results */ const SyncResults& getResults() const; signals: // public signals /*! \brief Signal indicating that the state of the synchronization process * has changed * * @param aState New state of synchronization process */ void stateChanged( DataSync::SyncState aState ); /*! \brief Signal indicating that the synchronization process has finished * * @param aState Resulting state of the synchronization process */ void syncFinished( DataSync::SyncState aState ); /*! \brief Signal indicating that an item has been processed * * @param aModificationType Type of modification made to the item (addition, modification or delete) * @param aModifiedDatabase Database that was modified (local or remote) * @param aLocalDatabase Identifier of the local database used in the sync * @param aMimeType Mimetype of the item prcessed * @param aCommittedItems No. of items committed for this operation */ void itemProcessed( DataSync::ModificationType aModificationType, DataSync::ModifiedDatabase aModifiedDatabase, QString aLocalDatabase, QString aMimeType, int aCommittedItems ); /*! \brief Signal indicating that a storage has been acquired * * @param aMimeType MIME type of the storage */ void storageAccquired (QString aMimeType); private slots: void receiveStateChanged( DataSync::SyncState aState ); void receiveSyncFinished( const QString& aRemoteDeviceId, DataSync::SyncState aState, const QString& aErrorString ); void accquiredStorage( const QString& aStorageMimeType ); void receiveItemProcessed( DataSync::ModificationType aModificationType, DataSync::ModifiedDatabase aModifiedDatabase, const QString aDatabase, const QString aMimeType, int aCommittedItems ); void listenEvent(); void listenError( DataSync::SyncState aState, QString aErrorString ); private: void finishSync( DataSync::SyncState aState, const QString& aErrorString ); bool initiateSession( const SyncAgentConfig& aConfig ); bool startClientInitiatedSession( const SyncAgentConfig& aConfig ); bool startServerInitiatedSession( const SyncAgentConfig& aConfig ); void abortSession(DataSync::SyncState aState); void cleanSession(); bool initiateListen( const SyncAgentConfig& aConfig ); void abortListen(); void cleanListen(); void cleanListenLater(); RequestListener* iListener; SessionHandler* iHandler; const SyncAgentConfig* iConfig; SyncResults iResults; friend class ::SyncAgentTest; }; } typedef DataSync::SyncAgent* (*createSyncAgent_t)(QObject* aParent); typedef void destroySyncAgent_t(DataSync::SyncAgent*); #endif buteo-syncml-0.5.15/src/SyncAgentConfig.cpp000066400000000000000000000523011433763642500205550ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncAgentConfig.h" #include #include #include #include #include #include #include "SyncAgentConfigProperties.h" #include "SyncCommonDefs.h" #include "datatypes.h" #include "Transport.h" #include "SyncMLLogging.h" using namespace DataSync; SyncAgentConfig::SyncAgentConfig() : iTransport( NULL ), iStorageProvider( NULL ), iDatabaseFilePath( "/etc/buteo/syncml.db" ), iProtocolVersion( SYNCML_1_2 ), iAuthenticationType( AUTH_NONE ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } SyncAgentConfig::~SyncAgentConfig() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool SyncAgentConfig::fromFile( const QString& aFile, const QString& aSchemaFile ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // @todo: The QXmlSchema class has a memory leak (http://bugreports.qt.nokia.com/browse/QTBUG-8948). // As this function is called for every sync performed, this leads to large leaks. // Since the schema validation part is already commented out, // there is no need to create a QXmlSchema object here. /* QByteArray schemaData; if( !readFile( aSchemaFile, schemaData ) ) { qCCritical(lcSyncML) << "Could not open schema file:" << aSchemaFile; return false; } QXmlSchema schema; schema.load(schemaData); if( !schema.isValid() ) { qCCritical(lcSyncML) << "Schema file is invalid:" << aSchemaFile; return false; } */ QByteArray xmlData; if( !readFile( aFile, xmlData ) ) { return false; } // @todo: Schema validation is currently disabled, because QXmlSchemaValidator // does not seem to work properl atleast in arm7 environment. After adding // new configuration parameters the time taken by validation was over 5 minutes! // Checked the situation without new configuration parameters, and even then // validation takes about a second, which is a _lot_ when actual parsing // about 50ms. So, disabling this for now. Situation should be checked again // in the future. /* QXmlSchemaValidator validator( schema ); if( !validator.validate( xmlData ) ) { qCCritical(lcSyncML) << "File did not pass validation:" << aFile; return false; } */ return parseConfFile(xmlData); } void SyncAgentConfig::setTransport( Transport* aTransport ) { if( aTransport ) { QList properties = iTransportProperties.keys(); for( int i = 0; i < properties.count(); ++i ) { aTransport->setProperty( properties[i], iTransportProperties.value( properties[i] ) ); } } iTransport = aTransport; } Transport* SyncAgentConfig::getTransport() const { return iTransport; } void SyncAgentConfig::setStorageProvider( StorageProvider* aProvider ) { iStorageProvider = aProvider; } StorageProvider* SyncAgentConfig::getStorageProvider() const { return iStorageProvider; } void SyncAgentConfig::setDeviceInfo( const DeviceInfo &aDeviceInfo ) { iDeviceInfo = aDeviceInfo; } const DeviceInfo& SyncAgentConfig::getDeviceInfo() const { return iDeviceInfo; } void SyncAgentConfig::setDatabaseFilePath( const QString& aPath ) { iDatabaseFilePath = aPath; } const QString& SyncAgentConfig::getDatabaseFilePath() const { return iDatabaseFilePath; } void SyncAgentConfig::setLocalDeviceName ( const QString& aDeviceName ) { iLocalDeviceName = aDeviceName; } const QString& SyncAgentConfig::getLocalDeviceName() const { return iLocalDeviceName; } void SyncAgentConfig::setAgentProperty( const QString& aProperty, const QString& aValue ) { iAgentProperties.insert( aProperty, aValue ); } QString SyncAgentConfig::getAgentProperty( const QString& aProperty ) const { return iAgentProperties.value( aProperty ); } void SyncAgentConfig::setTransportProperty( const QString& aProperty, const QString& aValue ) { iTransportProperties.insert( aProperty, aValue ); } QString SyncAgentConfig::getTransportProperty( const QString& aProperty ) const { return iTransportProperties.value( aProperty ); } void SyncAgentConfig::setSyncParams( const QString& aRemoteDeviceName, ProtocolVersion aVersion, const SyncMode& aSyncMode ) { iRemoteDeviceName = aRemoteDeviceName; iProtocolVersion = aVersion, iSyncMode = aSyncMode; } const QString& SyncAgentConfig::getRemoteDeviceName() const { return iRemoteDeviceName; } const ProtocolVersion& SyncAgentConfig::getProtocolVersion() const { return iProtocolVersion; } const SyncMode& SyncAgentConfig::getSyncMode() const { return iSyncMode; } void SyncAgentConfig::setAuthParams( const AuthType& aAuthType, const QString& aUsername, const QString& aPassword, const QString& aNonce ) { iAuthenticationType = aAuthType; iUsername = aUsername; iPassword = aPassword; iNonce = aNonce; } const AuthType& SyncAgentConfig::getAuthType() const { return iAuthenticationType; } const QString& SyncAgentConfig::getUsername() const { return iUsername; } const QString& SyncAgentConfig::getPassword() const { return iPassword; } const QString& SyncAgentConfig::getNonce() const { return iNonce; } void SyncAgentConfig::addSyncTarget( const QString& aSourceDb, const QString& aTargetDb ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iTargets[aSourceDb] = aTargetDb; iTargetDbs.append(aSourceDb); } void SyncAgentConfig::addDisabledSyncTarget( const QString& aSourceDb) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iDTargetDbs.append(aSourceDb); } QList SyncAgentConfig::getDisabledSourceDbs() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); return iDTargetDbs; } QList SyncAgentConfig::getSourceDbs() const { return iTargetDbs; } QString SyncAgentConfig::getTarget( const QString& aSourceDb ) const { return iTargets.value( aSourceDb ); } const QMap* SyncAgentConfig::getTargets() const { return &iTargets; } void SyncAgentConfig::setExtension( const QString& aName, const QVariant& aData ) { // ** Validate extensions data bool valid = false; if( aName == EMITAGSEXTENSION ) { QStringList tags = aData.toStringList(); if( tags.count() == 2 ) { valid = true; } else { qCWarning(lcSyncML) << "EMI tags extension: missing required data!"; } } else if( aName == SYNCWITHOUTINITPHASEEXTENSION ) { if( !aData.isValid() ) { valid = true; } else { qCWarning(lcSyncML) << "Sync without init phase extension: data should be invalid!"; } } else if( aName == SANMAPPINGSEXTENSION ) { QStringList mappings = aData.toStringList(); if( !mappings.isEmpty() && mappings.count() % 2 == 0 ) { valid = true; } else { qCWarning(lcSyncML) << "SAN mappings extension: missing required data!"; } } else { qCWarning(lcSyncML) << "Unknown extension" << aName; } if( valid ) { iExtensions.insert( aName, aData ); } } bool SyncAgentConfig::extensionEnabled( const QString& aName ) const { return iExtensions.contains( aName ); } QVariant SyncAgentConfig::getExtensionData( const QString& aName ) const { return iExtensions.value( aName ); } void SyncAgentConfig::clearExtension( const QString& aName ) { iExtensions.remove( aName ); } bool SyncAgentConfig::readFile( const QString& aFileName, QByteArray& aData ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QFile file( aFileName ); if( file.open( QIODevice::ReadOnly ) ) { aData = file.readAll(); file.close(); return true; } else { qCDebug(lcSyncML) << "Could not read file:" << aFileName; return false; } } bool SyncAgentConfig::parseConfFile( const QByteArray& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QXmlStreamReader reader( aData ); const QString ROOTELEMENT( "meego-syncml-conf" ); const QString DBPATH( "dbpath" ); const QString LOCALDEVICENAME( "local-device-name" ); const QString AGENTPROPS( "agent-props" ); const QString TRANSPORTPROPS( "transport-props" ); const QString EXTENSIONS( "extensions" ); while( !reader.atEnd() ) { if( reader.tokenType() == QXmlStreamReader::StartElement ) { if( reader.name() == DBPATH ) { reader.readNext(); QString dbPath = reader.text().toString(); qCDebug(lcSyncML) << "Found critical property" << DBPATH <<":" << dbPath; QFileInfo dbPathInfo(dbPath); if (dbPathInfo.isAbsolute()) { setDatabaseFilePath( dbPath ); } else { if (QDir().mkpath(Sync::syncConfigDir())) { setDatabaseFilePath(Sync::syncConfigDir() + QDir::separator() + dbPathInfo.fileName()); } else { qCCritical(lcSyncML) << "Unable to create database dir"; return false; } } } else if( reader.name() == LOCALDEVICENAME ) { reader.readNext(); QString localDeviceName = reader.text().toString(); qCDebug(lcSyncML) << "Found critical property" << LOCALDEVICENAME <<":" << localDeviceName; setLocalDeviceName( localDeviceName ); } else if( reader.name() == AGENTPROPS ) { parseAgentProps( reader ); } else if( reader.name() == TRANSPORTPROPS ) { parseTransportProps( reader ); } else if( reader.name() == EXTENSIONS ) { parseSyncExtensions( reader ); } } reader.readNext(); } return true; } bool SyncAgentConfig::parseAgentProps( QXmlStreamReader& aReader ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString AGENTPROPS( "agent-props" ); while( !aReader.atEnd() ) { if( aReader.tokenType() == QXmlStreamReader::StartElement ) { if( aReader.name() == MAXCHANGESPERMESSAGEPROP ) { aReader.readNext(); QString maxChangesPerMessage = aReader.text().toString(); qCDebug(lcSyncML) << "Found agent property" << MAXCHANGESPERMESSAGEPROP <<":" << maxChangesPerMessage; setAgentProperty( MAXCHANGESPERMESSAGEPROP, maxChangesPerMessage ); } else if( aReader.name() == MAXMESSAGESIZEPROP ) { aReader.readNext(); QString maxMessageSize = aReader.text().toString(); qCDebug(lcSyncML) << "Found agent property" << MAXMESSAGESIZEPROP <<":" << maxMessageSize; setAgentProperty( MAXMESSAGESIZEPROP, maxMessageSize ); } else if( aReader.name() == CONFLICTRESOLUTIONPOLICYPROP ) { aReader.readNext(); QString conflictResolutionPolicy = aReader.text().toString(); qCDebug(lcSyncML) << "Found agent property" << CONFLICTRESOLUTIONPOLICYPROP <<":" << conflictResolutionPolicy; setAgentProperty( CONFLICTRESOLUTIONPOLICYPROP, conflictResolutionPolicy ); } else if( aReader.name() == FASTMAPSSENDPROP ) { aReader.readNext(); QString fastMapsSend = aReader.text().toString(); qCDebug(lcSyncML) << "Found agent property" << FASTMAPSSENDPROP <<":" << fastMapsSend; setAgentProperty( FASTMAPSSENDPROP, fastMapsSend ); } else if( aReader.name() == OMITDATAUPDATESTATUSPROP ) { aReader.readNext(); QString omitDataUpdateStatus = aReader.text().toString(); qCDebug(lcSyncML) << "Found agent property" << OMITDATAUPDATESTATUSPROP <<":" << omitDataUpdateStatus; setAgentProperty( OMITDATAUPDATESTATUSPROP, omitDataUpdateStatus ); } } else if( aReader.tokenType() == QXmlStreamReader::EndElement && aReader.name() == AGENTPROPS ) { break; } aReader.readNext(); } return true; } bool SyncAgentConfig::parseTransportProps( QXmlStreamReader& aReader ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString TRANSPORTPROPS( "transport-props" ); while( !aReader.atEnd() ) { if( aReader.tokenType() == QXmlStreamReader::StartElement ) { if( aReader.name() == OBEXMTUBTPROP ) { aReader.readNext(); QString btObexMtu = aReader.text().toString(); qCDebug(lcSyncML) << "Found transport property" << OBEXMTUBTPROP <<":" << btObexMtu; setTransportProperty( OBEXMTUBTPROP, btObexMtu ); } else if( aReader.name() == OBEXMTUUSBPROP ) { aReader.readNext(); QString usbObexMtu = aReader.text().toString(); qCDebug(lcSyncML) << "Found transport property" << OBEXMTUUSBPROP <<":" << usbObexMtu; setTransportProperty( OBEXMTUUSBPROP, usbObexMtu ); } else if( aReader.name() == OBEXMTUOTHERPROP ) { aReader.readNext(); QString otherObexMtu = aReader.text().toString(); qCDebug(lcSyncML) << "Found transport property" << OBEXMTUOTHERPROP <<":" << otherObexMtu; setTransportProperty( OBEXMTUOTHERPROP, otherObexMtu ); } else if( aReader.name() == OBEXTIMEOUTPROP ) { aReader.readNext(); QString obexTimeout= aReader.text().toString(); qCDebug(lcSyncML) << "Found transport property" << OBEXTIMEOUTPROP <<":" << obexTimeout; setTransportProperty( OBEXTIMEOUTPROP, obexTimeout ); } else if( aReader.name() == HTTPNUMBEROFRESENDATTEMPTSPROP ) { aReader.readNext(); QString numAttempts = aReader.text().toString(); qCDebug(lcSyncML) << "Found transport property" << HTTPNUMBEROFRESENDATTEMPTSPROP <<":" << numAttempts; setTransportProperty( HTTPNUMBEROFRESENDATTEMPTSPROP, numAttempts ); } else if( aReader.name() == HTTPPROXYHOSTPROP ) { aReader.readNext(); QString proxyHost = aReader.text().toString(); qCDebug(lcSyncML) << "Found transport property" << HTTPPROXYHOSTPROP <<":" << proxyHost; setTransportProperty( HTTPPROXYHOSTPROP, proxyHost ); } else if( aReader.name() == HTTPPROXYPORTPROP ) { aReader.readNext(); QString proxyPort = aReader.text().toString(); qCDebug(lcSyncML) << "Found transport property" << HTTPPROXYPORTPROP <<":" << proxyPort; setTransportProperty( HTTPPROXYPORTPROP, proxyPort ); } } else if( aReader.tokenType() == QXmlStreamReader::EndElement && aReader.name() == TRANSPORTPROPS ) { break; } aReader.readNext(); } return true; } bool SyncAgentConfig::parseSyncExtensions( QXmlStreamReader& aReader ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString EXTENSIONS( "extensions" ); while( !aReader.atEnd() ) { if( aReader.tokenType() == QXmlStreamReader::StartElement ) { if( aReader.name() == EMITAGSEXTENSION ) { parseEMITagsExtension( aReader ); } else if( aReader.name() == SYNCWITHOUTINITPHASEEXTENSION ) { aReader.readNext(); qCDebug(lcSyncML) << "Found extension" << SYNCWITHOUTINITPHASEEXTENSION; QVariant data; setExtension( SYNCWITHOUTINITPHASEEXTENSION, data ); } else if( aReader.name() == SANMAPPINGSEXTENSION ) { parseSANMappingsExtension( aReader ); } } else if( aReader.tokenType() == QXmlStreamReader::EndElement && aReader.name() == EXTENSIONS ) { break; } aReader.readNext(); } return true; } bool SyncAgentConfig::parseEMITagsExtension( QXmlStreamReader& aReader ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString EMITAGSTOKEN( "token" ); const QString EMITAGSRESPONSE( "response" ); QString token; QString response; while( !aReader.atEnd() ) { if( aReader.tokenType() == QXmlStreamReader::StartElement ) { if( aReader.name() == EMITAGSTOKEN ) { aReader.readNext(); token = aReader.text().toString(); qCDebug(lcSyncML) << "Found EMI tag" << EMITAGSTOKEN <<":" << token; } else if( aReader.name() == EMITAGSRESPONSE ) { aReader.readNext(); response = aReader.text().toString(); qCDebug(lcSyncML) << "Found EMI tag" << EMITAGSRESPONSE <<":" << response; } } else if( aReader.tokenType() == QXmlStreamReader::EndElement && aReader.name() == EMITAGSEXTENSION ) { break; } aReader.readNext(); } QStringList data; data << token << response; setExtension( EMITAGSEXTENSION, QVariant( data ) ); return true; } bool SyncAgentConfig::parseSANMappingsExtension( QXmlStreamReader& aReader ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString SANMAPPING( "san-mapping" ); QStringList data; while( !aReader.atEnd() ) { if( aReader.tokenType() == QXmlStreamReader::StartElement && aReader.name() == SANMAPPING ) { parseSANMappingData( aReader, data ); } else if( aReader.tokenType() == QXmlStreamReader::EndElement && aReader.name() == SANMAPPINGSEXTENSION ) { break; } aReader.readNext(); } setExtension( SANMAPPINGSEXTENSION, QVariant( data ) ); return true; } bool SyncAgentConfig::parseSANMappingData( QXmlStreamReader& aReader, QStringList& aMappings ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); const QString SANMAPPING( "san-mapping" ); const QString URI( "uri" ); const QString MIME( "mime" ); QString uri; QString mime; while( !aReader.atEnd() ) { if( aReader.tokenType() == QXmlStreamReader::StartElement ) { if( aReader.name() == URI ) { aReader.readNext(); uri = aReader.text().toString(); qCDebug(lcSyncML) << "Found SAN URI:" << uri; } else if( aReader.name() == MIME ) { aReader.readNext(); mime = aReader.text().toString(); qCDebug(lcSyncML) << "Found SAN MIME:" << mime; } } else if( aReader.tokenType() == QXmlStreamReader::EndElement && aReader.name() == SANMAPPING ) { break; } aReader.readNext(); } aMappings << uri << mime; return true; } buteo-syncml-0.5.15/src/SyncAgentConfig.h000066400000000000000000000335271433763642500202330ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCAGENTCONFIG_H #define SYNCAGENTCONFIG_H #include #include #include #include #include "SyncAgentConsts.h" #include "SyncMode.h" #include "DeviceInfo.h" class QXmlStreamReader; namespace DataSync { class StorageProvider; class Transport; class SyncAgentConfigTest; /*! \brief Configuration object for the SyncAgent * * This class specifies all necessary configuration parameters for * SyncAgent. Configuration parameters are divided between critical * parameters, non-critical properties and extensions. Critical * parameters can be accessed and manipulated using get/set-functions * related to a particular parameter. Non-critical properties are * divided between agent-related properties and transport-related * properties. Extensions can be used to enable or disable features * that SyncAgent supports that are not directly related to OMA DS * protocol. */ class SyncAgentConfig { public: /*! \brief Constructor * */ SyncAgentConfig(); /*! \brief Destructor * */ ~SyncAgentConfig(); /*! \brief Internalizes configuration from a file * * It should be noted that only common configuration can be internalized * from a file. Configuration related to callback interfaces * ( setTransport() and setStorageProvider() ) and initiating a * synchronization session cannot be internalized from a file, and must * always be explicitly set. * * @param aFile Configuration file * @param aSchemaFile XML Schema file used when validating configuration file * @return True on success, otherwise false */ bool fromFile( const QString& aFile, const QString& aSchemaFile = "/etc/buteo/meego-syncml-conf.xsd" ); /*! \brief Sets the transport to use in sync * * Ownership is NOT transferred. It is MANDATORY to set transport when * attempting sync. Otherwise, sync preparation will fail. * * @param aTransport Transport instance to use */ void setTransport( Transport* aTransport ); /*! \brief Returns the transport to use in sync * * Ownership is NOT transferred * * @return */ Transport* getTransport() const; /*! \brief Sets the storage provider to use in sync * * Ownership is NOT transferred. It is MANDATORY to set transport when * attempting sync. Otherwise, sync preparation will fail. */ void setStorageProvider( StorageProvider* aProvider ); /*! \brief Returns the storage provider to use in sync * * Ownership is NOT transferred * * @return */ StorageProvider* getStorageProvider() const; /*! \brief Sets the device information to be used * * @param aDeviceInfo Device info to use */ void setDeviceInfo(const DeviceInfo &aDeviceInfo); /*! \brief Returns the device information to be user * * @return */ const DeviceInfo& getDeviceInfo() const; /*! \brief Set the database file location (full path) * * If not set, defaults to /etc/buteo/syncml.db * * @param aPath Full database file path */ void setDatabaseFilePath( const QString& aPath ); /*! \brief Returns the database file location (full path) * * @return Full path to database file */ const QString& getDatabaseFilePath() const; /*! \brief Sets the local device name to be used in sync * * If not set, defaults to device ID specified in device info * * @param aLocalDevice Local Device identification */ void setLocalDeviceName( const QString& aLocalDevice ); /*! \brief Returns the local device name to be used in sync * * @return */ const QString& getLocalDeviceName() const; /*! \brief Sets a property value related to the agent * * If property already exists, old value is replaced. See * SyncAgentConfigProperties.h for a list of supported properties. * * @param aProperty Property to set * @param aValue Value to set */ void setAgentProperty( const QString& aProperty, const QString& aValue ); /*! \brief Gets a property value related to the agent * * @param aProperty Property to get * @return Value of property if found, otherwise empty */ QString getAgentProperty( const QString& aProperty ) const; /*! \brief Sets a property value related to the transport * * If property already exists, old value is replaced. See * SyncAgentConfigProperties.h for a list of supported properties. * * @param aProperty Property to set * @param aValue Value to set */ void setTransportProperty( const QString& aProperty, const QString& aValue ); /*! \brief Gets a property value related to the transport * * @param aProperty Property to get * @return Value of property if found, otherwise empty */ QString getTransportProperty( const QString& aProperty ) const; /*! \brief Set parameters for initiating synchronization * * It should be noted that these parameters are relevant only for * initiating synchronization, they are not used when serving. By default, * remote device name is set to unknown device identifier ("/"), protocol * version 1.2 is used, and two-way synchronization is performed. * * @param aRemoteDeviceName Name of the remote device to synchronize with. * If not set, defaults to unknown device "/" * @param aVersion Protocol version to use. If not set, defaults to SYNCML_1_2 * @param aSyncMode Type of sync to be used. If not set, defaults to * two-way fast sync initiated by client */ void setSyncParams( const QString& aRemoteDeviceName, ProtocolVersion aVersion, const SyncMode& aSyncMode ); /*! \brief Returns the remote device name to be used in sync * * @return */ const QString& getRemoteDeviceName() const; /*! \brief Returns the protocol version to be used in sync * * @return */ const ProtocolVersion& getProtocolVersion() const; /*! \brief Returns the type of sync to be used in sync * * @return */ const SyncMode& getSyncMode() const; /*! \brief Sets the parameters to authenticate a synchronization session * * It should be noted that these parameters are relevant only for * initiating synchronization, they are not used when serving. By default, * no authentication is used. * * @param aAuthType Authentication type to use * @param aUsername Username to use (if required, otherwise empty) * @param aPassword Password to use (if required, otherwise empty) * @param aNonce Externally provided nonce to use with MD5. Usually * there's no need to provide this. */ void setAuthParams( const AuthType& aAuthType, const QString& aUsername, const QString& aPassword, const QString& aNonce = "" ); /*! \brief Returns the authentication type to be used * * @return */ const AuthType& getAuthType() const; /*! \brief Returns the user name to use * * @return */ const QString& getUsername() const; /*! \brief Returns the password to be used in SyncML authentication * * @return */ const QString& getPassword() const; /*! \brief Returns the nonce to be used in SyncML MD5 authentication * * @return */ const QString& getNonce() const; /*! \brief Adds a target for sync * * @param aSourceDb Source database * @param aTargetDb Target database */ void addSyncTarget( const QString& aSourceDb, const QString& aTargetDb = ""); /*! \brief Returns the source database targets * * @return List of source database targets */ QList getSourceDbs() const; /*! \brief Adds a disabled sync target(required for deleting) * * @param aSourceDb Source database */ void addDisabledSyncTarget( const QString& aSourceDb); /*! \brief Returns the disabled(UI) source database targets * * @return List of disabled source database targets */ QList getDisabledSourceDbs() const; /*! \brief Returns the set target database for given source database * * @return Target database if found, otherwise "" */ QString getTarget( const QString& aSourceDb ) const; /*! \brief Returns a map containing all source -> target databases * * @return Map of source -> target databases */ const QMap* getTargets() const; /*! \brief Enables a protocol extension * * @param aName Name of the extension * @param aData Data of the extension */ void setExtension( const QString& aName, const QVariant& aData = QVariant() ); /*! \brief Returns whether protocol extension has been enabled * * @param aName Name of the extension * @return */ bool extensionEnabled( const QString& aName ) const; /*! \brief Returns data of enaled extension * * @param aName * @return */ QVariant getExtensionData( const QString& aName ) const; /*! \brief Disables a protocol extension * * @param aName Name of the extension */ void clearExtension( const QString& aName ); private: /*! \brief Read a file * * @param aFileName Filename of the file to read * @param aData If reading succeeded, contains file data * @return True if reading succeeded, false otherwise */ bool readFile( const QString& aFileName, QByteArray& aData ) const; /*! \brief Parse contents of configuration file * * @param aData Data of conf file * @return True on success, otherwise false */ bool parseConfFile( const QByteArray& aData ); /*! \brief Parse agent properties * * @param aReader XML stream reader to use * @return True on success, otherwise false */ bool parseAgentProps( QXmlStreamReader& aReader ); /*! \brief Parse transport properties * * @param aReader XML stream reader to use * @return True on success, otherwise false */ bool parseTransportProps( QXmlStreamReader& aReader ); /*! \brief Parse protocol extensions * * @param aReader XML stream reader to use * @return True on success, otherwise false */ bool parseSyncExtensions( QXmlStreamReader& aReader ); /*! \brief Parse EMI tags extension data * * @param aReader XML stream reader to use * @return True on success, otherwise false */ bool parseEMITagsExtension( QXmlStreamReader& aReader ); /*! \brief Parse SAN Mappings extension data * * @param aReader XML stream reader to use * @return True on success, otherwise false */ bool parseSANMappingsExtension( QXmlStreamReader& aReader ); /*! \brief Parse data of single SAN Mapping * * @param aReader XML stream reader to use * @param aMappings Mappings table to insert data to * @return True on success, otherwise false */ bool parseSANMappingData( QXmlStreamReader& aReader, QStringList& aMappings ); Transport* iTransport; StorageProvider* iStorageProvider; QString iDatabaseFilePath; QString iLocalDeviceName; DeviceInfo iDeviceInfo; QMap iAgentProperties; QMap iTransportProperties; QString iRemoteDeviceName; ProtocolVersion iProtocolVersion; SyncMode iSyncMode; AuthType iAuthenticationType; QString iUsername; QString iPassword; QString iNonce; QMap iExtensions; QMap iTargets; QList iTargetDbs; QList iDTargetDbs; friend class SyncAgentConfigTest; }; } Q_DECLARE_METATYPE(DataSync::SyncAgentConfig); #endif // SYNCAGENTCONFIG_H buteo-syncml-0.5.15/src/SyncAgentConfigProperties.h000066400000000000000000000072511433763642500223030ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCAGENTCONFIGPROPERTIES_H #define SYNCAGENTCONFIGPROPERTIES_H namespace DataSync { // Property to control maximum size of accepted messages const QString MAXMESSAGESIZEPROP( "max-message-size" ); // Property to control the maximum number of changes to send per message const QString MAXCHANGESPERMESSAGEPROP( "max-changes-per-message" ); // Property to control the conflict resolution policy const QString CONFLICTRESOLUTIONPOLICYPROP( "conflict-resolution-policy" ); // Property to control whether item ID mappings should be sent fast // (alongside Status of the operation in Pck#4), or separately in Pck#5 const QString FASTMAPSSENDPROP( "fast-maps-send" ); // Property to control whether the data update status package is sent // (as client) when there are no changes on the server side const QString OMITDATAUPDATESTATUSPROP( "omit-data-update-status" ); // Property to control the maximum transfer unit of OBEX over BT const QString OBEXMTUBTPROP( "obex-mtu-bt" ); // Property to control the maximum transfer unit of OBEX over USB const QString OBEXMTUUSBPROP( "obex-mtu-usb" ); // Property to control the maximum transfer unit of OBEX over custom // transport const QString OBEXMTUOTHERPROP( "obex-mtu-other" ); // Property to control the timeout to use with OBEX operations const QString OBEXTIMEOUTPROP( "obex-timeout" ); // Property to control the number of times the sending of first message is // attempted const QString HTTPNUMBEROFRESENDATTEMPTSPROP( "http-number-of-resend-attempts" ); // Property to control the host address of http proxy const QString HTTPPROXYHOSTPROP( "http-proxy-host" ); // Property to control the port of http proxy const QString HTTPPROXYPORTPROP( "http-proxy-port" ); // Property to control EMI tags extension const QString EMITAGSEXTENSION( "emi-tags" ); // Property to control sync without initialization phase extension const QString SYNCWITHOUTINITPHASEEXTENSION( "sync-without-init-phase" ); // Property to control SAN mappings extension const QString SANMAPPINGSEXTENSION( "san-mappings" ); } #endif // SYNCAGENTCONFIGPROPERTIES_H buteo-syncml-0.5.15/src/SyncAgentConsts.h000066400000000000000000000122161433763642500202670ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCAGENTCONSTS_H #define SYNCAGENTCONSTS_H #include namespace DataSync { /*! \brief SyncML protocol version to use * */ enum ProtocolVersion { SYNCML_1_2, /*! * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncItem.h" #include "SyncMLLogging.h" using namespace DataSync; SyncItem::SyncItem () { } SyncItem::~SyncItem() { } const SyncItemKey* SyncItem::getKey() const { return &iKey; } void SyncItem::setKey( const SyncItemKey& aKey ) { iKey = aKey; } const SyncItemKey* SyncItem::getParentKey() const { return &iParentKey; } void SyncItem::setParentKey( const SyncItemKey& aParentKey ) { iParentKey = aParentKey; } QString SyncItem::getType() const { return iType; } void SyncItem::setType( const QString& aType ) { iType = aType; } QString SyncItem::getFormat() const { return iFormat; } void SyncItem::setFormat( const QString& aFormat ) { iFormat = aFormat; } QString SyncItem::getVersion() const { return iVersion; } void SyncItem::setVersion( const QString& aVersion ) { iVersion = aVersion; } buteo-syncml-0.5.15/src/SyncItem.h000066400000000000000000000111001433763642500167240ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCITEM_H #define SYNCITEM_H #include #include #include "SyncItemKey.h" namespace DataSync { /*! \brief Base class for items of data that can be synchronized * * SyncItem describes one synchronizable item. Each SyncItem has a unique * key assigned to it. SyncItem can be temporary, in this case it has no key * assigned to it. getKey() will return "" in this case. */ class SyncItem { public: /*! \brief Constructor * */ SyncItem(); /*! \brief Destructor * */ virtual ~SyncItem(); /*! \brief Returns the key of this item * * @return */ const SyncItemKey* getKey() const; /*! \brief Sets the key of this item * * @param aKey Key for the item */ void setKey( const SyncItemKey& aKey ); /*! \brief Returns the key of the parent of this item * * @return */ const SyncItemKey* getParentKey() const; /*! \brief Sets the key of the parent of this item * * @param aParentKey Key of the parent of this item */ void setParentKey( const SyncItemKey& aParentKey ); /*! \brief Returns the MIME type of this item * * @return */ QString getType() const; /*! \brief Sets the MIME type of this item * * @param aType MIME type for the item */ void setType( const QString& aType ); /*! \brief Returns the format of this item * * @return */ QString getFormat() const; /*! \brief Sets the format of this item * * @param aFormat Format of this item */ void setFormat( const QString& aFormat ); /*! \brief Returns the version of this item * * @return */ QString getVersion() const; /*! \brief Sets the version of this item * * @param aVersion Version of this item */ void setVersion( const QString& aVersion ); /*! \brief Returns the total size of the item data * * @return Size of the item data */ virtual qint64 getSize() const = 0; /*! \brief This method reads bytes of data from sync item * * @param aOffset Offset to start reading from * @param aLength Number of bytes to read * @param aData Data buffer where to place read data * @return */ virtual bool read( qint64 aOffset, qint64 aLength, QByteArray& aData ) const = 0; /*! \brief This method resizes the sync item * * @param aLength New Size * @return True on success, otherwise false */ virtual bool resize( qint64 aLength ) = 0; /*! \brief This method writes data to sync item. * * @param aOffset Offset to start writing from * @param aData Data buffer to write. All bytes from buffer are written * @return */ virtual bool write( qint64 aOffset, const QByteArray& aData ) = 0; private: SyncItemKey iKey; SyncItemKey iParentKey; QString iType; QString iFormat; QString iVersion; }; } #endif /* SYNCITEM_H */ buteo-syncml-0.5.15/src/SyncItemKey.h000066400000000000000000000033551433763642500174120ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCITEMKEY_H #define SYNCITEMKEY_H #include namespace DataSync { typedef QString SyncItemKey; } #endif buteo-syncml-0.5.15/src/SyncItemPrefetcher.cpp000066400000000000000000000120351433763642500212770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncItemPrefetcher.h" #include "SyncItem.h" #include "StoragePlugin.h" #include "SyncMLLogging.h" using namespace DataSync; SyncItemPrefetcher::SyncItemPrefetcher( const QList& aItemIds, StoragePlugin& aStoragePlugin, int aInitialBatchSizeHint ) : iStoragePlugin( aStoragePlugin ), iItemIdList( aItemIds ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iDefaultBatchSizeHint = aInitialBatchSizeHint; setBatchSizeHint( aInitialBatchSizeHint ); } SyncItemPrefetcher::~SyncItemPrefetcher() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qDeleteAll( iFetchedItems.values() ); iFetchedItems.clear(); } void SyncItemPrefetcher::setBatchSizeHint( int aBatchSizeHint ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iBatchSizeHint = aBatchSizeHint; } SyncItem* SyncItemPrefetcher::getItem( const SyncItemKey& aItemId ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if(!iBatchSizeHint) { iBatchSizeHint = iDefaultBatchSizeHint - iFetchedItems.count(); } if( iFetchedItems.contains( aItemId ) ) { // Prefetch hit: return item immediately qCDebug(lcSyncML) << "Item" << aItemId << "found from prefetched items"; return iFetchedItems.take( aItemId ); } else { // Prefetch miss: fetch more items qCDebug(lcSyncML) << "Item" << aItemId << "not found from prefetched items"; prefetch(); return iFetchedItems.take( aItemId ); } } void SyncItemPrefetcher::prefetch() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Item prefetcher waking..."; if( iFetchedItems.count() < iBatchSizeHint ) { qCDebug(lcSyncML) << "Prefetch cache not full"; int batchSize = qMin( iBatchSizeHint, iItemIdList.size() ); if( batchSize > 0 ) { qCDebug(lcSyncML) << "Requesting" << batchSize << "items"; QList nextItemIds = iItemIdList.mid( 0, batchSize ); QList nextItems = iStoragePlugin.getSyncItems( nextItemIds ); if( nextItems.count() != nextItemIds.count() ) { // We cannot trust the ordering nor the integrity of the items returned by the backend, so just // free them qCWarning(lcSyncML) << "Asked for" << nextItemIds.count() << "items, got" << nextItems.count() << "items"; qDeleteAll( nextItems ); nextItems.clear(); } for ( int i = 0; i < nextItemIds.count(); ++i ) { SyncItem* item = 0; for( int a = 0; a < nextItems.count(); ++a ) { if( nextItems[a] && nextItems[a]->getKey() == nextItemIds[i] ) { item = nextItems[a]; nextItems.removeAt( a ); } } iFetchedItems.insert( nextItemIds[i], item ); } iItemIdList = iItemIdList.mid( batchSize ); } else { qCDebug(lcSyncML) << "No more items remaining, skipping item request"; } } else { qCDebug(lcSyncML) << "Prefetch cache is already full"; } qCDebug(lcSyncML) << iFetchedItems.count() << "items in prefetch cache," << iItemIdList.count() << "items still to fetch"; qCDebug(lcSyncML) << "Item prefetcher going to sleep..."; } buteo-syncml-0.5.15/src/SyncItemPrefetcher.h000066400000000000000000000070601433763642500207460ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCITEMPREFETCHER_H #define SYNCITEMPREFETCHER_H #include #include #include #include "SyncItemKey.h" class SyncItemPrefetcherTest; namespace DataSync { class StoragePlugin; class SyncItem; /*! \brief Class that prefetches items from storage plugin based on * batch size hint to increase performance when sending items * * This class takes advantage on that the order of items requested from * storage plugin is known (aItemIds). Items are fetched in advance based * on current batch size hint. */ class SyncItemPrefetcher : public QObject { Q_OBJECT; public: /*! \brief Constructor * * @param aItemIds Ordered list of items to prefetch * @param aStoragePlugin Storage plugin from where to prefetch items * @param aInitialBatchSizeHint Initial value for batch size hint */ SyncItemPrefetcher( const QList& aItemIds, StoragePlugin& aStoragePlugin, int aInitialBatchSizeHint ); /*! \brief Destructor * */ virtual ~SyncItemPrefetcher(); /*! \brief Sets batch size hint * * @param aBatchSizeHint New value */ void setBatchSizeHint( int aBatchSizeHint ); /*! \brief Retrieve next item * * If item is not prefetched, next prefetch round is done and item * is returned after that * * @param aItemId Id of the item to retrieve * @return */ SyncItem* getItem( const SyncItemKey& aItemId ); public slots: /*! \brief Slot that should be invoked when prefetching can be done * */ void prefetch(); private: StoragePlugin& iStoragePlugin; int iBatchSizeHint; int iDefaultBatchSizeHint; QList iItemIdList; QHash iFetchedItems; friend class ::SyncItemPrefetcherTest; }; } #endif // SYNCITEMPREFETCHER_H buteo-syncml-0.5.15/src/SyncMLCommand.h000066400000000000000000000043741433763642500176540ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLCOMMAND_H #define SYNCMLCOMMAND_H namespace DataSync { /*! \brief Enumeration representing different SyncML commands * */ enum SyncMLCommand { SYNCML_ADD, /*! * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLGLOBALS_H #define SYNCMLGLOBALS_H #include "SyncItemKey.h" namespace DataSync { /*! \brief Possible sync types as specified in DevInf * */ enum SyncTypes { SYNCTYPE_TWOWAY = 1, SYNCTYPE_TWOWAYSLOW, SYNCTYPE_FROMCLIENT, SYNCTYPE_FROMCLIENTSLOW, SYNCTYPE_FROMSERVER, SYNCTYPE_FROMSERVERSLOW, SYNCTYPE_SERVERALERTED }; /*! \brief UID mapping of a single item * */ struct UIDMapping { QString iRemoteUID; ///< UID of the item in remote side SyncItemKey iLocalUID; ///< UID of the item in local side }; } #endif // SYNCMLGLOBALS_H buteo-syncml-0.5.15/src/SyncMLLogging.cpp000066400000000000000000000034031433763642500202070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2021 Jolla Ltd. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLLogging.h" Q_LOGGING_CATEGORY(lcSyncML, "buteo.syncml", QtWarningMsg) Q_LOGGING_CATEGORY(lcSyncMLProtocol, "buteo.syncml.protocol", QtWarningMsg) Q_LOGGING_CATEGORY(lcSyncMLTrace, "buteo.syncml.trace", QtWarningMsg) buteo-syncml-0.5.15/src/SyncMLLogging.h000066400000000000000000000034441433763642500176610ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2021 Jolla Ltd. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLLOGGING_H #define SYNCMLLOGGING_H #include #include Q_DECLARE_LOGGING_CATEGORY(lcSyncML) Q_DECLARE_LOGGING_CATEGORY(lcSyncMLProtocol) Q_DECLARE_LOGGING_CATEGORY(lcSyncMLTrace) #endif // SYNCMLLOGGING_H buteo-syncml-0.5.15/src/SyncMLMessageParser.cpp000066400000000000000000001450121433763642500213650ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMessageParser.h" #include #include "RemoteDeviceInfo.h" #include "SyncMLLogging.h" using namespace DataSync; SyncMLMessageParser::SyncMLMessageParser() : iLastMessageInPackage( false ), iError( PARSER_ERROR_LAST ), iSyncHdrFound( false ), iSyncBodyFound( false ), iIsNewPacket( false ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qRegisterMetaType("DataSync::ParserError"); #ifdef QT_DEBUG // additional functions for debugging the status and alert codes from server initMaps(); #endif } SyncMLMessageParser::~SyncMLMessageParser() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qDeleteAll(iFragments); iFragments.clear(); } QList SyncMLMessageParser::takeFragments() { FUNCTION_CALL_TRACE(lcSyncMLTrace); QList fragments = iFragments; iFragments.clear(); return fragments; } void SyncMLMessageParser::parseResponse( QIODevice *aDevice, bool aIsNewPacket ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iIsNewPacket = aIsNewPacket; if( aDevice->bytesAvailable() == 0 ) { qCCritical(lcSyncML) << "Zero-sized message detected, aborting parsing"; emit parsingError( PARSER_ERROR_INVALID_DATA ); } else { qCDebug(lcSyncML) << "Beginning to parse incoming message..."; iReader.setDevice( aDevice ); iReader.setNamespaceProcessing( false ); startParsing(); qCDebug(lcSyncML) << "Incoming message parsed"; } } void SyncMLMessageParser::startParsing() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qDeleteAll(iFragments); iFragments.clear(); iLastMessageInPackage = false; iSyncHdrFound = false; iSyncBodyFound = false; iError = PARSER_ERROR_LAST; while( shouldContinue() ) { iReader.readNext(); QXmlStreamReader::TokenType token = iReader.tokenType(); switch( token ) { case QXmlStreamReader::StartDocument: { break; } case QXmlStreamReader::EndDocument: { break; } case QXmlStreamReader::StartElement: { QStringRef name = iReader.name(); if( name == SYNCML_ELEMENT_SYNCHDR ) { readHeader(); } else if( name == SYNCML_ELEMENT_SYNCBODY ) { readBody(); } else if( name != SYNCML_ELEMENT_SYNCML ){ qCCritical(lcSyncML) << "Unexpected element in SyncML message:" << name; iError = PARSER_ERROR_UNEXPECTED_DATA; } break; } case QXmlStreamReader::EndElement: case QXmlStreamReader::Characters: case QXmlStreamReader::DTD: case QXmlStreamReader::Comment: { break; } case QXmlStreamReader::Invalid: case QXmlStreamReader::NoToken: case QXmlStreamReader::EntityReference: case QXmlStreamReader::ProcessingInstruction: { qCCritical(lcSyncML) << "Unexpected token in SyncML message" << iReader.tokenType(); iError = PARSER_ERROR_UNEXPECTED_DATA; break; } } } if( iError != PARSER_ERROR_LAST ) { qCCritical(lcSyncML) << "Error while parsing SyncML document:" << iError; // Check if the parsing error happened due to invalid XML characters if( iIsNewPacket && ( QXmlStreamReader::PrematureEndOfDocumentError == iReader.error() || QXmlStreamReader::NotWellFormedError == iReader.error() ) ) { // Change error here to Invalid character found error // so that session handler can retry after removing illegal // characters iError = PARSER_ERROR_INVALID_CHARS; } emit parsingError( iError ); } else if( !iSyncHdrFound || !iSyncBodyFound ) { qCCritical(lcSyncML) << "Malformed SyncML document, missing either SyncHdr or SyncBody"; emit parsingError( PARSER_ERROR_INCOMPLETE_DATA ); } else { emit parsingComplete(iLastMessageInPackage); } } void SyncMLMessageParser::readBody() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iSyncBodyFound ) { qCCritical(lcSyncML) << "Invalid SyncML message, multiple SyncBody elements found"; iError = PARSER_ERROR_INVALID_DATA; return; } iSyncBodyFound = true; while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_SYNCBODY ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_STATUS) { readStatus(); } else if (name == SYNCML_ELEMENT_SYNC) { readSync(); } else if (name == SYNCML_ELEMENT_PUT) { readPut(); } else if (name == SYNCML_ELEMENT_RESULTS) { readResults(); } else if (name == SYNCML_ELEMENT_MAP ) { readMap(); }else if (name == SYNCML_ELEMENT_FINAL) { iLastMessageInPackage = true; } else { CommandParams* command = new CommandParams(); if( readCommand( name, *command ) ) { iFragments.append( command ); } else { delete command; command = 0; qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in BODY:NOT HANDLED BY PARSER" << name; } } } } if( iReader.atEnd() ) { qCCritical(lcSyncML) << "Incomplete SyncML message"; iError = PARSER_ERROR_INCOMPLETE_DATA; } } void SyncMLMessageParser::readHeader() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iSyncHdrFound ) { qCCritical(lcSyncML) << "Invalid SyncML message, multiple SyncHdr elements found"; iError = PARSER_ERROR_INVALID_DATA; return; } iSyncHdrFound = true; HeaderParams *header = new HeaderParams(); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_SYNCHDR ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_VERDTD) { header->verDTD = readString(); } else if (name == SYNCML_ELEMENT_VERPROTO) { header->verProto = readString(); } else if (name == SYNCML_ELEMENT_SESSIONID) { header->sessionID = readString(); } else if (name == SYNCML_ELEMENT_MSGID) { header->msgID = readInt(); } else if (name == SYNCML_ELEMENT_TARGET) { header->targetDevice = readURI(); } else if (name == SYNCML_ELEMENT_SOURCE) { header->sourceDevice = readURI(); } else if (name == SYNCML_ELEMENT_RESPURI) { header->respURI = readString(); } else if (name == SYNCML_ELEMENT_NORESP) { header->noResp = true; } else if (name == SYNCML_ELEMENT_CRED) { readCred( header->cred ); } else if (name == SYNCML_ELEMENT_META) { readMeta( header->meta ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in HEADER:NOT HANDLED BY PARSER" << name; } } } iFragments.append(header); if( iReader.atEnd() ) { qCCritical(lcSyncML) << "Incomplete SyncML message"; iError = PARSER_ERROR_INCOMPLETE_DATA; } } void SyncMLMessageParser::readChal( ChalParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); if( iReader.isEndElement() && iReader.name() == SYNCML_ELEMENT_CHAL ) { break; } if( iReader.isStartElement() ) { if( iReader.name() == SYNCML_ELEMENT_META ) { readMeta( aParams.meta ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in CHAL:NOT HANDLED BY PARSER" << iReader.name(); } } } } void SyncMLMessageParser::readStatus() { FUNCTION_CALL_TRACE(lcSyncMLTrace); StatusParams *status = new StatusParams(); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_STATUS ) { break; } if( iReader.isStartElement() ) { if(name == SYNCML_ELEMENT_CMDID) { status->cmdId = readInt(); } else if (name == SYNCML_ELEMENT_MSGREF) { status->msgRef = readInt(); } else if (name == SYNCML_ELEMENT_CMDREF) { status->cmdRef = readInt(); } else if (name == SYNCML_ELEMENT_CMD) { status->cmd = readString(); } else if (name == SYNCML_ELEMENT_TARGETREF) { status->targetRef = readString(); } else if (name == SYNCML_ELEMENT_SOURCEREF) { status->sourceRef = readString(); } else if (name == SYNCML_ELEMENT_DATA) { status->data = (ResponseStatusCode)readInt(); qCDebug(lcSyncML) << iStatusCodeMap[status->data] << ":" << status->data; } else if (name == SYNCML_ELEMENT_ITEM) { ItemParams item; readItem( item ); status->items.append( item ); } else if (name == SYNCML_ELEMENT_CHAL) { status->hasChal = true; readChal( status->chal ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in STATUS:NOT HANDLED BY PARSER" << name; } } } iFragments.append(status); } void SyncMLMessageParser::readSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncParams *sync = new SyncParams(); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_SYNC ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_CMDID) { sync->cmdId = readInt(); } else if (name == SYNCML_ELEMENT_NORESP) { sync->noResp = true; } else if (name == SYNCML_ELEMENT_META) { readMeta( sync->meta ); } else if (name == SYNCML_ELEMENT_TARGET) { sync->target = readURI(); } else if (name == SYNCML_ELEMENT_SOURCE) { sync->source = readURI(); } else if( name == SYNCML_ELEMENT_NUMOFCHANGES ) { sync->numberOfChanges = readInt(); } else { CommandParams command; if( readCommand( name, command ) ) { sync->commands.append(command); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in SYNC:NOT HANDLED BY PARSER" << name; } } } } iFragments.append(sync); } void SyncMLMessageParser::readMap() { FUNCTION_CALL_TRACE(lcSyncMLTrace); MapParams *map = new MapParams(); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_MAP ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_CMDID) { map->cmdId = readInt(); } else if (name == SYNCML_ELEMENT_TARGET) { map->target = readURI(); } else if (name == SYNCML_ELEMENT_SOURCE) { map->source = readURI(); } else if (name == SYNCML_ELEMENT_META) { readMeta( map->meta ); } else if (name == SYNCML_ELEMENT_MAPITEM) { MapItemParams item; readMapItem( item ); map->mapItems.append( item ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in MAP:NOT HANDLED BY PARSER" << name; } } } iFragments.append(map); } void SyncMLMessageParser::readMapItem( MapItemParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_MAPITEM ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_TARGET) { aParams.target = readURI(); } else if (name == SYNCML_ELEMENT_SOURCE) { aParams.source = readURI(); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in MAPITEM:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readPut() { FUNCTION_CALL_TRACE(lcSyncMLTrace); PutParams* put = new PutParams; while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_PUT ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_CMDID) { put->cmdId = readInt(); } else if (name == SYNCML_ELEMENT_NORESP) { put->noResp = true; } else if (name == SYNCML_ELEMENT_META) { readMeta( put->meta ); } else if (name == SYNCML_ELEMENT_ITEM) { readDevInfItem( put->devInf ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in PUT:NOT HANDLED BY PARSER" << name; } } } // Ensure that the PUT fragment is kept next only to the HEADER, or RESULTS fragment. if( iFragments.count() > 0 ) { iFragments.insert( 1, put ); } else { iFragments.append(put); } } void SyncMLMessageParser::readResults() { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResultsParams *results = new ResultsParams(); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_RESULTS ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_CMDID) { results->cmdId = readInt(); } else if (name == SYNCML_ELEMENT_MSGREF) { results->msgRef = readInt(); } else if (name == SYNCML_ELEMENT_CMDREF) { results->cmdRef = readInt(); } else if (name == SYNCML_ELEMENT_META) { readMeta( results->meta ); } else if (name == SYNCML_ELEMENT_TARGETREF) { results->targetRef = readString(); } else if (name == SYNCML_ELEMENT_SOURCEREF) { results->sourceRef = readString(); } else if (name == SYNCML_ELEMENT_ITEM) { readDevInfItem( results->devInf ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in RESULTS:NOT HANDLED BY PARSER" << name; } } } // Ensure that the RESULTS fragment is kept next only to the HEADER, or PUT fragment. if( iFragments.count() > 0 ) { iFragments.insert(1, results); } else { iFragments.append(results); } } bool SyncMLMessageParser::readCommand( const QStringRef& aName, CommandParams& aCommand ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool found = true; if( aName == SYNCML_ELEMENT_ALERT ) { aCommand.commandType = CommandParams::COMMAND_ALERT; readLeafCommand( aCommand, SYNCML_ELEMENT_ALERT ); } else if (aName == SYNCML_ELEMENT_ADD) { aCommand.commandType = CommandParams::COMMAND_ADD; readLeafCommand( aCommand, SYNCML_ELEMENT_ADD ); } else if (aName == SYNCML_ELEMENT_REPLACE) { aCommand.commandType = CommandParams::COMMAND_REPLACE; readLeafCommand( aCommand, SYNCML_ELEMENT_REPLACE ); } else if (aName == SYNCML_ELEMENT_DELETE) { aCommand.commandType = CommandParams::COMMAND_DELETE; readLeafCommand( aCommand, SYNCML_ELEMENT_DELETE ); } else if (aName == SYNCML_ELEMENT_GET) { aCommand.commandType = CommandParams::COMMAND_GET; readLeafCommand( aCommand, SYNCML_ELEMENT_GET ); } else if (aName == SYNCML_ELEMENT_COPY) { aCommand.commandType = CommandParams::COMMAND_COPY; readLeafCommand( aCommand, SYNCML_ELEMENT_COPY ); } else if (aName == SYNCML_ELEMENT_MOVE) { aCommand.commandType = CommandParams::COMMAND_MOVE; readLeafCommand( aCommand, SYNCML_ELEMENT_MOVE ); } else if (aName == SYNCML_ELEMENT_EXEC ) { aCommand.commandType = CommandParams::COMMAND_EXEC; readLeafCommand( aCommand, SYNCML_ELEMENT_EXEC ); } else if (aName == SYNCML_ELEMENT_ATOMIC) { aCommand.commandType = CommandParams::COMMAND_ATOMIC; readContainerCommand( aCommand, SYNCML_ELEMENT_ATOMIC ); } else if (aName == SYNCML_ELEMENT_SEQUENCE) { aCommand.commandType = CommandParams::COMMAND_SEQUENCE; readContainerCommand( aCommand, SYNCML_ELEMENT_SEQUENCE ); } else { found = false; } return found; } void SyncMLMessageParser::readLeafCommand( CommandParams& aParams, const QString& aCommand ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == aCommand ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_CMDID ) { aParams.cmdId = readInt(); } else if( name == SYNCML_ELEMENT_NORESP ) { aParams.noResp = true; } else if (name == SYNCML_ELEMENT_DATA) { aParams.data = readString(); } else if( name == SYNCML_ELEMENT_CORRELATOR ) { aParams.correlator = readString(); } else if( name == SYNCML_ELEMENT_META ) { readMeta( aParams.meta ); } else if( name == SYNCML_ELEMENT_ITEM ) { ItemParams item; readItem( item ); aParams.items.append( item ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in COMMAND:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readContainerCommand( CommandParams& aParams, const QString& aCommand ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == aCommand ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_CMDID ) { aParams.cmdId = readInt(); } else if( name == SYNCML_ELEMENT_NORESP ) { aParams.noResp = true; } else if( name == SYNCML_ELEMENT_META ) { readMeta( aParams.meta ); } else { CommandParams command; if( readCommand( name, command ) ) { aParams.subCommands.append(command); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in COMMAND:NOT HANDLED BY PARSER" << name; } } } } } void SyncMLMessageParser::readCred( CredParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_CRED ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_META ) { readMeta( aParams.meta ); } else if( name == SYNCML_ELEMENT_DATA ) { aParams.data = readString(); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in CRED:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readMeta( MetaParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_META ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_FORMAT) { aParams.format = readString(); } else if (name == SYNCML_ELEMENT_SIZE) { aParams.size = readInt(); } else if (name == SYNCML_ELEMENT_TYPE) { aParams.type = readString(); } else if (name == SYNCML_ELEMENT_ANCHOR) { readAnchor( aParams.anchor ); } else if (name == SYNCML_ELEMENT_VERSION) { aParams.version = readString(); } else if (name == SYNCML_ELEMENT_NEXTNONCE) { aParams.nextNonce = readString(); } else if (name == SYNCML_ELEMENT_MAXMSGSIZE) { aParams.maxMsgSize = readInt(); } else if (name == SYNCML_ELEMENT_MAXOBJSIZE) { aParams.maxObjSize = readInt(); } else if (name == SYNCML_ELEMENT_EMI) { aParams.EMI.append( readString() ); } else if (name == SYNCML_ELEMENT_MARK) { aParams.mark = readString(); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in META:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readAnchor( AnchorParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_ANCHOR ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_NEXT) { aParams.next = readString(); } else if (name == SYNCML_ELEMENT_LAST) { aParams.last = readString(); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in ANCHOR:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readDevInfItem( DevInfItemParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_ITEM ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_SOURCE ) { aParams.source = readURI(); } else if( name == SYNCML_ELEMENT_DEVINF ) { readDevInf( aParams ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readDevInf( DevInfItemParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QString dtd; while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_DEVINF ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_VERDTD ) { dtd = readString(); if( dtd != SYNCML_DTD_VERSION_1_1 && dtd != SYNCML_DTD_VERSION_1_2 ) { qCCritical(lcSyncML) << "Unrecognized DevInf verDTD:" << dtd; iError = PARSER_ERROR_INVALID_DATA; } } else if( name == SYNCML_ELEMENT_MAN ) { aParams.devInfo.deviceInfo().setManufacturer( readString() ); } else if( name == SYNCML_ELEMENT_MOD ) { aParams.devInfo.deviceInfo().setModel( readString() ); } else if( name == SYNCML_ELEMENT_OEM ) { aParams.devInfo.deviceInfo().setOEM( readString() ); } else if( name == SYNCML_ELEMENT_FWVERSION ) { aParams.devInfo.deviceInfo().setFirmwareVersion( readString() ); } else if( name == SYNCML_ELEMENT_SWVERSION ) { aParams.devInfo.deviceInfo().setSoftwareVersion( readString() ); } else if( name == SYNCML_ELEMENT_HWVERSION ) { aParams.devInfo.deviceInfo().setHardwareVersion( readString() ); } else if( name == SYNCML_ELEMENT_DEVID ) { aParams.devInfo.deviceInfo().setDeviceID( readString() ); } else if( name == SYNCML_ELEMENT_DEVTYPE ) { aParams.devInfo.deviceInfo().setDeviceType( readString() ); } else if( name == SYNCML_ELEMENT_UTC ) { aParams.devInfo.setSupportsUTC( true ); } else if( name == SYNCML_ELEMENT_SUPPORTLARGEOBJS ) { aParams.devInfo.setSupportsLargeObjs( true ); } else if( name == SYNCML_ELEMENT_SUPPORTNUMBEROFCHANGES ) { aParams.devInfo.setSupportsNumberOfChanges( true ); } else if( name == SYNCML_ELEMENT_DATASTORE ) { Datastore newDatastore; readDataStore( newDatastore, dtd ); aParams.devInfo.datastores().append( newDatastore ); } else if( name == SYNCML_ELEMENT_CTCAP ) { // CTCap element resides under DevInf only 1.1, in 1.2 it's under // DataStore if( dtd == SYNCML_DTD_VERSION_1_1 ) { readCTCap11( aParams.devInfo.datastores() ); } else { qCCritical(lcSyncML) << SYNCML_ELEMENT_CTCAP << "under DevInf allowed only for DS 1.1"; iError = PARSER_ERROR_INVALID_DATA; } } else{ qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readDataStore( Datastore& aDatastore, const QString& aDTD ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_DATASTORE ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_SOURCEREF ) { QString URI = readString(); qCDebug(lcSyncML) << "URI of the new datastore instance:" << URI; aDatastore.setSourceURI( URI ); } else if( name == SYNCML_ELEMENT_RX_PREF ) { ContentFormat rxPref; readContentFormat( rxPref, SYNCML_ELEMENT_RX_PREF ); aDatastore.formatInfo().setPreferredRx( rxPref ); } else if( name == SYNCML_ELEMENT_RX ) { ContentFormat rx; readContentFormat( rx, SYNCML_ELEMENT_RX ); aDatastore.formatInfo().rx().append( rx ); } else if( name == SYNCML_ELEMENT_TX_PREF ) { ContentFormat txPref; readContentFormat( txPref, SYNCML_ELEMENT_TX_PREF ); aDatastore.formatInfo().setPreferredTx( txPref ); } else if( name == SYNCML_ELEMENT_TX ) { ContentFormat tx; readContentFormat( tx, SYNCML_ELEMENT_TX ); aDatastore.formatInfo().tx().append( tx ); } else if( name == SYNCML_ELEMENT_SYNCCAP ) { readSyncCaps( aDatastore ); } else if( name == SYNCML_ELEMENT_CTCAP ) { readCTCap12( aDatastore ); } else if( name == SYNCML_ELEMENT_SUPPORTHIERARCHICALSYNC ) { if( aDTD == SYNCML_DTD_VERSION_1_2 ) { aDatastore.setSupportsHierarchicalSync( true ); } else { qCCritical(lcSyncML) << SYNCML_ELEMENT_SUPPORTHIERARCHICALSYNC << "under DevInf allowed only for DS 1.2"; iError = PARSER_ERROR_INVALID_DATA; } } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readContentFormat( ContentFormat& aFormat, const QString& aEndElement ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == aEndElement ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_CTTYPE ) { aFormat.iType = readString(); } else if( name == SYNCML_ELEMENT_VERCT ) { aFormat.iVersion = readString(); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readSyncCaps( Datastore& aDatastore ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_SYNCCAP ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_SYNCTYPE ) { int syncType = readInt(); aDatastore.syncCaps().append( static_cast( syncType ) ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readCTCap11( QList& aDataStores ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QList caps; CTCap* currentCap = 0; while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_CTCAP ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_CTTYPE ) { QString type = readString(); currentCap = 0; for( int i = 0; i < caps.count(); ++i ) { if( caps[i].getFormat().iType == type ) { currentCap = &caps[i]; break; } } if( !currentCap ) { qCDebug(lcSyncML) << "Creating new CTCap instance with type" << type; CTCap newCap; ContentFormat format; format.iType = type; newCap.setFormat(format); caps.append(newCap); currentCap = &caps.last(); } } else { if( !currentCap ) { qCCritical(lcSyncML) << "Cannot process" << name <<"as no" << SYNCML_ELEMENT_CTTYPE << "was found!"; iError = PARSER_ERROR_INVALID_DATA; } else if( name == SYNCML_ELEMENT_PROPNAME ) { CTCapProperty newProp; newProp.iName = readString(); currentCap->properties().append( newProp ); } else if( name == SYNCML_ELEMENT_VALENUM ) { QString val = readString(); currentCap->properties().last().iValues.append( val ); } else if( name == SYNCML_ELEMENT_DATATYPE ) { QString type = readString(); currentCap->properties().last().iType = type; } else if( name == SYNCML_ELEMENT_SIZE ) { int size = readInt(); currentCap->properties().last().iSize = size; } else if( name == SYNCML_ELEMENT_DISPLAYNAME ) { QString displayName = readString(); currentCap->properties().last().iDisplayName = displayName; } else if( name == SYNCML_ELEMENT_PARAMNAME ) { // In SyncML 1.1, parameter names (for example TYPE) are not conveyed, instead // parameter values (for example WORK). So we must create an anonymous parameter // that includes all the allowed parameter values QString paramName = readString(); if( currentCap->properties().last().iParameters.isEmpty() ) { CTCapParameter newParam; newParam.iValues.append( paramName ); currentCap->properties().last().iParameters.append( newParam ); } else { currentCap->properties().last().iParameters.last().iValues.append( paramName ); } \ } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } // Sweep through declared datastores, check the content formats they are interested, and add // parsed CTCaps if a datastore is interested for( int i = 0; i < caps.count(); ++i ) { for( int a = 0; a < aDataStores.count(); ++a ) { QList interestedFormats; const StorageContentFormatInfo& formatInfo = aDataStores[a].formatInfo(); interestedFormats.append( formatInfo.getPreferredRx() ); interestedFormats.append( formatInfo.rx()); interestedFormats.append( formatInfo.getPreferredTx() ); interestedFormats.append( formatInfo.tx()); for( int b = 0; b < interestedFormats.count(); ++b ) { if( interestedFormats[b].iType == caps[i].getFormat().iType ) { qCDebug(lcSyncML) << "Datastore" << aDataStores[a].getSourceURI() << "is interested in CTType" << caps[i].getFormat().iType; aDataStores[a].ctCaps().append( caps[i] ); break; } } } } } void SyncMLMessageParser::readCTCap12( Datastore& aDatastore ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); CTCap cap; while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_CTCAP ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_CTTYPE ) { ContentFormat format = cap.getFormat(); format.iType = readString(); cap.setFormat( format ); } else if( name == SYNCML_ELEMENT_VERCT ) { ContentFormat format = cap.getFormat(); format.iVersion = readString(); cap.setFormat( format ); } else if( name == SYNCML_ELEMENT_PROPERTY ) { CTCapProperty newProperty; readCTCap12Property( newProperty ); cap.properties().append( newProperty ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } aDatastore.ctCaps().append( cap ); } void SyncMLMessageParser::readCTCap12Property( CTCapProperty& aProperty ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_PROPERTY ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_PROPNAME ) { aProperty.iName = readString(); } else if( name == SYNCML_ELEMENT_DATATYPE ) { aProperty.iType = readString(); } else if( name == SYNCML_ELEMENT_MAXOCCUR ) { aProperty.iMaxOccur = readInt(); } else if( name == SYNCML_ELEMENT_MAXSIZE ) { aProperty.iSize = readInt(); } else if( name == SYNCML_ELEMENT_NOTRUNCATE ) { aProperty.iNoTruncate = true; } else if( name == SYNCML_ELEMENT_DISPLAYNAME ) { aProperty.iDisplayName = readString(); } else if( name == SYNCML_ELEMENT_VALENUM ) { aProperty.iValues.append( readString() ); } else if( name == SYNCML_ELEMENT_PROPPARAM ) { CTCapParameter newParam; readCTCap12Parameter( newParam ); aProperty.iParameters.append( newParam ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readCTCap12Parameter( CTCapParameter& aParameter ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_PROPPARAM ) { break; } if( iReader.isStartElement() ) { if( name == SYNCML_ELEMENT_PARAMNAME ) { aParameter.iName = readString(); } else if( name == SYNCML_ELEMENT_DATATYPE ) { aParameter.iType = readString(); } else if( name == SYNCML_ELEMENT_DISPLAYNAME ) { aParameter.iDisplayName = readString(); } else if( name == SYNCML_ELEMENT_VALENUM ) { aParameter.iValues.append( readString() ); } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in DEVINF:NOT HANDLED BY PARSER" << name; } } } } void SyncMLMessageParser::readItem( ItemParams& aParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && name == SYNCML_ELEMENT_ITEM ) { break; } if( iReader.isStartElement() ) { if (name == SYNCML_ELEMENT_META) { readMeta( aParams.meta ); } else if (name == SYNCML_ELEMENT_TARGET) { aParams.target = readURI(); } else if (name == SYNCML_ELEMENT_SOURCE) { aParams.source = readURI(); } else if( name == SYNCML_ELEMENT_TARGETPARENT ) { aParams.targetParent = readURI(); } else if( name == SYNCML_ELEMENT_SOURCEPARENT ) { aParams.sourceParent = readURI(); } else if (name == SYNCML_ELEMENT_DATA) { aParams.data = readMixed(); } else if (name == SYNCML_ELEMENT_MOREDATA) { aParams.moreData = true; } else { qCWarning(lcSyncML) << "UNKNOWN TOKEN TYPE in ITEM:NOT HANDLED BY PARSER" << name; } } } } QString SyncMLMessageParser::readURI() { FUNCTION_CALL_TRACE(lcSyncMLTrace); QString uri; while( shouldContinue() ) { iReader.readNext(); QStringRef name = iReader.name(); if( iReader.isEndElement() && ( name == SYNCML_ELEMENT_TARGET || name == SYNCML_ELEMENT_SOURCE || name == SYNCML_ELEMENT_TARGETPARENT || name == SYNCML_ELEMENT_SOURCEPARENT ) ){ break; } if( iReader.isStartElement() && name == SYNCML_ELEMENT_LOCURI ) { uri = readString(); continue; } } return uri; } int SyncMLMessageParser::readInt() { iReader.readNext(); return iReader.text().toString().toInt(); } QString SyncMLMessageParser::readString() { QString string; while( shouldContinue() ) { iReader.readNext(); if( iReader.isCharacters() ) { string.append( iReader.text().toString() ); } else if( iReader.isEndElement() ) { break; } } return string; } QString SyncMLMessageParser::readMixed() { FUNCTION_CALL_TRACE(lcSyncMLTrace); QString text; QString xml; while( shouldContinue() ) { iReader.readNext(); if( iReader.isStartElement() ) { QString elementName = iReader.name().toString(); QByteArray buffer; QXmlStreamWriter writer( &buffer ); writer.setAutoFormatting( false ); while( !(iReader.isEndElement() && iReader.name() == elementName ) ) { writer.writeCurrentToken( iReader ); iReader.readNext(); } writer.writeCurrentToken( iReader ); xml = QString::fromUtf8( buffer.constData() ); break; } else if( iReader.isCharacters() ) { text.append( iReader.text().toString() ); } else if( iReader.isEndElement() ) { break; } } if( xml.isEmpty() ) { qCDebug(lcSyncML) << "Text was found:" << text.size() << "bytes"; return text; } else { qCDebug(lcSyncML) << "XML data was found:" << xml.size() << "bytes"; return xml; } } bool SyncMLMessageParser::shouldContinue() const { if( iError == PARSER_ERROR_LAST && !iReader.atEnd() ) { return true; } else { return false; } } void SyncMLMessageParser::initMaps() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // for debugging alert codes iAlertCodeMap[100] = "Alert for DISPLAY"; // Alert codes used at the sync init iAlertCodeMap[200] = "Alert for TWO_WAY_SYNC"; iAlertCodeMap[201] = "Alert for SLOW_SYNC"; iAlertCodeMap[202] = "Alert for ONE_WAY_FROM_CLIENT_SYNC"; iAlertCodeMap[203] = "Alert for REFRESH_FROM_CLIENT_SYNC"; iAlertCodeMap[204] = "Alert for ONE_WAY_FROM_SERVER_SYNC"; iAlertCodeMap[205] = "Alert for REFRESH_FROM_SERVER_SYNC"; // Alert codes used by the server when alerting the sync iAlertCodeMap[206] = "Alert for TWO_WAY_BY_SERVER"; iAlertCodeMap[207] = "Alert for ONE_WAY_FROM_CLIENT_BY_SERVER"; iAlertCodeMap[208] = "Alert for REFRESH_FROM_CLIENT_BY_SERVER"; iAlertCodeMap[209] = "Alert for ONE_WAY_FROM_SERVER_BY_SERVER"; iAlertCodeMap[210] = "Alert for REFRESH_FROM_SERVER_BY_SERVER"; iAlertCodeMap[221] = "Alert for RESULT_ALERT"; iAlertCodeMap[222] = "Alert for NEXT_MESSAGE"; iAlertCodeMap[223] = "Alert for NO_END_OF_DATA"; iAlertCodeMap[224] = "Alert for ALERT_SUSPEND"; iAlertCodeMap[225] = "Alert for ALERT_RESUME"; iAlertCodeMap[206] = "Alert for TWO_WAY_BY_SERVER"; iStatusCodeMap[101] = "Status:IN_PROGRESS"; // Successful 2xx iStatusCodeMap[200] = "Status:SUCCESS"; iStatusCodeMap[201] = "Status:ITEM_ADDED"; iStatusCodeMap[202] = "Status:ACCEPTED_FOR_PROCESSING"; iStatusCodeMap[203] = "Status:NONAUTHORITATIVE_RESPONSE"; iStatusCodeMap[204] = "Status:NO_CONTENT"; iStatusCodeMap[205] = "Status:RESET_CONTENT"; iStatusCodeMap[206] = "Status:PARTIAL_CONTENT"; iStatusCodeMap[207] = "Status:RESOLVED_WITH_MERGE"; iStatusCodeMap[208] = "Status:RESOLVED_CLIENT_WINNING"; iStatusCodeMap[209] = "Status:RESOLVED_WITH_DUPLICATE"; iStatusCodeMap[210] = "Status:DELETE_WITHOUT_ARCHIVE"; iStatusCodeMap[211] = "Status:ITEM_NOT_DELETED"; iStatusCodeMap[212] = "Status:AUTH_ACCEPTED"; iStatusCodeMap[213] = "Status:CHUNKED_ITEM_ACCEPTED"; iStatusCodeMap[214] = "Status:CANCELLED"; iStatusCodeMap[215] = "Status:NOT_EXECUTED"; iStatusCodeMap[216] = "Status:ATOMIC_ROLLBACK_OK"; // Redirection 3xx iStatusCodeMap[300] = "Status:MULTIPLE_CHOICES"; iStatusCodeMap[301] = "Status:MOVED_PERMANENTLY"; iStatusCodeMap[302] = "Status:FOUND"; iStatusCodeMap[303] = "Status:SEE_OTHER"; iStatusCodeMap[304] = "Status:NOT_MODIFIED"; iStatusCodeMap[305] = "Status:USE_PROXY"; // Originator exceptions 4xx iStatusCodeMap[400] = "Status:BAD_REQUEST"; iStatusCodeMap[401] = "Status:INVALID_CRED"; iStatusCodeMap[402] = "Status:PAYMENT_NEEDED"; iStatusCodeMap[403] = "Status:FORBIDDEN"; iStatusCodeMap[404] = "Status:NOT_FOUND"; iStatusCodeMap[405] = "Status:COMMAND_NOT_ALLOWED"; iStatusCodeMap[406] = "Status:NOT_SUPPORTED"; iStatusCodeMap[407] = "Status:MISSING_CRED"; iStatusCodeMap[408] = "Status:REQUEST_TIMEOUT"; iStatusCodeMap[409] = "Status:CONFLICT"; iStatusCodeMap[410] = "Status:GONE"; iStatusCodeMap[411] = "Status:SIZE_REQUIRED"; iStatusCodeMap[412] = "Status:INCOMPLETE_COMMAND"; iStatusCodeMap[413] = "Status:REQUEST_ENTITY_TOO_LARGE"; iStatusCodeMap[414] = "Status:URI_TOO_LONG"; iStatusCodeMap[415] = "Status:UNSUPPORTED_FORMAT"; iStatusCodeMap[416] = "Status:REQUEST_SIZE_TOO_BIG"; iStatusCodeMap[417] = "Status:RETRY_LATER"; iStatusCodeMap[418] = "Status:ALREADY_EXISTS"; iStatusCodeMap[419] = "Status:RESOLVED_WITH_SERVER_DATA"; iStatusCodeMap[420] = "Status:DEVICE_FULL"; iStatusCodeMap[421] = "Status:UNKNOWN_SEARCH_GRAMMAR"; iStatusCodeMap[422] = "Status:BAD_CGI_SCRIPT"; iStatusCodeMap[423] = "Status:SOFTDELETE_CONFLICT"; iStatusCodeMap[424] = "Status:SIZE_MISMATCH"; iStatusCodeMap[425] = "Status:PERMISSION_DENIED"; iStatusCodeMap[426] = "Status:PARTIAL_ITEM_NOT_ACCEPTED"; iStatusCodeMap[427] = "Status:ITEM_NOT_EMPTY"; iStatusCodeMap[428] = "Status:MOVE_FAILED"; // Recipient exception 5xx iStatusCodeMap[500] = "Status:COMMAND_FAILED"; iStatusCodeMap[501] = "Status:NOT_IMPLEMENTED"; iStatusCodeMap[502] = "Status:BAD_GATEWAY"; iStatusCodeMap[503] = "Status:SERVICE_UNAVAILABLE"; iStatusCodeMap[504] = "Status:GATEWAY_TIMEOUT"; iStatusCodeMap[505] = "Status:UNSUPPORTED_DTD_VERSION"; iStatusCodeMap[506] = "Status:PROCESSING_ERROR"; iStatusCodeMap[507] = "Status:ATOMIC_FAILED"; iStatusCodeMap[508] = "Status:REFRESH_REQUIRED"; iStatusCodeMap[510] = "Status:DATA_STORE_FAILURE"; iStatusCodeMap[511] = "Status:SERVER_FAILURE"; iStatusCodeMap[512] = "Status:SYNC_FAILED"; iStatusCodeMap[513] = "Status:UNSUPPORTED_PROTOCOL_VERSION"; iStatusCodeMap[514] = "Status:OPERATION_CANCELLED"; iStatusCodeMap[516] = "Status:ATOMIC_ROLLBACK_FAILED"; iStatusCodeMap[517] = "Status:ATOMIC_RESPONSE_TOO_LARGE"; } buteo-syncml-0.5.15/src/SyncMLMessageParser.h000066400000000000000000000126451433763642500210370ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMESSAGEPARSER_H #define SYNCMLMESSAGEPARSER_H #include #include #include "Fragments.h" class SyncMLMessageParserTest; namespace DataSync { /*! \brief Enumeration describing possible parser errors * */ enum ParserError { PARSER_ERROR_UNEXPECTED_DATA, /*!< Parser encountered unexpected data*/ PARSER_ERROR_INCOMPLETE_DATA, /*!< Parser encountered incomplete data*/ PARSER_ERROR_INVALID_DATA, /*!< Parser encountered invalid data*/ PARSER_ERROR_INVALID_CHARS, /*!< Parser encountered invalid XML characters in data */ PARSER_ERROR_LAST /*!< Placeholder for last parser error*/ }; /*! \brief Constructs SyncML Commands into usable data structures. * * This Class reads the XML data from the incoming stream and builds * individual structs for the SyncML commands received in the SyncML * Message. */ class SyncMLMessageParser : public QObject { Q_OBJECT public: /*! \brief Constructor */ SyncMLMessageParser(); /*! \brief Destructor */ virtual ~SyncMLMessageParser(); public: /*! \brief Retrieves the fragments of the last parsing operation * * Ownership of the fragments is transferred. * @return */ QList takeFragments(); public slots: /*! \brief Parse incoming data * * @param aDevice QIODevice from which to retrieve data * @param aIsNewPacket To indicate if the packet is a newly received or a * purged one */ void parseResponse( QIODevice *aDevice, bool aIsNewPacket ); signals: /*! \brief Emitted when parsing of a message has been completed * * @param aLastMessageInPackage True if the parsed message contained * Final element */ void parsingComplete( bool aLastMessageInPackage ); /*! \brief Emitted when error occurred during parsing of a message * * @param aEvent Occurred error */ void parsingError( DataSync::ParserError aEvent ); private: void startParsing(); void readHeader(); void readBody(); void readStatus(); void readSync(); void readPut(); void readResults(); void readMap(); void readMapItem( MapItemParams& aParams ); bool readCommand( const QStringRef& aName, CommandParams& aCommand ); void readLeafCommand( CommandParams& aParams, const QString& aCommand ); void readContainerCommand( CommandParams& aParams, const QString& aCommand ); void readChal( ChalParams& aParams ); void readCred( CredParams& aParams ); void readMeta( MetaParams& aParams ); void readItem( ItemParams& aParams ); void readAnchor( AnchorParams& aParams ); void readDevInfItem( DevInfItemParams& aParams ); void readDevInf( DevInfItemParams& aParams ); void readDataStore( Datastore& aDatastore, const QString& aDTD ); void readContentFormat( ContentFormat& aFormat, const QString& aEndElement ); void readSyncCaps( Datastore& aDatastore ); void readCTCap11( QList& aDatastores ); void readCTCap12( Datastore& aDatastore ); void readCTCap12Property( CTCapProperty& aProperty ); void readCTCap12Parameter( CTCapParameter& aParameter ); QString readURI(); int readInt(); QString readString(); QString readMixed(); bool shouldContinue() const; void initMaps(); QXmlStreamReader iReader; QList iFragments; bool iLastMessageInPackage; ParserError iError; QHash iAlertCodeMap; QHash iStatusCodeMap; bool iSyncHdrFound; bool iSyncBodyFound; bool iIsNewPacket; friend class ::SyncMLMessageParserTest; }; } Q_DECLARE_METATYPE(DataSync::ParserError); #endif // SYNCMLMESSAGEPARSER_H buteo-syncml-0.5.15/src/SyncMode.cpp000066400000000000000000000153531433763642500172630ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMode.h" #include "datatypes.h" using namespace DataSync; SyncMode::SyncMode( SyncDirection aDirection, SyncInitiator aInitiator, SyncType aType ) : iDirection( aDirection ), iInitiator( aInitiator ), iType( aType ), iValid( true ) { } SyncMode::SyncMode( qint32 aSyncMLCode ) : iDirection(DIRECTION_TWO_WAY), iInitiator(INIT_CLIENT), iType(TYPE_FAST) { if( aSyncMLCode < TWO_WAY_SYNC || aSyncMLCode > REFRESH_FROM_SERVER_BY_SERVER ) { iValid = false; } else { iValid = true; switch( aSyncMLCode ) { case TWO_WAY_SYNC: { iDirection = DIRECTION_TWO_WAY; iInitiator = INIT_CLIENT; iType = TYPE_FAST; break; } case SLOW_SYNC: { iDirection = DIRECTION_TWO_WAY; iInitiator = INIT_CLIENT; iType = TYPE_SLOW; break; } case ONE_WAY_FROM_CLIENT_SYNC: { iDirection = DIRECTION_FROM_CLIENT; iInitiator = INIT_CLIENT; iType = TYPE_FAST; break; } case REFRESH_FROM_CLIENT_SYNC: { iDirection = DIRECTION_FROM_CLIENT; iInitiator = INIT_CLIENT; iType = TYPE_REFRESH; break; } case ONE_WAY_FROM_SERVER_SYNC: { iDirection = DIRECTION_FROM_SERVER; iInitiator = INIT_CLIENT; iType = TYPE_FAST; break; } case REFRESH_FROM_SERVER_SYNC: { iDirection = DIRECTION_FROM_SERVER; iInitiator = INIT_CLIENT; iType = TYPE_REFRESH; break; } case TWO_WAY_BY_SERVER: { iDirection = DIRECTION_TWO_WAY; iInitiator = INIT_SERVER; iType = TYPE_FAST; break; } case ONE_WAY_FROM_CLIENT_BY_SERVER: { iDirection = DIRECTION_FROM_CLIENT; iInitiator = INIT_SERVER; iType = TYPE_FAST; break; } case REFRESH_FROM_CLIENT_BY_SERVER: { iDirection = DIRECTION_FROM_CLIENT; iInitiator = INIT_SERVER; iType = TYPE_REFRESH; break; } case ONE_WAY_FROM_SERVER_BY_SERVER: { iDirection = DIRECTION_FROM_SERVER; iInitiator = INIT_SERVER; iType = TYPE_FAST; break; } case REFRESH_FROM_SERVER_BY_SERVER: { iDirection = DIRECTION_FROM_SERVER; iInitiator = INIT_SERVER; iType = TYPE_REFRESH; break; } default: { iValid = false; break; } } } } SyncMode::~SyncMode() { } bool SyncMode::isValid() const { return iValid; } SyncDirection SyncMode::syncDirection() const { return iDirection; } SyncInitiator SyncMode::syncInitiator() const { return iInitiator; } SyncType SyncMode::syncType() const { return iType; } void SyncMode::toSlowSync() { iType = TYPE_SLOW; } void SyncMode::setRefresh() { iType = TYPE_REFRESH; } void SyncMode::toClientInitiated() { iInitiator = INIT_CLIENT; } qint32 SyncMode::toSyncMLCode() const { qint32 code = -1; if( iDirection == DIRECTION_TWO_WAY ) { if( iInitiator == INIT_CLIENT ) { if( iType == TYPE_FAST ) { code = TWO_WAY_SYNC; } else if( iType == TYPE_SLOW ) { code = SLOW_SYNC; } } else if( iInitiator == INIT_SERVER ) { code = TWO_WAY_BY_SERVER; } } else if( iDirection == DIRECTION_FROM_CLIENT ) { if( iInitiator == INIT_CLIENT ) { if( iType == TYPE_REFRESH ) { code = REFRESH_FROM_CLIENT_SYNC; } else { code = ONE_WAY_FROM_CLIENT_SYNC; } } else if( iInitiator == INIT_SERVER ) { if( iType == TYPE_REFRESH ) { code = REFRESH_FROM_CLIENT_BY_SERVER; } else { code = ONE_WAY_FROM_CLIENT_BY_SERVER; } } } else if( iDirection == DIRECTION_FROM_SERVER ) { if( iInitiator == INIT_CLIENT ) { if( iType == TYPE_REFRESH ) { code = REFRESH_FROM_SERVER_SYNC; } else { code = ONE_WAY_FROM_SERVER_SYNC; } } else if( iInitiator == INIT_SERVER ) { if( iType == TYPE_REFRESH ) { code = REFRESH_FROM_SERVER_BY_SERVER; } else { code = ONE_WAY_FROM_SERVER_BY_SERVER; } } } return code; } buteo-syncml-0.5.15/src/SyncMode.h000066400000000000000000000072161433763642500167270ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMODE_H #define SYNCMODE_H #include "SyncAgentConsts.h" #include namespace DataSync { class SyncModeTest; /*! \brief Utility class for handling SyncML Alert codes related to sync modes * */ class SyncMode { public: /*! \brief Construct using direction and initiator * * By default, direction is two-way, initiator is client and type if fast * sync * * @param aDirection Direction of the sync * @param aInitiator Initiator of the sync * @param aType Type of the sync */ SyncMode( SyncDirection aDirection = DIRECTION_TWO_WAY, SyncInitiator aInitiator = INIT_CLIENT, SyncType aType = TYPE_FAST ); /*! \brief Construct using SyncML Alert code * * @param aSyncMLCode SyncML Alert code */ explicit SyncMode( qint32 aSyncMLCode ); /*! \brief Destructor * */ ~SyncMode(); /*! \brief Returns true if class instance holds a valid SyncML Alert code * * If false is returned, functioning of other functions is undefined * * @return */ bool isValid() const; /*! \brief Return the direction of the sync * * @return */ SyncDirection syncDirection() const; /*! \brief Return the initiator of the sync * * @return */ SyncInitiator syncInitiator() const; /*! \brief Return the type of the sync * * @return */ SyncType syncType() const; /*! \brief Turn sync mode to slow sync * */ void toSlowSync(); /*! \brief Turn sync mode to refresh sync * */ void setRefresh(); /*! \brief Turn sync mode to client initiated sync * */ void toClientInitiated(); /*! \brief Output SyncML Alert code that matches presented sync mode * * @return */ qint32 toSyncMLCode() const; protected: private: SyncDirection iDirection; SyncInitiator iInitiator; SyncType iType; bool iValid; friend class SyncModeTest; }; } #endif // SYNCMODE_H buteo-syncml-0.5.15/src/SyncResults.cpp000066400000000000000000000076171433763642500200440ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncResults.h" #include "SyncMLLogging.h" using namespace DataSync; SyncResults::SyncResults() : iState( NOT_PREPARED ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } DataSync::SyncResults::~SyncResults() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } void SyncResults::reset() { FUNCTION_CALL_TRACE(lcSyncMLTrace); iResults.clear(); } SyncState SyncResults::getState() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); return iState; } void SyncResults::setState( const SyncState& aState ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iState = aState; } QString SyncResults::getErrorString() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); return iErrorString; } void SyncResults::setErrorString( const QString& aErrorString ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iErrorString = aErrorString; } void SyncResults::setRemoteDeviceId( const QString& aDeviceId ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iRemoteId = aDeviceId; } QString SyncResults::getRemoteDeviceId( ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); return iRemoteId; } const QMap* SyncResults::getDatabaseResults() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); return &iResults; } void SyncResults::addProcessedItem( DataSync::ModificationType aModificationType, DataSync::ModifiedDatabase aModifiedDatabase, const QString& aDatabase ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); DatabaseResults& results = iResults[aDatabase]; if( aModifiedDatabase == MOD_LOCAL_DATABASE ) { if( aModificationType == MOD_ITEM_ADDED ) { ++results.iLocalItemsAdded; } else if( aModificationType == MOD_ITEM_MODIFIED ) { ++results.iLocalItemsModified; } else if( aModificationType == MOD_ITEM_DELETED ) { ++results.iLocalItemsDeleted; } } else if( aModifiedDatabase == MOD_REMOTE_DATABASE ) { if( aModificationType == MOD_ITEM_ADDED ) { ++results.iRemoteItemsAdded; } else if( aModificationType == MOD_ITEM_MODIFIED ) { ++results.iRemoteItemsModified; } else if( aModificationType == MOD_ITEM_DELETED ) { ++results.iRemoteItemsDeleted; } } } buteo-syncml-0.5.15/src/SyncResults.h000066400000000000000000000112411433763642500174750ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCRESULTS_H #define SYNCRESULTS_H #include "SyncAgentConsts.h" #include #include namespace DataSync { /*! \brief Describes details of items transferred between single databases * */ struct DatabaseResults { int iLocalItemsAdded; /*!* getDatabaseResults() const; /*! \brief Adds a processed item to database results * * @param aModificationType Type of modification made to the item (addition, modification or delete) * @param aModifiedDatabase Database that was modified (local or remote) * @param aDatabase Identifier of the database that was modified */ void addProcessedItem( DataSync::ModificationType aModificationType, DataSync::ModifiedDatabase aModifiedDatabase, const QString& aDatabase ); private: SyncState iState; QString iErrorString; QString iRemoteId; QMap iResults; }; } #endif // SYNCRESULTS_H buteo-syncml-0.5.15/src/SyncTarget.cpp000066400000000000000000000214051433763642500176200ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncTarget.h" #include "ChangeLog.h" #include "StoragePlugin.h" #include "SyncItem.h" #include "DatabaseHandler.h" #include "SyncMLLogging.h" using namespace DataSync; SyncTarget::SyncTarget( ChangeLog* aChangeLog, StoragePlugin* aPlugin, const SyncMode& aSyncMode, const QString& aLocalNextAnchor ) : iChangeLog( aChangeLog ), iPlugin( aPlugin ), iSyncMode( aSyncMode ), iLocalNextAnchor( aLocalNextAnchor ), iReverted( false ), iLocalChangesDiscovered( false ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } SyncTarget::~SyncTarget() { FUNCTION_CALL_TRACE(lcSyncMLTrace); delete iChangeLog; iChangeLog = NULL; } QString SyncTarget::getSourceDatabase() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QString sourceDb; if (iPlugin != NULL) { sourceDb = iPlugin->getSourceURI(); } return sourceDb; } void SyncTarget::setTargetDatabase( const QString& aTargetDatabase ) { iTargetDatabase = aTargetDatabase; } QString SyncTarget::getTargetDatabase() const { return iTargetDatabase; } QString SyncTarget::getLocalLastAnchor() const { return iChangeLog->getLastLocalAnchor(); } QString SyncTarget::getLocalNextAnchor() const { return iLocalNextAnchor; } QString SyncTarget::getRemoteLastAnchor() const { return iChangeLog->getLastRemoteAnchor(); } QString SyncTarget::getRemoteNextAnchor() const { return iRemoteNextAnchor; } void SyncTarget::setRemoteNextAnchor( const QString& aRemoteNextAnchor ) { iRemoteNextAnchor = aRemoteNextAnchor; } SyncMode* SyncTarget::getSyncMode() { return &iSyncMode; } const SyncMode* SyncTarget::getSyncMode() const { return &iSyncMode; } void SyncTarget::setSyncMode( const SyncMode& aSyncMode ) { iSyncMode = aSyncMode; } void SyncTarget::revertSyncMode() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iSyncMode.syncType() == TYPE_FAST ) { iSyncMode.toSlowSync(); iReverted = true; } } bool SyncTarget::setRefreshFromClient() { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool refreshSet = false; if( iSyncMode.syncDirection() == DIRECTION_FROM_CLIENT && iSyncMode.syncInitiator() == INIT_CLIENT ) { iSyncMode.setRefresh(); refreshSet = true; } return refreshSet; } bool SyncTarget::reverted() const { return iReverted; } bool SyncTarget::discoverLocalChanges( const Role& aRole ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iLocalChangesDiscovered ) { return true; } bool success = false; iLocalChanges.added.clear(); iLocalChanges.modified.clear(); iLocalChanges.removed.clear(); qCDebug(lcSyncML) << "Analyzing local changes"; qCDebug(lcSyncML) << "Sync Type getting Local Changes " << iSyncMode.toSyncMLCode(); SyncDirection direction = iSyncMode.syncDirection(); if( direction == DIRECTION_TWO_WAY || ( aRole == ROLE_CLIENT && direction == DIRECTION_FROM_CLIENT ) || ( aRole == ROLE_SERVER && direction == DIRECTION_FROM_SERVER ) ) { if( iSyncMode.syncType() == TYPE_SLOW ) { qCDebug(lcSyncML) << "Slow sync mode"; if (iPlugin != NULL) { success = iPlugin->getAll( iLocalChanges.added ); } } else if( iSyncMode.syncType() == TYPE_REFRESH ) { qCDebug(lcSyncML) << "Refresh sync mode"; // As server, we don't initiate a refresh sync if( aRole == ROLE_CLIENT && direction == DIRECTION_FROM_CLIENT ) { qCDebug(lcSyncML) << "We need to send all changes as a client"; if (iPlugin != NULL) { success = iPlugin->getAll( iLocalChanges.added ); } } } else { qCDebug(lcSyncML) << "Fast sync mode"; QDateTime time = iChangeLog->getLastSyncTime(); qCDebug(lcSyncML) << "Getting modifications after: " << time; if (iPlugin != NULL) { if( time.toString().isEmpty() ) { qCDebug(lcSyncML) << "Getting All modifications for a 1st time fast sync req"; success = iPlugin->getAll( iLocalChanges.added ); } else { success = iPlugin->getModifications( iLocalChanges.added, iLocalChanges.modified, iLocalChanges.removed, time ); } } } } else { qCDebug(lcSyncML) << "Local changes not needed in current sync mode"; success = true; } qCDebug(lcSyncML) << "Number of items added: " << iLocalChanges.added.count(); qCDebug(lcSyncML) << "Number of items modified: " << iLocalChanges.modified.count(); qCDebug(lcSyncML) << "Number of items deleted: " << iLocalChanges.removed.count(); iLocalChangesDiscovered = success; return success; } const LocalChanges* SyncTarget::getLocalChanges() const { return &iLocalChanges; } LocalChanges* SyncTarget::getLocalChanges() { return &iLocalChanges; } StoragePlugin* SyncTarget::getPlugin() const { return iPlugin; } void SyncTarget::addUIDMapping( const UIDMapping& aMapping ) { iUIDMappings.append( aMapping ); } void SyncTarget::removeUIDMapping( const SyncItemKey& aLocalKey ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); for( int i = 0; i < iUIDMappings.count(); ++i ) { if( iUIDMappings[i].iLocalUID == aLocalKey ) { iUIDMappings.removeAt( i ); break; } } } SyncItemKey SyncTarget::mapToLocalUID( const QString& aRemoteKey ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncItemKey localUID; for( int i = 0; i < iUIDMappings.count(); ++i ) { if( iUIDMappings[i].iRemoteUID == aRemoteKey ) { localUID = iUIDMappings[i].iLocalUID; break; } } if( localUID.isEmpty() ) { qCDebug(lcSyncML) << "Warning: no existing mapping found for remote key" << aRemoteKey; } return localUID; } QString SyncTarget::mapToRemoteUID( const SyncItemKey& aLocalUID ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QString remoteUID; for( int i = 0; i < iUIDMappings.count(); ++i ) { if( iUIDMappings[i].iLocalUID == aLocalUID ) { remoteUID = iUIDMappings[i].iRemoteUID; break; } } return remoteUID; } void SyncTarget::loadUIDMappings() { iUIDMappings = iChangeLog->getMaps(); } const QList& SyncTarget::getUIDMappings() const { return iUIDMappings; } void SyncTarget::clearUIDMappings() { iUIDMappings.clear(); } void SyncTarget::saveSession( DatabaseHandler& aDbHandler, const QDateTime& aSyncEndTime ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iChangeLog->setLastLocalAnchor( iLocalNextAnchor ); iChangeLog->setLastRemoteAnchor( iRemoteNextAnchor ); iChangeLog->setLastSyncTime( aSyncEndTime ); iChangeLog->setMaps( iUIDMappings ); if( !iChangeLog->save( aDbHandler.getDbHandle() ) ) { qCWarning(lcSyncML) << "Could not save information to persistent storage!"; } } buteo-syncml-0.5.15/src/SyncTarget.h000066400000000000000000000161511433763642500172670ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCTARGET_H #define SYNCTARGET_H #include "SyncMode.h" #include "SyncAgentConsts.h" #include "SyncMLGlobals.h" #include "LocalChanges.h" #include "datatypes.h" namespace DataSync { class StoragePlugin; class ChangeLog; class DatabaseHandler; class SyncTargetTest; /*! \brief Sync target represent sync of a single local database with a single * remote database */ class SyncTarget { public: /*! \brief Constructor * * @param aChangeLog Change log to associate with this sync target. SyncTarget takes ownership. * @param aPlugin Source storage plugin * @param aSyncMode Sync mode to use * @param aLocalNextAnchor Next anchor to use */ SyncTarget( ChangeLog* aChangeLog, StoragePlugin* aPlugin, const SyncMode& aSyncMode, const QString& aLocalNextAnchor ); /*! \brief Destructor * */ ~SyncTarget(); /*! \brief Returns the source database URI * * @return */ QString getSourceDatabase() const; /*! \brief Sets the target database URI * * @param aTargetDatabase Target database URI */ void setTargetDatabase( const QString& aTargetDatabase ); /*! \brief Returns the target database URI * * @return */ QString getTargetDatabase() const; /*! \brief Returns the last local anchor * * @return */ QString getLocalLastAnchor() const; /*! \brief Returns the next local anchor * * @return */ QString getLocalNextAnchor() const; /*! \brief Returns the last remote anchor * * @return */ QString getRemoteLastAnchor() const; /*! \brief Returns the next remote anchor * * @return */ QString getRemoteNextAnchor() const; /*! \brief Sets the next remote anchor * * @param aRemoteNextAnchor Next remote anchor */ void setRemoteNextAnchor( const QString& aRemoteNextAnchor ); /*! \brief Returns the sync mode in use * * @return */ SyncMode* getSyncMode(); /*! \brief Returns the sync mode in use * * @return */ const SyncMode* getSyncMode() const; /*! \brief Set the sync mode in use * * @param aSyncMode Sync mode */ void setSyncMode( const SyncMode& aSyncMode ); /*! \brief Revert to slow sync mode * */ void revertSyncMode(); /*! \brief Set client only refresh sync type * * @return True if sync mode has been set to client inited refresh from client (203) */ bool setRefreshFromClient(); /*! \brief Returns whether this target's sync mode has been reverted to slow sync * * @return True if sync mode has been reverted, otherwise false */ bool reverted() const; /*! \brief Detects local changes since last sync * * To retrieve the changes, use getLocalChanges() * * @param aRole Role in use * @return True on success, otherwise false */ bool discoverLocalChanges( const Role& aRole); /*! \brief Retrieve local changes since last sync * * Before calling this function, discoverLocalChanges() should be used to * find the changes * * @return Local changes */ const LocalChanges* getLocalChanges() const; /*! \brief Retrieve local changes since last sync * * Before calling this function, discoverLocalChanges() should be used to * find the changes * * @return Local changes */ LocalChanges* getLocalChanges() ; /*! \brief Return the plugin of the sync target * * @return */ StoragePlugin* getPlugin() const; /*! \brief Adds a mapping from remote UID to local UID * * @param aMapping Mapping */ void addUIDMapping( const UIDMapping& aMapping ); /*! \brief Removes a mapping from remote UID to local UID * * @param aLocalKey Local UID of the mapping to remove */ void removeUIDMapping( const SyncItemKey& aLocalKey ); /*! \brief Map a remote UID to local UID * * @param aRemoteUID Remote UID * @return Local UID if found, otherwise "" */ SyncItemKey mapToLocalUID( const QString& aRemoteUID ) const; /*! \brief Map a local UID to remote UID * * @param aLocalUID Local UID * @return Remote UID if found, otherwise "" */ QString mapToRemoteUID( const SyncItemKey& aLocalUID ) const; /*! \brief Loads UID mappings from persistent storage * */ void loadUIDMappings(); /*! \brief Returns the list of all mappings from remote UID to local UID * * @return List of mappings */ const QList& getUIDMappings() const; /*! \brief Clears the list of all mappings from remote UID to local UID * */ void clearUIDMappings(); /*! \brief Saves the sync session information after successful sync * * @param aDbHandler Database handler * @param aSyncEndTime Time of the end of sync */ void saveSession( DatabaseHandler& aDbHandler, const QDateTime& aSyncEndTime ); protected: private: ChangeLog* iChangeLog; StoragePlugin* iPlugin; QString iTargetDatabase; SyncMode iSyncMode; QString iLocalNextAnchor; QString iRemoteNextAnchor; LocalChanges iLocalChanges; QList iUIDMappings; bool iReverted; bool iLocalChangesDiscovered; friend class SyncTargetTest; }; } #endif // SYNCTARGET_H buteo-syncml-0.5.15/src/client/000077500000000000000000000000001433763642500163055ustar00rootroot00000000000000buteo-syncml-0.5.15/src/client/ClientSessionHandler.cpp000066400000000000000000000560641433763642500231040ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ClientSessionHandler.h" #include #include "SyncAgentConfig.h" #include "SyncAgentConfigProperties.h" #include "SyncTarget.h" #include "FinalPackage.h" #include "AlertPackage.h" #include "LocalMappingsPackage.h" #include "StoragePlugin.h" #include "ServerAlertedNotification.h" #include "SyncMLLogging.h" using namespace DataSync; ClientSessionHandler::ClientSessionHandler( const SyncAgentConfig* aConfig, QObject* aParent ) : SessionHandler(aConfig, ROLE_CLIENT, aParent), iConfig(aConfig) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } ClientSessionHandler::~ClientSessionHandler() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } void ClientSessionHandler::initiateSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !prepareSync() ) { return; } QString sessionId = generateSessionID(); setupSession( sessionId ); setupSyncTargets(); if( getStorages().count() != iConfig->getSourceDbs().count() ) { qCCritical(lcSyncML) << "Could not create all targets, aborting sync"; abortSync( DATABASE_FAILURE, "Could not create all sync targets" ); return; } if( !getTransport().init() ) { qCCritical(lcSyncML) << "Could not initialize transport"; abortSync( CONNECTION_ERROR, "Could not initiate transport" ); return; } composeClientInitializationPackage(); // If doing sync without init phase, move to sending items state if( isSyncWithoutInitPhase() ) { setSyncState( SENDING_ITEMS ); } else { setSyncState( LOCAL_INIT ); } sendNextMessage(); getTransport().receive(); } void ClientSessionHandler::handleNotificationXML( QList& aFragments ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !prepareSync() ) { return; } processMessage( aFragments, true ); } void ClientSessionHandler::handleNotificationPackage( const SANDS& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !prepareSync() ) { return; } // Set up session if( aData.iHeader.iSessionId == 0 ) { params().setSessionId( generateSessionID() ); } else { params().setSessionId( QString::number( aData.iHeader.iSessionId ) ); } if( !getConfig()->getLocalDeviceName().isEmpty() ) { params().setLocalDeviceName( getConfig()->getLocalDeviceName() ); } else { params().setLocalDeviceName( getConfig()->getDeviceInfo().getDeviceID() ); } params().setRemoteDeviceName( aData.iHeader.iServerIdentifier ); QString verDTD; QString verProto; if( aData.iHeader.iVersion == SYNCML_1_1 ) { qCDebug(lcSyncML) << "Setting SyncML 1.1 protocol version"; setProtocolVersion( SYNCML_1_1 ); verDTD = SYNCML_DTD_VERSION_1_1; verProto = DS_VERPROTO_1_1; } else if( aData.iHeader.iVersion == SYNCML_1_2 ) { qCDebug(lcSyncML) << "Setting SyncML 1.2 protocol version"; setProtocolVersion( SYNCML_1_2 ); verDTD = SYNCML_DTD_VERSION_1_2; verProto = DS_VERPROTO_1_2; } if( getConfig()->extensionEnabled( SYNCWITHOUTINITPHASEEXTENSION ) ) { setSyncWithoutInitPhase( true ); } HeaderParams headerParams; headerParams.verDTD = verDTD; headerParams.verProto = verProto; headerParams.sessionID = params().sessionId(); headerParams.sourceDevice = params().localDeviceName(); headerParams.targetDevice = params().remoteDeviceName(); headerParams.meta.maxMsgSize = params().localMaxMsgSize(); if( getConfig()->extensionEnabled( EMITAGSEXTENSION ) ) { insertEMITagsToken( headerParams ); } setLocalHeaderParams( headerParams ); // Set up targets for( int i = 0; i< aData.iSyncInfo.count(); ++i ) { SyncMode syncMode( aData.iSyncInfo[i].iSyncType ); syncMode.toClientInitiated(); QString serverURI = aData.iSyncInfo[i].iServerURI; if( !serverURI.contains( SYNCML_URI_PREFIX ) ) { serverURI.prepend( SYNCML_URI_PREFIX ); } QString mime = aData.iSyncInfo[i].iContentType; if( mime.isEmpty() ) { mime = convertSANURItoMIME( serverURI ); } if( mime.isEmpty() ) { qCCritical(lcSyncML) << "Could not find MIME for server URI:" << serverURI; continue; } qCDebug(lcSyncML) << "Searching for storage with MIME type" << mime; StoragePlugin* source = createStorageByMIME( mime ); if( !source ) { qCCritical(lcSyncML) << "Could not found matching storage for MIME:" << mime; continue; } SyncTarget* target = createSyncTarget( *source, syncMode ); if( !target ) { qCCritical(lcSyncML) << "Could not a target for MIME:" << mime; continue; } target->setTargetDatabase( serverURI ); // Use slow sync if this is the preferred mode or if we don't have a last anchor if( iConfig->getSyncMode().syncType() == TYPE_SLOW || target->getRemoteLastAnchor().isEmpty() ) { qCDebug(lcSyncML) << "Did not find last remote anchor or slow sync is forced, using slow sync"; SyncMode* mode = target->getSyncMode(); mode->toSlowSync(); target->setSyncMode( *mode ); } addSyncTarget( target ); } if( getStorages().count() != aData.iSyncInfo.count() ) { qCCritical(lcSyncML) << "Could not create all targets, aborting"; abortSync( DATABASE_FAILURE, "Could not create all sync targets"); return; } composeClientInitializationPackage(); // If doing sync without init phase, move to sending items state if( isSyncWithoutInitPhase() ) { setSyncState( SENDING_ITEMS ); } else { setSyncState( LOCAL_INIT ); } sendNextMessage(); getTransport().receive(); } void ClientSessionHandler::suspendSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // @todo: existing implementation was considered flawed, reimplement to be working // as soon as possible Q_ASSERT( 0 ); } void ClientSessionHandler::resumeSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // @todo: existing implementation was considered flawed, reimplement to be working // as soon as possible Q_ASSERT( 0 ); } void ClientSessionHandler::messageReceived( HeaderParams& aHeaderParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState state = getSyncState(); if( state == PREPARED ) { // Server is initiating a sync setupSession( aHeaderParams ); } else if( state == LOCAL_INIT ) { // Initialization message from server // When we sent initialization message we might not have necessarily // known the remote device id, so update it based on the received header params().setRemoteDeviceName( aHeaderParams.sourceDevice ); // Update remote device id also to header params HeaderParams headerParams = getLocalHeaderParams(); headerParams.targetDevice = aHeaderParams.sourceDevice; setLocalHeaderParams( headerParams ); } } ResponseStatusCode ClientSessionHandler::syncAlertReceived( const SyncMode& aSyncMode, CommandParams& aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status; SyncState syncState = getSyncState(); if( syncState == PREPARED ) { // Server is initiating a sync status = setupTargetByServer( aSyncMode, aAlertParams ); } else if( syncState == LOCAL_INIT || syncState == REMOTE_INIT ) { // Server is acknowledging a sync mode status = acknowledgeTarget( aSyncMode, aAlertParams ); setSyncState( REMOTE_INIT ); } else if( syncState == SENDING_ITEMS ) { // Allow Alert only if we're doing sync without init phase if( isSyncWithoutInitPhase() ) { status = acknowledgeTarget( aSyncMode, aAlertParams ); setSyncState( REMOTE_INIT ); } else { status = COMMAND_NOT_ALLOWED; } } else { // Don't allow sync related alerts in other states status = COMMAND_NOT_ALLOWED; } return status; } bool ClientSessionHandler::syncReceived() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); if( syncState == SENDING_ITEMS || syncState == RECEIVING_ITEMS ) { setSyncState( RECEIVING_ITEMS ); return true; } else if( syncState == REMOTE_INIT ) { // Allow only if doing sync without init phase if( isSyncWithoutInitPhase() ) { setSyncState( RECEIVING_ITEMS ); return true; } else { return false; } } else { // We don't allow sync in other states return false; } } bool ClientSessionHandler::mapReceived() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Client should never receive Map return false; } void ClientSessionHandler::finalReceived() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); switch( syncState ) { case PREPARED: { composeClientInitializationPackage(); setSyncState( LOCAL_INIT ); break; } case REMOTE_INIT: { composeClientModificationsPackage(); setSyncState( SENDING_ITEMS ); break; } case RECEIVING_ITEMS: { composeDataUpdateStatusPackage(); setSyncState( SENDING_MAPPINGS ); break; } case SENDING_ITEMS: case SENDING_MAPPINGS: { setSyncState( FINALIZING ); break; } default: { QString errorMsg; SyncState state = getLastError(errorMsg); abortSync( state, errorMsg ); break; } } } void ClientSessionHandler::messageParsed() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // if we have 101 for SyncHdr Status in SyncBody // send a result Alert if( isRemoteBusyStatusSet()) { composeResultAlert(); resetRemoteBusyStatus(); } SyncState syncState = getSyncState(); switch( syncState ) { case PREPARED: case LOCAL_INIT: case REMOTE_INIT: case SENDING_ITEMS: case RECEIVING_ITEMS: { sendNextMessage(); getTransport().receive(); break; } case SENDING_MAPPINGS: { // Check if we need to send the next message if( shouldSendDataUpdateStatus() ) { sendNextMessage(); getTransport().receive(); } else { qCDebug(lcSyncML) << "Omiting update status package!"; finishSync(); } break; } case FINALIZING: { finishSync(); break; } default: { break; } } } bool ClientSessionHandler::shouldSendDataUpdateStatus() { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool shouldSend = true; if( 0 < getConfig()->getAgentProperty( OMITDATAUPDATESTATUSPROP ).toInt() ) { // Check if we have anything other than status for the SyncHdr, and the // Final package to send to the server const QList& responseStatuses = getResponseGenerator().getStatuses(); if( ( 1 == responseStatuses.count() ) && ( SYNCML_ELEMENT_SYNCHDR == responseStatuses.at(0)->cmd ) && ( getResponseGenerator().getPackages().count() <= 1 ) ) { qCDebug(lcSyncML) << "There is only one status fragment in response and it's for the sync header,\ so we can omit the update status package"; shouldSend = false; } } return shouldSend; } void ClientSessionHandler::resendPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); switch( syncState ) { case LOCAL_INIT: { getDevInfHandler().reset(); composeClientInitializationPackage(); break; } case SENDING_ITEMS: { composeClientModificationsPackage(); break; } case SENDING_MAPPINGS: { composeDataUpdateStatusPackage(); break; } default: { abortSync( INTERNAL_ERROR, "Internal state machine error" ); break; } } } ResponseStatusCode ClientSessionHandler::setupTargetByServer( const SyncMode& aSyncMode, CommandParams& aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aAlertParams.items.isEmpty() ) { qCWarning(lcSyncML) << "Received alert without any items! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } ItemParams& item = aAlertParams.items.first(); const MetaParams& meta = item.meta; if( item.source.isEmpty() || meta.type.isEmpty() ) { qCWarning(lcSyncML) << "Received alert that did not pass validation! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } SyncMode syncMode = aSyncMode; syncMode.toClientInitiated(); qCDebug(lcSyncML) << "Searching for storage with MIME type" << meta.type; StoragePlugin* source = createStorageByMIME( meta.type ); if( !source ) { qCDebug(lcSyncML) << "Could not found matching storage for MIME:" << meta.type; return NOT_FOUND; } SyncTarget* target = createSyncTarget( *source, syncMode ); if( !target ) { return COMMAND_FAILED; } ResponseStatusCode status = SUCCESS; target->setTargetDatabase( item.source ); if( target->getSyncMode()->syncType() == TYPE_FAST ) { //We are in fast sync mode, load mappings for target target->loadUIDMappings(); } else { //In slow mode, all mappings become invalid qCDebug(lcSyncML) << "In client mode slow sync, clear all mappings"; target->clearUIDMappings(); } addSyncTarget( target ); // Set target database now that we know what it is so that we can write proper // targetref to returned status item.target = target->getSourceDatabase(); return status; } ResponseStatusCode ClientSessionHandler::acknowledgeTarget( const SyncMode& aSyncMode, CommandParams& aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aAlertParams.items.isEmpty() ) { qCWarning(lcSyncML) << "Received alert without any items! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } const ItemParams& item = aAlertParams.items.first(); const MetaParams& meta = item.meta; const AnchorParams& anchors = meta.anchor; if( item.target.isEmpty() || anchors.next.isEmpty() ) { qCWarning(lcSyncML) << "Received alert that did not pass validation! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } SyncMode syncMode = aSyncMode; SyncTarget* target = getSyncTarget( item.target ); if( !target ) { return NOT_FOUND; } ResponseStatusCode status = SUCCESS; target->setRemoteNextAnchor( anchors.next ); // Analyze sync mode proposed by server. According to OMA DS 1.2 specification, // client SHOULD follow sync mode given by server even if it is different than the // sync mode sent by client. // Explicitly order sync target to revert in case of slow sync, it is not enough // to just set a new sync mode. Also we need to clear all mappings as they are now // invalid if( syncMode.syncType() != TYPE_FAST ) { qCDebug(lcSyncML) << "Server requested revertion to slow sync for database" << target->getSourceDatabase() <<", complying and clearing mappings"; target->revertSyncMode(); target->clearUIDMappings(); } // Set mode proposed by server target->setSyncMode(syncMode); return status; } void ClientSessionHandler::setupSyncTargets() { FUNCTION_CALL_TRACE(lcSyncMLTrace); QList sources; if (iConfig != NULL) { sources = iConfig->getSourceDbs(); } foreach(const QString& sourceDb, sources) { StoragePlugin* plugin = createStorageByURI( sourceDb ); SyncTarget* target = NULL; if (plugin != NULL) { target = createSyncTarget( *plugin, iConfig->getSyncMode() ); } if (target != NULL) { QString targetDb = iConfig->getTarget( sourceDb ); target->setTargetDatabase( targetDb ); // Use slow sync if this is the preferred mode or if we don't have a last anchor if (iConfig->getSyncMode().syncType() == TYPE_SLOW || target->getRemoteLastAnchor().isEmpty()) { qCDebug(lcSyncML) << "Did not find last remote anchor, forcing slow sync"; SyncMode* mode = target->getSyncMode(); mode->toSlowSync(); target->setSyncMode( *mode ); } addSyncTarget( target ); } } } void ClientSessionHandler::composeClientInitializationPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Compose initialization composeClientInitialization(); // If we are to do sync without separate initialization phase, send local modifications too if( isSyncWithoutInitPhase() ) { discoverClientLocalChanges(); composeLocalChanges(); } // Close the package by appending Final getResponseGenerator().addPackage( new FinalPackage() ); } void ClientSessionHandler::composeClientModificationsPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); discoverClientLocalChanges(); composeLocalChanges(); // Close the package by appending Final getResponseGenerator().addPackage( new FinalPackage() ); } void ClientSessionHandler::composeDataUpdateStatusPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Mappings need to be sent in data update status package if we have not // yet sent them bool fastMapsSend = false; int configValue = getConfig()->getAgentProperty( FASTMAPSSENDPROP ).toInt(); if( configValue > 0 ) { fastMapsSend = true; } if( !fastMapsSend ) { const QList& targets = getSyncTargets(); foreach( const SyncTarget* target, targets ) { QList mappings = target->getUIDMappings(); if (mappings.size() > 0 ) { LocalMappingsPackage* localMappingsPackage = new LocalMappingsPackage( target->getSourceDatabase(), target->getTargetDatabase(), mappings); connect( localMappingsPackage, SIGNAL( newMapWritten( int, int, const QString&, const QString& ) ), this, SLOT( newMapReference( int, int, const QString&, const QString& ) ) ); getResponseGenerator().addPackage( localMappingsPackage ); } } } // Close the package by appending Final getResponseGenerator().addPackage( new FinalPackage() ); } void ClientSessionHandler::composeClientInitialization() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Authentication authentication().composeAuthentication( getResponseGenerator(), getDatabaseHandler(), params().localDeviceName(), params().remoteDeviceName() ); // Device info exchange getDevInfHandler().composeLocalInitiatedDevInfExchange( getStorages(), getProtocolVersion(), ROLE_CLIENT, getResponseGenerator() ); // Sync init packages include alerts to inform server about the databases we wish to sync const QList& targets = getSyncTargets(); foreach( const SyncTarget* target, targets) { if (target != NULL) { AlertPackage* package = new AlertPackage( target->getSyncMode()->toSyncMLCode(), target->getSourceDatabase(), target->getTargetDatabase(), target->getLocalLastAnchor(), target->getLocalNextAnchor() ); getResponseGenerator().addPackage( package ); } } } void ClientSessionHandler::composeResultAlert() { FUNCTION_CALL_TRACE(lcSyncMLTrace); AlertPackage* package = new AlertPackage( RESULT_ALERT, params().localDeviceName(), params().remoteDeviceName() ); getResponseGenerator().addPackage( package ); } void ClientSessionHandler::discoverClientLocalChanges() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // @todo: check what we should do if discovering local changes fails. Probably // internal abort as we can't reliable achieve synchronization? if (iConfig != NULL) { const QList targets = getSyncTargets(); foreach (SyncTarget* target, targets) { if( target != NULL && !target->discoverLocalChanges(ROLE_CLIENT) ) { qCWarning(lcSyncML) << "Error in discovering changes for target" << target->getSourceDatabase(); } } } } QString ClientSessionHandler::convertSANURItoMIME( const QString& aServerURI ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QString mime; if( getConfig()->extensionEnabled( SANMAPPINGSEXTENSION ) ) { QStringList mappings = getConfig()->getExtensionData( SANMAPPINGSEXTENSION ).toStringList(); for( int i = 0; i < mappings.count(); i+=2 ) { if( aServerURI.contains( mappings[i], Qt::CaseInsensitive ) ) { mime = mappings[i+1]; qCDebug(lcSyncML) << "Found mapping for server URI" << aServerURI <<":" << mime; break; } } } return mime; } buteo-syncml-0.5.15/src/client/ClientSessionHandler.h000066400000000000000000000077631433763642500225530ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CLIENTSESSIONHANDLER_H #define CLIENTSESSIONHANDLER_H #include "SessionHandler.h" class SessionHandlerTest; class ClientSessionHandlerTest; namespace DataSync { struct SANDS; /*! \brief Handles SyncML client related session management * */ class ClientSessionHandler : public SessionHandler { Q_OBJECT; public: /** * \brief Constructor * @param aConfig A pointer to configuration object * @param aParent A pointer to parent object */ explicit ClientSessionHandler( const SyncAgentConfig* aConfig, QObject* aParent = 0); /** * \brief Destructor */ virtual ~ClientSessionHandler(); public slots: virtual void initiateSync(); virtual void suspendSync(); virtual void resumeSync(); /*! \brief Initiate a synchronization session from XML-based server-alerted * notification * * @param aFragments Protocol fragments of the notification */ void handleNotificationXML( QList& aFragments ); /*! \brief Initiate a synchronization session from server-alerted notification * package * * @param aData Data of the notification */ void handleNotificationPackage( const SANDS& aData ); protected: virtual void messageReceived( HeaderParams& aHeaderParams ); virtual ResponseStatusCode syncAlertReceived( const SyncMode& aSyncMode, CommandParams& aAlertParams ); virtual bool syncReceived(); virtual bool mapReceived(); virtual void finalReceived(); virtual void messageParsed(); virtual void resendPackage(); private: // functions ResponseStatusCode setupTargetByServer( const SyncMode& aSyncMode, CommandParams& aAlertParams ); ResponseStatusCode acknowledgeTarget( const SyncMode& aSyncMode, CommandParams& aAlertParams ); void setupSyncTargets(); void composeClientInitializationPackage(); void composeClientModificationsPackage(); void composeDataUpdateStatusPackage(); void composeClientInitialization(); void discoverClientLocalChanges(); void composeResultAlert(); QString convertSANURItoMIME( const QString& aServerURI ); bool shouldSendDataUpdateStatus(); private: // data const DataSync::SyncAgentConfig* iConfig; ///< A pointer to configuration friend class ::SessionHandlerTest; friend class ::ClientSessionHandlerTest; }; } #endif /* CLIENTSESSIONHANDLER_H */ buteo-syncml-0.5.15/src/client/client.pro000066400000000000000000000001061433763642500203020ustar00rootroot00000000000000HEADERS += ClientSessionHandler.h SOURCES += ClientSessionHandler.cpp buteo-syncml-0.5.15/src/config/000077500000000000000000000000001433763642500162745ustar00rootroot00000000000000buteo-syncml-0.5.15/src/config/meego-syncml-conf.xml000066400000000000000000000014571433763642500223470ustar00rootroot00000000000000 syncml.db MeegoDevice 16384 22 0 0 0 16384 32768 1024 120 3 buteo-syncml-0.5.15/src/config/meego-syncml-conf.xsd000066400000000000000000000120061433763642500223350ustar00rootroot00000000000000 buteo-syncml-0.5.15/src/datatypes.h000066400000000000000000000267101433763642500172040ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DATATYPES_H #define DATATYPES_H #include #include #include #include #include #include #include "SyncItemKey.h" #include "SyncMLCommand.h" namespace DataSync { /*! \brief OMA DS role * */ enum Role { ROLE_CLIENT, /*! * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ServerSessionHandler.h" #include "SyncAgentConfig.h" #include "StoragePlugin.h" #include "SyncTarget.h" #include "AlertPackage.h" #include "FinalPackage.h" #include "DevInfPackage.h" #include "AuthHelper.h" #include "ServerAlertedNotification.h" #include "StorageProvider.h" #include "SyncMLLogging.h" using namespace DataSync; ServerSessionHandler::ServerSessionHandler( const SyncAgentConfig* aConfig, QObject* aParent ) : SessionHandler( aConfig, ROLE_SERVER, aParent ), iConfig(aConfig) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } ServerSessionHandler::~ServerSessionHandler() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } void ServerSessionHandler::initiateSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !prepareSync() ) { return; } QString sessionId = generateSessionID(); setupSession( sessionId ); ProtocolVersion protocolVersion = getProtocolVersion(); qCDebug(lcSyncML) << "Using protocol version " << protocolVersion; QList sourceDbs = iConfig->getSourceDbs(); QList< QPair > storages; for( int i = 0; i < sourceDbs.count(); ++i ) { const QString& sourceURI = sourceDbs[i]; StorageContentFormatInfo info; if( iConfig->getStorageProvider()->getStorageContentFormatInfo( sourceURI, info ) ) { QPair storage; storage.first = sourceURI; storage.second = info.getPreferredTx().iType; storages.append( storage ); } } if( storages.count() != sourceDbs.count() ) { qCCritical(lcSyncML) << "Could not find all targets, aborting sync"; abortSync( DATABASE_FAILURE, "Could not find all sync targets" ); return; } if( !getTransport().init() ) { qCCritical(lcSyncML) << "Could not initialize transport"; abortSync( CONNECTION_ERROR, "Could not initiate transport" ); return; } if( protocolVersion == SYNCML_1_1 ) { serverInitiatedSyncDS11( storages ); } else if ( protocolVersion == SYNCML_1_2 ){ serverInitiatedSyncDS12( storages ); } else { abortSync( INTERNAL_ERROR, "Unknown protocol version" ); } } void ServerSessionHandler::serveRequest( QList& aFragments ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !prepareSync() ) { return; } processMessage( aFragments, true ); } void ServerSessionHandler::suspendSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Sync cannot be suspended or resumed from server. Therefore this function // should never be called. Abort with internal error in those situations abortSync( INTERNAL_ERROR, "Not supported in server mode" ); } void ServerSessionHandler::resumeSync() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Sync cannot be suspended or resumed from server. Therefore this function // should never be called. Abort with internal error in those situations abortSync( INTERNAL_ERROR, "Not supported in server mode" ); } void ServerSessionHandler::messageReceived( HeaderParams& aHeaderParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState state = getSyncState(); if( state == PREPARED ) { // Sync session initialization setupSession( aHeaderParams ); } } ResponseStatusCode ServerSessionHandler::syncAlertReceived( const SyncMode& aSyncMode, CommandParams& aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); ResponseStatusCode status; SyncState syncState = getSyncState(); if( syncState == PREPARED || syncState == REMOTE_INIT ) { // Client is sending initial alerts for sync status = setupTargetByClient( aSyncMode, aAlertParams ); setSyncState( REMOTE_INIT ); } else if( syncState == LOCAL_INIT ) { // Client is acknowledging alert, to revert to slow sync status = acknowledgeTarget( aSyncMode, aAlertParams ); } else { // Don't allow sync related alerts outside init phase status = COMMAND_NOT_ALLOWED; } return status; } bool ServerSessionHandler::syncReceived() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); if( syncState == REMOTE_INIT ) { // If we receive a sync when in remote init, it means that // client is doing sync without init phase. Check if reverts occurred, // in that case we can't do sync without init phase. Then, all // modifications sent by client must be ignored. bool reverts = false; const QList& targets = getSyncTargets(); for( int i = 0; i < targets.count(); ++i ) { if( targets[i]->reverted() ) { reverts = true; break; } } if( reverts ) { return false; } else { setSyncWithoutInitPhase(true); setSyncState( RECEIVING_ITEMS ); return true; } } else if( syncState == LOCAL_INIT ) { setSyncState( RECEIVING_ITEMS ); return true; } else if( syncState == RECEIVING_ITEMS ) { return true; } else { // We don't allow sync in other states return false; } } bool ServerSessionHandler::mapReceived() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); // If we sent the last set of items and received mappings from client, send the final if( syncState == SENDING_ITEMS && getResponseGenerator().packageQueueEmpty() ) { setSyncState( RECEIVING_MAPPINGS ); return true; } // If we receive mappings before we close our sending items package, don't send the final else if( syncState == SENDING_ITEMS ) { return true; } else if( syncState == RECEIVING_MAPPINGS ) { return true; } else { // We don't allow map in other states return false; } } void ServerSessionHandler::finalReceived() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); switch( syncState ) { case REMOTE_INIT: { composeServerInitializationPackage(); setSyncState( LOCAL_INIT ); break; } case RECEIVING_ITEMS: { const QList& targets = getSyncTargets(); // Search for targets that need their modifications sent bool sendServerModifications = false; foreach( const SyncTarget* syncTarget, targets) { if( syncTarget->getSyncMode()->syncDirection() != DIRECTION_FROM_CLIENT ) { sendServerModifications = true; break; } } if( sendServerModifications ){ composeServerModificationsPackage(); setSyncState( SENDING_ITEMS ); } // Don't need to send server modifications else { composeMapAcknowledgementPackage(); setSyncState( FINALIZING ); } break; } case SENDING_ITEMS: { // If we have no more items to send if( getResponseGenerator().packageQueueEmpty() ) { composeMapAcknowledgementPackage(); setSyncState( FINALIZING ); } break; } case RECEIVING_MAPPINGS: { setSyncState( FINALIZING ); composeMapAcknowledgementPackage(); break; } default: { // Try to find out what error occurred QString errorMsg; SyncState state = getLastError(errorMsg); abortSync( state, errorMsg ); break; } } } void ServerSessionHandler::messageParsed() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); switch( syncState ) { case PREPARED: case REMOTE_INIT: case LOCAL_INIT: case RECEIVING_ITEMS: case SENDING_ITEMS: case RECEIVING_MAPPINGS: { sendNextMessage(); getTransport().receive(); break; } case FINALIZING: { sendNextMessage(); // Check if we've finished sending everything we need to send to client if( getResponseGenerator().packageQueueEmpty() ) { finishSync(); } break; } default: { break; } } } void ServerSessionHandler::resendPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncState syncState = getSyncState(); switch( syncState ) { case LOCAL_INIT: { composeServerInitializationPackage(); break; } case SENDING_ITEMS: { composeServerModificationsPackage(); break; } case FINALIZING: { composeMapAcknowledgementPackage(); break; } default: { abortSync( INTERNAL_ERROR, "Internal state machine error" ); break; } } } ResponseStatusCode ServerSessionHandler::setupTargetByClient( const SyncMode& aSyncMode, CommandParams& aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aAlertParams.items.isEmpty() ) { qCWarning(lcSyncML) << "Received alert without any items! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } // Require remote device source database (which is our target database), and // either remote device target database (which is our source database) or mime type // of our source database. Also Next anchor const ItemParams& item = aAlertParams.items.first(); const MetaParams& meta = item.meta; const AnchorParams& anchors = meta.anchor; if( item.source.isEmpty() || anchors.next.isEmpty() || ( item.target.isEmpty() && meta.type.isEmpty() ) ) { qCWarning(lcSyncML) << "Received alert that did not pass validation! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } StoragePlugin* source = 0; if( !item.target.isEmpty() ) { source = createStorageByURI( item.target ); } else if( !meta.type.isEmpty() ){ source = createStorageByMIME( meta.type ); } if( !source ) { return NOT_FOUND; } SyncTarget* target = createSyncTarget( *source, aSyncMode ); if( !target ) { return COMMAND_FAILED; } ResponseStatusCode status = SUCCESS; target->setSyncMode( aSyncMode ); target->setRemoteNextAnchor( anchors.next ); target->setTargetDatabase( item.source ); if( aSyncMode.syncType() == TYPE_SLOW || iConfig->getSyncMode().syncType() == TYPE_SLOW || anchorMismatch( aSyncMode, *target, anchors.last ) ) { qCDebug(lcSyncML) << "Anchor mismatch, refresh required"; // Anchor mismatch, must revert to slow sync status = REFRESH_REQUIRED; // @todo: we should implement this better, so that it'd check synccaps of remote device // in all cases, not just for from-client syncs bool clientInitiedRefresh = false; int datastoreIndex = -1; const QList& datastores = getDevInfHandler().getRemoteDeviceInfo().datastores(); qCDebug(lcSyncML) << "Count for remote device stores:::" << datastores.count(); for( int i = 0; i < datastores.count(); ++i ) { if( datastores[i].getSourceURI() == target->getTargetDatabase() ) { datastoreIndex = i; break; } } if( datastoreIndex != -1 ) { if( datastores[datastoreIndex].syncCaps().contains( DataSync::SYNCTYPE_FROMCLIENTSLOW ) && (clientInitiedRefresh = target->setRefreshFromClient()) ) { qCDebug(lcSyncML) << "Anchor mismatch, client refresh required, sending 203 as client supports refresh"; } if( !clientInitiedRefresh ){ qCDebug(lcSyncML) << "Anchor mismatch, refresh required, sending 202"; target->revertSyncMode(); } } else { qCDebug(lcSyncML) << "Anchor mismatch but have no device info available, reverting"; target->revertSyncMode(); } } if( target->getSyncMode()->syncType() == TYPE_FAST ) { // We are in fast sync mode, load mappings for target target->loadUIDMappings(); } else { // In slow mode, all mappings become invalid target->clearUIDMappings(); } addSyncTarget( target ); return status; } ResponseStatusCode ServerSessionHandler::acknowledgeTarget( const SyncMode& /*aSyncMode*/, CommandParams& aAlertParams ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aAlertParams.items.isEmpty() ) { qCWarning(lcSyncML) << "Received alert without any items! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } const ItemParams& item = aAlertParams.items.first(); if( item.target.isEmpty() ) { qCWarning(lcSyncML) << "Received alert that did not pass validation! Cmd Id:" << aAlertParams.cmdId; return INCOMPLETE_COMMAND; } SyncTarget* target = getSyncTarget( item.target ); if( !target ) { return NOT_FOUND; } target->setRemoteNextAnchor( item.meta.anchor.next ); target->revertSyncMode(); // In slow mode, all mappings become invalid target->clearUIDMappings(); return SUCCESS; } void ServerSessionHandler::composeSyncML11ServerAlertedSyncPackage( const QList< QPair >& aStorages ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qint32 alertCode = iConfig->getSyncMode().toSyncMLCode(); for( int i = 0; i < aStorages.count(); ++i ) { AlertPackage* package = new AlertPackage(aStorages[i].first, aStorages[i].second, alertCode ); getResponseGenerator().addPackage(package); } // Close the package by appending Final getResponseGenerator().addPackage( new FinalPackage() ); } void ServerSessionHandler::composeAndSendSyncML12ServerAlertedSyncPackage( const QList< QPair >& aStorages ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SANHandler handler; SANDS data; data.iHeader.iVersion = SYNCML_1_2; data.iHeader.iUIMode = SANUIMODE_BACKGROUND; data.iHeader.iInitiator = SANINITIATOR_SERVER; data.iHeader.iSessionId = 0; data.iHeader.iServerIdentifier = getConfig()->getLocalDeviceName(); int syncType = getConfig()->getSyncMode().toSyncMLCode(); for( int i = 0; i < aStorages.count(); ++i ) { SANSyncInfo syncInfo; syncInfo.iSyncType = syncType; syncInfo.iServerURI = aStorages[i].first; syncInfo.iContentType = aStorages[i].second; data.iSyncInfo.append( syncInfo ); } QByteArray message; QString user = getConfig()->getUsername(); QString password = getConfig()->getPassword(); if( !handler.generateSANMessageDS( data, user, password, message ) ) { qCCritical(lcSyncML) << "Could not generate SyncML 1.2 SAN package"; abortSync( INTERNAL_ERROR, "Error while generating 1.2 SAN package" ); return; } if( !getTransport().sendSAN( message ) ) { qCCritical(lcSyncML) << "Could not send SyncML 1.2 SAN package"; abortSync( INTERNAL_ERROR, "Error while sending 1.2 SAN package" ); } } void ServerSessionHandler::composeServerInitializationPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); composeServerInitialization(); // Close the package by appending Final getResponseGenerator().addPackage( new FinalPackage() ); } void ServerSessionHandler::composeServerModificationsPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // If doing sync without init phase, also send initialization if( isSyncWithoutInitPhase() ) { composeServerInitialization(); } composeLocalChanges(); // Close the package by appending Final getResponseGenerator().addPackage( new FinalPackage() ); } void ServerSessionHandler::composeMapAcknowledgementPackage() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Close the package by appending Final getResponseGenerator().addPackage( new FinalPackage() ); } void ServerSessionHandler::composeServerInitialization() { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Sync init packages include alerts to inform client about the databases we wish to sync const QList& targets = getSyncTargets(); foreach( const SyncTarget* target, targets) { AlertPackage* package = new AlertPackage( target->getSyncMode()->toSyncMLCode(), target->getSourceDatabase(), target->getTargetDatabase(), target->getLocalLastAnchor(), target->getLocalNextAnchor() ); getResponseGenerator().addPackage( package ); } } void ServerSessionHandler::serverInitiatedSyncDS11( const QList< QPair >& aStorages ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Send initialization package to client composeSyncML11ServerAlertedSyncPackage( aStorages ); setSyncState( PREPARED ); sendNextMessage(); getTransport().receive(); } void ServerSessionHandler::serverInitiatedSyncDS12( const QList< QPair >& aStorages ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Send initialization package to client composeAndSendSyncML12ServerAlertedSyncPackage( aStorages ); setSyncState( PREPARED ); getTransport().receive(); } buteo-syncml-0.5.15/src/server/ServerSessionHandler.h000066400000000000000000000077461433763642500226340ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SERVERSESSIONHANDLER_H #define SERVERSESSIONHANDLER_H #include "SessionHandler.h" #include #include #include class ServerSessionHandlerTest; namespace DataSync { /*! \brief Handles SyncML server related session management * */ class ServerSessionHandler: public SessionHandler { Q_OBJECT public: /*! \brief Constructor * * @param aConfig A pointer to configuration object * @param aParent A pointer to parent object */ explicit ServerSessionHandler( const SyncAgentConfig* aConfig, QObject* aParent = 0 ); /*! \brief Destructor * */ virtual ~ServerSessionHandler(); public slots: virtual void initiateSync(); virtual void suspendSync(); virtual void resumeSync(); /*! \brief Initiate a new synchronization session as a server by serving the * request sent by remote client * * @param aFragments Protocol fragments of the request sent by client */ void serveRequest( QList& aFragments ); protected: virtual void messageReceived( HeaderParams& aHeaderParams ); virtual ResponseStatusCode syncAlertReceived( const SyncMode& aSyncMode, CommandParams& aAlertParams ); virtual bool syncReceived(); virtual bool mapReceived(); virtual void finalReceived(); virtual void messageParsed(); virtual void resendPackage(); private: ResponseStatusCode setupTargetByClient( const SyncMode& aSyncMode, CommandParams& aAlertParams ); ResponseStatusCode acknowledgeTarget( const SyncMode& aSyncMode, CommandParams& aAlertParams ); void composeSyncML11ServerAlertedSyncPackage( const QList< QPair >& aStorages ); void composeAndSendSyncML12ServerAlertedSyncPackage( const QList< QPair >& aStorages ); void composeServerInitializationPackage(); void composeServerModificationsPackage(); void composeMapAcknowledgementPackage(); void composeServerInitialization(); void serverInitiatedSyncDS11( const QList< QPair >& aStorages ); void serverInitiatedSyncDS12( const QList< QPair >& aStorages ); private: // data const DataSync::SyncAgentConfig* iConfig; ///< A pointer to configuration friend class ::ServerSessionHandlerTest; }; } #endif /* SERVERSESSIONHANDLER_H */ buteo-syncml-0.5.15/src/server/server.pro000066400000000000000000000001071433763642500203630ustar00rootroot00000000000000SOURCES += ServerSessionHandler.cpp HEADERS += ServerSessionHandler.h buteo-syncml-0.5.15/src/src.pro000066400000000000000000000077141433763642500163510ustar00rootroot00000000000000include(syncelements/syncelements.pro) include(server/server.pro) include(client/client.pro) include(transport/transport.pro) TEMPLATE = lib TARGET = buteosyncml5 VPATH += client \ syncelements \ server \ transport CONFIG += dll \ create_pc \ create_prl \ link_pkgconfig PKGCONFIG = buteosyncfw5 \ libwbxml2 INCLUDEPATH += . \ syncelements \ server \ client \ transport DEPENDPATH += . \ syncelements \ server \ client \ transport SOURCES += SyncItem.cpp \ ChangeLog.cpp \ SuspendLog.cpp \ SyncAgent.cpp \ SyncAgentConfig.cpp \ SyncMLMessageParser.cpp \ AuthenticationPackage.cpp \ LocalChangesPackage.cpp \ LocalMappingsPackage.cpp \ DeviceInfo.cpp \ RemoteDeviceInfo.cpp \ SyncTarget.cpp \ FinalPackage.cpp \ AlertPackage.cpp \ SyncResults.cpp \ SessionHandler.cpp \ CommandHandler.cpp \ StorageHandler.cpp \ ResponseGenerator.cpp \ SyncMode.cpp \ DevInfPackage.cpp \ DatabaseHandler.cpp \ ConflictResolver.cpp \ AuthHelper.cpp \ NonceStorage.cpp \ ServerAlertedNotification.cpp \ RequestListener.cpp \ SyncMLLogging.cpp \ DevInfHandler.cpp \ SyncItemPrefetcher.cpp \ CTCap.cpp \ DataStore.cpp \ StorageContentFormatInfo.cpp \ SessionAuthentication.cpp \ SessionParams.cpp HEADERS += SyncItem.h \ StoragePlugin.h \ ChangeLog.h \ SuspendLog.h \ SyncAgent.h \ SyncItemKey.h \ datatypes.h \ Fragments.h \ SyncAgentConfig.h \ SyncMLMessageParser.h \ AuthenticationPackage.h \ LocalChangesPackage.h \ LocalMappingsPackage.h \ Package.h \ DeviceInfo.h \ RemoteDeviceInfo.h \ SyncAgentConsts.h \ SyncResults.h \ SyncTarget.h \ FinalPackage.h \ AlertPackage.h \ SyncMLCommand.h \ SessionHandler.h \ CommandHandler.h \ StorageHandler.h \ ResponseGenerator.h \ SyncMode.h \ DevInfPackage.h \ DatabaseHandler.h \ ConflictResolver.h \ AuthHelper.h \ NonceStorage.h \ StorageProvider.h \ ServerAlertedNotification.h \ SyncMLGlobals.h \ SyncMLLogging.h \ RequestListener.h \ DevInfHandler.h \ SyncAgentConfigProperties.h \ SyncItemPrefetcher.h \ CTCap.h \ DataStore.h \ StorageContentFormatInfo.h \ LocalChanges.h \ SessionAuthentication.h \ SessionParams.h OTHER_FILES += config/meego-syncml-conf.xsd \ config/meego-syncml-conf.xml LIBS += -lsqlite3 -lopenobex QTDIR = $$[QT_INSTALL_LIBS]/qt5 QT += network \ xml \ sql \ xmlpatterns QT -= gui # TODO extract DEBUG QMAKE_CXXFLAGS = -Wall \ -g \ -Wno-cast-align \ -O2 -finline-functions QMAKE_CLEAN += lib*.so* \ lib$${TARGET}.prl pkgconfig/* #QMAKE_STRIP = strip #QMAKE_STRIPFLAGS_LIB += --strip-unneeded headers.path = $$PREFIX/include/buteosyncml5 headers.files = $$HEADERS target.path = $$[QT_INSTALL_LIBS] config.path = /etc/buteo config.files = config/meego-syncml-conf.xsd \ config/meego-syncml-conf.xml INSTALLS += target \ headers \ config QMAKE_PKGCONFIG_DESTDIR = pkgconfig QMAKE_PKGCONFIG_LIBDIR = $$target.path QMAKE_PKGCONFIG_INCDIR = $$headers.path QMAKE_PKGCONFIG_VERSION = $$VERSION # Uncomment the following line to enable GCOV/LCOV report generation #CONFIG += gcov gcov { message(Test coverage report is ENABLED) QMAKE_CC = SBOX_USE_CCACHE=no $$QMAKE_CC QMAKE_CXX = SBOX_USE_CCACHE=no $$QMAKE_CXX QMAKE_CFLAGS += -fprofile-arcs -ftest-coverage QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage LIBS += -lgcov } !gcov { message(Test coverage report is DISABLED) } QMAKE_CLEAN += *.gcno *.gcda *.gcov buteo-syncml-0.5.15/src/syncelements/000077500000000000000000000000001433763642500175405ustar00rootroot00000000000000buteo-syncml-0.5.15/src/syncelements/SyncMLAdd.cpp000066400000000000000000000034571433763642500220330ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLAdd.h" #include "datatypes.h" using namespace DataSync; SyncMLAdd::SyncMLAdd( int aCmdID ) : SyncMLLocalChange( SYNCML_ELEMENT_ADD, aCmdID ) { } SyncMLAdd::~SyncMLAdd() { } buteo-syncml-0.5.15/src/syncelements/SyncMLAdd.h000066400000000000000000000042041433763642500214670ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLADD_H #define SYNCMLADD_H #include "SyncMLLocalChange.h" namespace DataSync { /*! \brief SyncMLAdd is class for generating SyncML Add XML object * * Does not support generation of SourceParent and TargetParent elements */ class SyncMLAdd : public SyncMLLocalChange { public: /*! \brief Constructor * * @param aCmdID Command id for this element */ explicit SyncMLAdd( int aCmdID ); /*! \brief Destructor * */ virtual ~SyncMLAdd(); private: }; } #endif // SYNCMLADD_H buteo-syncml-0.5.15/src/syncelements/SyncMLAlert.cpp000066400000000000000000000074201433763642500224040ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLAlert.h" #include "SyncMLMeta.h" #include "SyncMLItem.h" #include "datatypes.h" #include "Fragments.h" using namespace DataSync; SyncMLAlert::SyncMLAlert(CommandParams& aAlertParams) : SyncMLCmdObject( SYNCML_ELEMENT_ALERT ) { SyncMLCmdObject* cmdIdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number(aAlertParams.cmdId) ); addChild(cmdIdObject); SyncMLCmdObject* dataObject = new SyncMLCmdObject( SYNCML_ELEMENT_DATA, aAlertParams.data ); dataObject->setCDATA( true ); addChild(dataObject); if( !aAlertParams.correlator.isEmpty() ) { SyncMLCmdObject* correlatorObject = new SyncMLCmdObject( SYNCML_ELEMENT_CORRELATOR, aAlertParams.correlator ); addChild( correlatorObject ); } for( int i = 0; i < aAlertParams.items.count(); ++i ) { const ItemParams& item = aAlertParams.items[i]; SyncMLItem* itemObject = new SyncMLItem(); if( !item.target.isEmpty() ) { itemObject->insertTarget( item.target ); } if( !item.source.isEmpty() ) { itemObject->insertSource( item.source); } if( !item.meta.anchor.last.isEmpty() || !item.meta.anchor.next.isEmpty() || !item.meta.type.isEmpty() || !item.meta.format.isEmpty() || !item.meta.mark.isEmpty() ) { SyncMLMeta* metaObject = new SyncMLMeta; if( !item.meta.anchor.last.isEmpty() || !item.meta.anchor.next.isEmpty() ) { metaObject->addAnchors( item.meta.anchor.last, item.meta.anchor.next ); } if( !item.meta.type.isEmpty() ) { metaObject->addType( item.meta.type ); } if( !item.meta.format.isEmpty() ) { metaObject->addFormat( item.meta.format ); } if( !item.meta.mark.isEmpty() ) { metaObject->addMark( item.meta.mark ); } itemObject->addChild(metaObject); } if( !item.data.isEmpty() ) { itemObject->insertData( item.data.toUtf8() ); } addChild( itemObject ); } } SyncMLAlert::~SyncMLAlert() { } buteo-syncml-0.5.15/src/syncelements/SyncMLAlert.h000066400000000000000000000041511433763642500220470ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLALERT_H #define SYNCMLALERT_H #include "SyncMLCmdObject.h" namespace DataSync { struct CommandParams; /*! \brief SyncMLAlert is class for generating SyncML Alert XML object */ class SyncMLAlert : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aAlertParams Parameters to use when generating XML object */ explicit SyncMLAlert( CommandParams& aAlertParams ); /*! \brief Destructor * */ ~SyncMLAlert(); private: }; } #endif buteo-syncml-0.5.15/src/syncelements/SyncMLBody.cpp000066400000000000000000000034461433763642500222360ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLBody.h" #include "datatypes.h" using namespace DataSync; SyncMLBody::SyncMLBody() : SyncMLCmdObject( SYNCML_ELEMENT_SYNCBODY ) { } SyncMLBody::~SyncMLBody() { } buteo-syncml-0.5.15/src/syncelements/SyncMLBody.h000066400000000000000000000037671433763642500217110ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLBODY_H #define SYNCMLBODY_H #include "SyncMLCmdObject.h" namespace DataSync { /*! \brief SyncMLBody is class for generating SyncML SyncBody XML object */ class SyncMLBody : public SyncMLCmdObject { public: /*! \brief Constructor * */ SyncMLBody(); /*! \brief Destructor * */ virtual ~SyncMLBody(); private: }; } #endif // SYNCMLBODY_H buteo-syncml-0.5.15/src/syncelements/SyncMLCTCap.cpp000066400000000000000000000057451433763642500222770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLCTCap.h" #include "SyncMLGlobals.h" #include #include "datatypes.h" #include "SyncMLLogging.h" using namespace DataSync; SyncMLCTCap::SyncMLCTCap() : SyncMLCmdObject( SYNCML_ELEMENT_CTCAP ) { } SyncMLCTCap::~SyncMLCTCap() { } void SyncMLCTCap::addCTCap( const QByteArray& aDescription ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QXmlStreamReader reader( aDescription ); while( !reader.atEnd() ) { reader.readNext(); // Ignore the enclosing start and end elements if( reader.name() == SYNCML_ELEMENT_CTCAP ) { continue; } // Convert the found XML elements to SyncMLCmdObjects. if( reader.isStartElement() ) { processElement( reader, this ); } } } void SyncMLCTCap::processElement( QXmlStreamReader& aReader, SyncMLCmdObject* aParent ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncMLCmdObject* obj = new SyncMLCmdObject( aReader.name().toString() ); while( !aReader.atEnd() ) { aReader.readNext(); if( aReader.isStartElement() ) { processElement( aReader, obj ); } else if( aReader.isCharacters() ) { obj->setValue( aReader.text().toString().simplified() ); } else if( aReader.isEndElement() ) { break; } } aParent->addChild( obj ); } buteo-syncml-0.5.15/src/syncelements/SyncMLCTCap.h000066400000000000000000000050351433763642500217340ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLCTCAP_H #define SYNCMLCTCAP_H #include "SyncMLCmdObject.h" class QXmlStreamReader; namespace DataSync { /*! \brief SyncDevInf is a class for generating SyncML CTCap element * */ class SyncMLCTCap : public SyncMLCmdObject { public: /*! \brief Constructor * */ SyncMLCTCap(); /*! \brief Destructor * */ virtual ~SyncMLCTCap(); /*! \brief Adds CTCap description of a single storage plugin in XML form * * In SyncML 1.1, single CTCap element includes the information of every * storage plugin. In SyncML 1.2, CTCap always includes information of * a single storage plugin. The XML-based description given to this * method should have CTCap element as a root parent. * */ void addCTCap( const QByteArray& aDescription ); private: void processElement( QXmlStreamReader& aReader, SyncMLCmdObject* aParent ); }; } #endif // SYNCMLCTCAP_H buteo-syncml-0.5.15/src/syncelements/SyncMLCmdObject.cpp000066400000000000000000000114011433763642500231610ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLCmdObject.h" #include "SyncMLLogging.h" #include "LibWbXML2Encoder.h" #include "QtEncoder.h" #include "datatypes.h" // As this base class is extensively used in SyncML generation, please do not // enable function tracing unless you have a very good reason to do that. // Otherwise, prepare for severe debug spam. using namespace DataSync; SyncMLCmdObject::SyncMLCmdObject( const QString& aName, const QString& aValue ) : iName( aName ), iValue( aValue ), iIsCDATA( false ) { } SyncMLCmdObject::~SyncMLCmdObject() { qDeleteAll(iChildren); iChildren.clear(); } const QString& SyncMLCmdObject::getName() const { return iName; } void SyncMLCmdObject::setName( const QString& aName ) { iName = aName; } const QString& SyncMLCmdObject::getValue() const { return iValue; } void SyncMLCmdObject::setValue( const QString& aValue ) { iValue = aValue; } bool SyncMLCmdObject::getCDATA() const { return iIsCDATA; } void SyncMLCmdObject::setCDATA( bool aCDATA ) { iIsCDATA = aCDATA; } void SyncMLCmdObject::addAttribute( const QString& aName, const QString& aValue ) { iAttributes.insert( aName, aValue ); } const QMap& SyncMLCmdObject::getAttributes() const { return iAttributes; } void SyncMLCmdObject::addChild( SyncMLCmdObject* aChild ) { Q_ASSERT( aChild ); iChildren.append( aChild ); } const QList& SyncMLCmdObject::getChildren() const { return iChildren; } int SyncMLCmdObject::calculateSize(bool aWBXML, const ProtocolVersion& aVersion) { // It should be noted that this is just coarse estimation! Document size limit // is always set to 90% of the maximum available transport size, so this does // not need to be byte-accurate. We gain lots of performance when we don't have // to serialize to XML to check the current size if (aWBXML) { LibWbXML2Encoder encoder; QByteArray aData; if( aVersion == SYNCML_1_1 ) { addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_SYNCML11 ); } else if( aVersion == SYNCML_1_2 ) { addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_SYNCML12 ); } if( encoder.encodeToWbXML( *this, aVersion, aData ) ) { return aData.size(); } } int size = 0; if( iValue.isEmpty() && iChildren.isEmpty() ) { // size += 3 + iName.length(); } else { // + if( iName.length() > 0 ) { size += 5 + 2* iName.length(); } // value size += iValue.length(); // CDATA if( iIsCDATA ) { // size += 12; } for( int i = 0; i < iChildren.count(); ++i ) { size += iChildren[i]->calculateSize(aWBXML, aVersion); } } // attributes ( attr="value" ) QMapIterator i( iAttributes ); while( i.hasNext() ) { i.next(); size += 1 + i.key().length() + 2 + i.value().length() + 1; } return size; } buteo-syncml-0.5.15/src/syncelements/SyncMLCmdObject.h000066400000000000000000000105011433763642500226260ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLCMDOBJECT_H #define SYNCMLCMDOBJECT_H #include #include #include "SyncAgentConsts.h" namespace DataSync { /*! \brief SyncMLCmdObject is the base class for generating * SyncML message tree * */ class SyncMLCmdObject { public: /*! \brief Constructor * * @param aName Name of this element * @param aValue Value of this element */ explicit SyncMLCmdObject( const QString& aName = "", const QString& aValue = "" ); /*! \brief Destructor * */ virtual ~SyncMLCmdObject(); /*! \brief Returns the name of the XML element represented by this object * * @return Name of the XML element */ const QString& getName() const; /*! \brief Sets the name of the XML element represented by this object * * @param aName Name of the XML element */ void setName( const QString& aName ); /*! \brief Returns the value of the XML element represented by this object * * @return Value of the XML element */ const QString& getValue() const; /*! \brief Sets the value of the XML element represented by this object * * @param aValue Value of the XML element */ void setValue( const QString& aValue ); /*! \brief Returns whether the value of the XML element should be written as CDATA * * @return True if value of XML element should be written as CDATA, otherwise false */ bool getCDATA() const; /*! \brief Sets whether the value of the XML element should be written as CDATA * * @param aCDATA True if value of XML element should be written as CDATA, otherwise false */ void setCDATA( bool aCDATA ); /*! \brief Adds an XML attribute * * @param aName Name of the attribute to add * @param aValue Value of the attribute to addl */ void addAttribute( const QString& aName, const QString& aValue ); /*! \brief Returns the XML attributes * * @return XML attributes */ const QMap& getAttributes() const; /*! \brief Adds a child to this element * * @param aChild */ void addChild( SyncMLCmdObject* aChild ); /*! \brief Returns the children of this object * * @return Children of this object */ const QList& getChildren() const; /*! \brief Estimate the size of the present object when formatted as XML object * * @return Estimated size of the object, including all child objects */ int calculateSize(bool aWbXML, const ProtocolVersion& aVersion); protected: private: QString iName; QString iValue; bool iIsCDATA; QMap iAttributes; QList iChildren; }; } Q_DECLARE_TYPEINFO(DataSync::SyncMLCmdObject,Q_COMPLEX_TYPE); #endif // SYNCMLCMDOBJECT_H buteo-syncml-0.5.15/src/syncelements/SyncMLCred.cpp000066400000000000000000000042461433763642500222150ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLCred.h" #include "SyncMLMeta.h" #include "datatypes.h" using namespace DataSync; SyncMLCred::SyncMLCred( const QString& aFormat, const QString& aType, const QByteArray& aData ) : SyncMLCmdObject( SYNCML_ELEMENT_CRED ) { SyncMLMeta* metaObject = new SyncMLMeta(); metaObject->addFormat( aFormat ); metaObject->addType( aType ); addChild( metaObject ); SyncMLCmdObject* dataObject = new SyncMLCmdObject( SYNCML_ELEMENT_DATA, QString::fromUtf8( aData.constData() ) ); addChild( dataObject ); } SyncMLCred::~SyncMLCred() { } buteo-syncml-0.5.15/src/syncelements/SyncMLCred.h000066400000000000000000000042321433763642500216550ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLCRED_H #define SYNCMLCRED_H #include "SyncMLCmdObject.h" namespace DataSync { /*! \brief SyncMLCred is class for generating SyncML Cred XML object */ class SyncMLCred : public SyncMLCmdObject { public: /*!\ brief Constructor * * @param aFormat Format of Cred element * @param aType Type of Cred element * @param aData Data of Cred element */ SyncMLCred( const QString& aFormat, const QString& aType, const QByteArray& aData ); virtual ~SyncMLCred(); protected: private: }; } #endif // SYNCMLCRED_H buteo-syncml-0.5.15/src/syncelements/SyncMLDelete.cpp000066400000000000000000000035021433763642500225340ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLDelete.h" #include "datatypes.h" using namespace DataSync; SyncMLDelete::SyncMLDelete( int aCmdID ) : SyncMLLocalChange( SYNCML_ELEMENT_DELETE, aCmdID ) { } SyncMLDelete::~SyncMLDelete() { } buteo-syncml-0.5.15/src/syncelements/SyncMLDelete.h000066400000000000000000000042541433763642500222060ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLDELETE_H #define SYNCMLDELETE_H #include "SyncMLLocalChange.h" namespace DataSync { /*! \brief SyncMLDelete is class for generating SyncML Delete XML object * * Does not support generation of Archive, SftDel, SourceParent and TargetParent elements */ class SyncMLDelete : public SyncMLLocalChange { public: /*! \brief Constructor * * @param aCmdID Command id for this element */ explicit SyncMLDelete( int aCmdID ); /*! \brief Destructor * */ virtual ~SyncMLDelete(); private: }; } #endif // SYNCMLDELETE_H buteo-syncml-0.5.15/src/syncelements/SyncMLDevInf.cpp000066400000000000000000000303171433763642500225110ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLDevInf.h" #include #include #include "SyncMLGlobals.h" #include "DeviceInfo.h" #include "StoragePlugin.h" #include "SyncMLCTCap.h" #include "SyncMLExt.h" #include "datatypes.h" #include "SyncMLLogging.h" using namespace DataSync; SyncMLDevInf::SyncMLDevInf( const QList &aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole ) : SyncMLCmdObject( SYNCML_ELEMENT_ITEM ), iDeviceInfo( aDeviceInfo ) { SyncMLCmdObject* sourceObject = new SyncMLCmdObject(SYNCML_ELEMENT_SOURCE); SyncMLCmdObject* sourceURIObject = new SyncMLCmdObject(SYNCML_ELEMENT_LOCURI, aVersion == SYNCML_1_2 ? SYNCML_DEVINF_PATH_12 : SYNCML_DEVINF_PATH_11 ); sourceObject->addChild(sourceURIObject); addChild(sourceObject); SyncMLCmdObject* dataObject = new SyncMLCmdObject(SYNCML_ELEMENT_DATA); SyncMLCmdObject* devInfObject = new SyncMLCmdObject(SYNCML_ELEMENT_DEVINF); devInfObject->addAttribute( XML_NAMESPACE,XML_NAMESPACE_VALUE_DEVINF ); SyncMLCmdObject* verDTDObject = new SyncMLCmdObject(SYNCML_ELEMENT_VERDTD, aVersion == SYNCML_1_2 ? SYNCML_DTD_VERSION_1_2 : SYNCML_DTD_VERSION_1_1 ); devInfObject->addChild( verDTDObject ); SyncMLCmdObject* manObject = new SyncMLCmdObject( SYNCML_ELEMENT_MAN, iDeviceInfo.getManufacturer() ); devInfObject->addChild( manObject ); SyncMLCmdObject* modObject = new SyncMLCmdObject( SYNCML_ELEMENT_MOD, iDeviceInfo.getModel() ); devInfObject->addChild( modObject ); SyncMLCmdObject* fwVObject = new SyncMLCmdObject( SYNCML_ELEMENT_FWVERSION, iDeviceInfo.getFirmwareVersion() ); devInfObject->addChild( fwVObject ); SyncMLCmdObject* swVObject = new SyncMLCmdObject( SYNCML_ELEMENT_SWVERSION, iDeviceInfo.getSoftwareVersion() ); devInfObject->addChild( swVObject ); SyncMLCmdObject* hwVObject = new SyncMLCmdObject( SYNCML_ELEMENT_HWVERSION, iDeviceInfo.getHardwareVersion() ); devInfObject->addChild( hwVObject ); SyncMLCmdObject* devIDObject = new SyncMLCmdObject( SYNCML_ELEMENT_DEVID, iDeviceInfo.getDeviceID() ); devInfObject->addChild( devIDObject ); SyncMLCmdObject* devTypObject = new SyncMLCmdObject( SYNCML_ELEMENT_DEVTYPE, iDeviceInfo.getDeviceType() ); devInfObject->addChild( devTypObject ); SyncMLCmdObject* utcObject = new SyncMLCmdObject( SYNCML_ELEMENT_UTC ); devInfObject->addChild( utcObject ); SyncMLCmdObject* supportLargeObjsObject = new SyncMLCmdObject(SYNCML_ELEMENT_SUPPORTLARGEOBJS); devInfObject->addChild( supportLargeObjsObject ); SyncMLCmdObject* nocObject = new SyncMLCmdObject( SYNCML_ELEMENT_SUPPORTNUMBEROFCHANGES ); devInfObject->addChild( nocObject ); // In SyncML 1.1, CTCaps are sent with DevInf element as parent and a single CTCaps element includes // capabilities of every storage plugin. In SyncML 1.2 CTCaps are sent with corresponding // DataStore element as parent if( aVersion == SYNCML_1_1) { SyncMLCTCap* ctcap = NULL; for( int i = 0; i < aDataStores.count(); ++i ) { devInfObject->addChild( generateDataStore( *aDataStores[i], aRole ) ); QByteArray cap = aDataStores[i]->getPluginCTCaps( SYNCML_1_1 ); if( !cap.isEmpty() ) { if( !ctcap ) { ctcap = new SyncMLCTCap(); } ctcap->addCTCap( cap ); } } if( ctcap ) { devInfObject->addChild( ctcap ); } } else if( aVersion == SYNCML_1_2 ) { for( int i = 0; i < aDataStores.count(); ++i ) { SyncMLCmdObject* dataStore = generateDataStore( *aDataStores[i], aRole ); QByteArray cap = aDataStores[i]->getPluginCTCaps( SYNCML_1_2 ); QDomDocument doc; if( !cap.isEmpty() && doc.setContent( cap ) ) { // Make sure that CtCap elements are under one root element named CtCaps. QDomElement root = doc.documentElement(); if ( root.tagName() != SYNCML_ELEMENT_CTCAPS ) { QDomElement newRoot = doc.createElement( SYNCML_ELEMENT_CTCAPS ); newRoot.appendChild( root ); root = newRoot; } QDomElement ctCapElement = root.firstChildElement( SYNCML_ELEMENT_CTCAP ); for ( ; !ctCapElement.isNull(); ctCapElement = ctCapElement.nextSiblingElement( SYNCML_ELEMENT_CTCAP ) ) { QByteArray ctCapData; QTextStream ctCapStream( &ctCapData ); ctCapElement.save( ctCapStream, 1 ); SyncMLCTCap* ctcap = new SyncMLCTCap(); ctcap->addCTCap( ctCapData ); dataStore->addChild( ctcap ); } } devInfObject->addChild( dataStore ); } } //insert Ext if exist QByteArray ext_data; for( int i = 0; i < aDataStores.count(); ++i ) { if (!(aDataStores[i]->getPluginExts().isEmpty())) { ext_data.append(aDataStores[i]->getPluginExts()); } } QDomDocument doc; if(!ext_data.isEmpty() && doc.setContent( ext_data ) ) { // Make sure that Extensions elements are under one root element named Ext. QDomElement root = doc.documentElement(); if ( root.tagName() != SYNCML_ELEMENT_EXT ) { QDomElement newRoot = doc.createElement( SYNCML_ELEMENT_EXT ); newRoot.appendChild( root ); root = newRoot; } qCDebug(lcSyncML) << Q_FUNC_INFO << "Ext Root generated"; for ( ; !root.isNull(); root = root.nextSiblingElement( SYNCML_ELEMENT_EXT ) ) { QTextStream extStream( &ext_data ); root.save( extStream, 1 ); SyncMLExt* ext_dom = new SyncMLExt(); ext_dom->addExt(ext_data ); devInfObject->addChild( ext_dom ); qCDebug(lcSyncML) << Q_FUNC_INFO << "Added child generated" << ext_data; } } dataObject->addChild( devInfObject ); addChild( dataObject ); } SyncMLDevInf::~SyncMLDevInf() { } SyncMLCmdObject* SyncMLDevInf::generateDataStore( const StoragePlugin& aPlugin, const Role& aRole ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncMLCmdObject* dataStoreObject = new SyncMLCmdObject(SYNCML_ELEMENT_DATASTORE); SyncMLCmdObject* sourceRef = new SyncMLCmdObject( SYNCML_ELEMENT_SOURCEREF, aPlugin.getSourceURI() ); dataStoreObject->addChild( sourceRef ); // If in client mode, send maximum GUID size if( aRole == ROLE_CLIENT ) { SyncMLCmdObject* maxGUIDSize = new SyncMLCmdObject( SYNCML_ELEMENT_MAXGUIDSIZE, SYNCML_DSINFO_MAXGUIDSIZE ); dataStoreObject->addChild( maxGUIDSize ); } const ContentFormat& rxPref = aPlugin.getFormatInfo().getPreferredRx(); if( !rxPref.iType.isEmpty() ) { SyncMLCmdObject *rxPrefObject = new SyncMLCmdObject(SYNCML_ELEMENT_RX_PREF); SyncMLCmdObject* rxCTTypeObject = new SyncMLCmdObject( SYNCML_ELEMENT_CTTYPE, rxPref.iType ); rxPrefObject->addChild( rxCTTypeObject ); SyncMLCmdObject* rxVerCTObject = new SyncMLCmdObject( SYNCML_ELEMENT_VERCT, rxPref.iVersion ); rxPrefObject->addChild( rxVerCTObject ); dataStoreObject->addChild( rxPrefObject ); } const ContentFormat& txPref = aPlugin.getFormatInfo().getPreferredTx(); if( !txPref.iType.isEmpty() ) { SyncMLCmdObject *txPrefObject = new SyncMLCmdObject(SYNCML_ELEMENT_TX_PREF); SyncMLCmdObject* txCTTypeObject = new SyncMLCmdObject( SYNCML_ELEMENT_CTTYPE, txPref.iType); txPrefObject->addChild( txCTTypeObject ); SyncMLCmdObject* txVerCTObject = new SyncMLCmdObject( SYNCML_ELEMENT_VERCT, txPref.iVersion ); txPrefObject->addChild( txVerCTObject ); dataStoreObject->addChild( txPrefObject ); } const QList& rx = aPlugin.getFormatInfo().rx(); for( int i = 0; i < rx.count(); ++i ) { const ContentFormat& format = rx[i]; SyncMLCmdObject *rxObject = new SyncMLCmdObject(SYNCML_ELEMENT_RX); SyncMLCmdObject* rxCTTypeObject = new SyncMLCmdObject( SYNCML_ELEMENT_CTTYPE, format.iType ); rxObject->addChild( rxCTTypeObject ); SyncMLCmdObject* rxVerCTObject = new SyncMLCmdObject( SYNCML_ELEMENT_VERCT, format.iVersion ); rxObject->addChild( rxVerCTObject ); dataStoreObject->addChild( rxObject ); } const QList& tx = aPlugin.getFormatInfo().tx(); for( int i = 0; i < tx.count(); ++i ) { const ContentFormat& format = tx[i]; SyncMLCmdObject *txObject = new SyncMLCmdObject(SYNCML_ELEMENT_TX); SyncMLCmdObject* txCTTypeObject = new SyncMLCmdObject( SYNCML_ELEMENT_CTTYPE, format.iType); txObject->addChild( txCTTypeObject ); SyncMLCmdObject* txVerCTObject = new SyncMLCmdObject( SYNCML_ELEMENT_VERCT, format.iVersion ); txObject->addChild( txVerCTObject ); dataStoreObject->addChild( txObject ); } SyncMLCmdObject* syncCapObject = new SyncMLCmdObject(SYNCML_ELEMENT_SYNCCAP); QList syncTypes; // Two-way sync syncTypes.append( SYNCTYPE_TWOWAY ); // Slow two-way sync syncTypes.append( SYNCTYPE_TWOWAYSLOW ); // One-way sync from client only syncTypes.append( SYNCTYPE_FROMCLIENT ); // Refresh sync from client only syncTypes.append( SYNCTYPE_FROMCLIENTSLOW ); // One-way sync from server only syncTypes.append( SYNCTYPE_FROMSERVER ); // Refresh sync from server only syncTypes.append( SYNCTYPE_FROMSERVERSLOW ); // Server alerted sync syncTypes.append( SYNCTYPE_SERVERALERTED ); for( int i = 0; i < syncTypes.count(); ++i ) { SyncMLCmdObject* syncType = new SyncMLCmdObject( SYNCML_ELEMENT_SYNCTYPE, QString::number( syncTypes[i] )); syncCapObject->addChild( syncType ); } dataStoreObject->addChild( syncCapObject ); return dataStoreObject; } buteo-syncml-0.5.15/src/syncelements/SyncMLDevInf.h000066400000000000000000000052011433763642500221500ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLDEVINF_H #define SYNCMLDEVINF_H #include "SyncMLCmdObject.h" #include "SyncAgentConsts.h" #include "datatypes.h" namespace DataSync { class StoragePlugin; class DeviceInfo; /*! \brief SyncDevInf is a class for generating SyncML 1.1 and 1.2 DevInf Item * element * */ class SyncMLDevInf : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aDataStores Data stores available to use in generation * @param aDeviceInfo Device info object * @param aVersion Protocol version to use * @param aRole Role in use */ SyncMLDevInf( const QList &aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole ); /*! \brief Destructor * */ virtual ~SyncMLDevInf(); protected: private: const DeviceInfo& iDeviceInfo; SyncMLCmdObject* generateDataStore( const StoragePlugin& aPlugin, const Role& aRole ); }; } #endif /* SYNCMLDEVINF_H */ buteo-syncml-0.5.15/src/syncelements/SyncMLExt.cpp000066400000000000000000000056411433763642500221000ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLExt.h" #include #include "datatypes.h" #include "SyncMLLogging.h" using namespace DataSync; SyncMLExt::SyncMLExt() : SyncMLCmdObject( SYNCML_ELEMENT_EXT ) { } SyncMLExt::~SyncMLExt() { } void SyncMLExt::addExt(const QByteArray &aDescription) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QXmlStreamReader reader( aDescription ); while( !reader.atEnd() ) { reader.readNext(); // Ignore the enclosing start and end elements if( reader.name() == SYNCML_ELEMENT_EXT ) { continue; } // Convert the found XML elements to SyncMLCmdObjects. if( reader.isStartElement() ) { processElement( reader, this ); } } } void SyncMLExt::processElement( QXmlStreamReader& aReader, SyncMLCmdObject* aParent ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); SyncMLCmdObject* obj = new SyncMLCmdObject( aReader.name().toString() ); while( !aReader.atEnd() ) { aReader.readNext(); if( aReader.isStartElement() ) { processElement( aReader, obj ); } else if( aReader.isCharacters() ) { obj->setValue( aReader.text().toString().simplified() ); } else if( aReader.isEndElement() ) { break; } } aParent->addChild( obj ); } buteo-syncml-0.5.15/src/syncelements/SyncMLExt.h000066400000000000000000000043571433763642500215500ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLEXT_H #define SYNCMLEXT_H #include "SyncMLCmdObject.h" class QXmlStreamReader; namespace DataSync { /*! \brief SyncDevInf is a class for generating SyncML Ext element * */ class SyncMLExt : public SyncMLCmdObject { public: /*! \brief Constructor * */ SyncMLExt(); /*! \brief Destructor * */ virtual ~SyncMLExt(); /*! \brief Add a new Ext * * @param aDescription Document containing Ext information * */ void addExt( const QByteArray& aDescription ); private: void processElement( QXmlStreamReader& aReader, SyncMLCmdObject* aParent ); }; } #endif // SYNCMLEXT_H buteo-syncml-0.5.15/src/syncelements/SyncMLGet.cpp000066400000000000000000000047601433763642500220600ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLGet.h" #include "SyncMLMeta.h" #include "datatypes.h" using namespace DataSync; SyncMLGet::SyncMLGet( int aCmdID, const QString& aType, const QString& aTarget ) : SyncMLCmdObject( SYNCML_ELEMENT_GET ) { SyncMLCmdObject* cmdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number( aCmdID ) ); addChild( cmdObject ); SyncMLMeta* metaObject = new SyncMLMeta; metaObject->addType( aType ); addChild( metaObject ); SyncMLCmdObject* item = new SyncMLCmdObject(SYNCML_ELEMENT_ITEM); SyncMLCmdObject* targetObject = new SyncMLCmdObject( SYNCML_ELEMENT_TARGET ); SyncMLCmdObject* locURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aTarget ); targetObject->addChild( locURIObject ); item->addChild( targetObject ); addChild( item ); } SyncMLGet::~SyncMLGet() { } buteo-syncml-0.5.15/src/syncelements/SyncMLGet.h000066400000000000000000000042721433763642500215230ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLGET_H #define SYNCMLGET_H #include "SyncMLCmdObject.h" namespace DataSync { /*! \brief SyncMLGet is a class for generating SyncML Get XML object * */ class SyncMLGet : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aCmdID Command id for this element * @param aType Type metadata for this element * @param aTarget Targe LoccURI for this element */ SyncMLGet( int aCmdID, const QString& aType, const QString& aTarget ); /*! \brief Destructor * */ virtual ~SyncMLGet(); }; } #endif // SYNCMLGET_H buteo-syncml-0.5.15/src/syncelements/SyncMLHdr.cpp000066400000000000000000000102511433763642500220460ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLHdr.h" #include "SyncMLMeta.h" #include "datatypes.h" #include "Fragments.h" using namespace DataSync; SyncMLHdr::SyncMLHdr( const HeaderParams& aHeaderParams ) : SyncMLCmdObject(SYNCML_ELEMENT_SYNCHDR) { SyncMLCmdObject* verDTDObject = new SyncMLCmdObject( SYNCML_ELEMENT_VERDTD, aHeaderParams.verDTD ); addChild(verDTDObject); SyncMLCmdObject* verProtoObject = new SyncMLCmdObject( SYNCML_ELEMENT_VERPROTO, aHeaderParams.verProto ); addChild(verProtoObject); SyncMLCmdObject* sessionIDObject = new SyncMLCmdObject( SYNCML_ELEMENT_SESSIONID, aHeaderParams.sessionID ); addChild(sessionIDObject); SyncMLCmdObject* msgIDObject = new SyncMLCmdObject( SYNCML_ELEMENT_MSGID, QString::number(aHeaderParams.msgID) ); addChild(msgIDObject); SyncMLCmdObject* targetObject = new SyncMLCmdObject(SYNCML_ELEMENT_TARGET); SyncMLCmdObject* targetURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aHeaderParams.targetDevice ); targetObject->addChild(targetURIObject); addChild(targetObject); SyncMLCmdObject* sourceObject = new SyncMLCmdObject(SYNCML_ELEMENT_SOURCE); SyncMLCmdObject* sourceURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aHeaderParams.sourceDevice); sourceObject->addChild(sourceURIObject); addChild(sourceObject); if( !aHeaderParams.respURI.isEmpty() ) { SyncMLCmdObject *respURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_RESPURI, aHeaderParams.respURI ); addChild( respURIObject ); } if( aHeaderParams.meta.maxMsgSize > 0 || aHeaderParams.meta.maxObjSize > 0 || aHeaderParams.meta.EMI.size() > 0 ) { SyncMLMeta* metaObject = new SyncMLMeta; if( aHeaderParams.meta.maxMsgSize > 0 ) { metaObject->addMaxMsgSize( aHeaderParams.meta.maxMsgSize ); } if( aHeaderParams.meta.maxObjSize > 0 ) { metaObject->addMaxObjSize( aHeaderParams.meta.maxObjSize ); } for( int i = 0; i < aHeaderParams.meta.EMI.size(); ++i ) { metaObject->addEMI( aHeaderParams.meta.EMI[i] ); } addChild(metaObject); } } SyncMLHdr::~SyncMLHdr() { } buteo-syncml-0.5.15/src/syncelements/SyncMLHdr.h000066400000000000000000000041541433763642500215200ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLHDR_H #define SYNCMLHDR_H #include "SyncMLCmdObject.h" namespace DataSync { struct HeaderParams; /*! \brief SyncMLHdr is class for generating SyncML SyncHdr XML object */ class SyncMLHdr : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aHeaderParams SyncML header parameters to use * */ SyncMLHdr( const HeaderParams& aHeaderParams ); /*! \brief Destructor * */ virtual ~SyncMLHdr(); private: }; } #endif // SYNCMLHDR_H buteo-syncml-0.5.15/src/syncelements/SyncMLItem.cpp000066400000000000000000000074111433763642500222330ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLItem.h" #include "datatypes.h" using namespace DataSync; SyncMLItem::SyncMLItem() : SyncMLCmdObject( SYNCML_ELEMENT_ITEM ) { } SyncMLItem::~SyncMLItem() { } void SyncMLItem::insertTarget( const SyncItemKey& aLocURI ) { SyncMLCmdObject* targetObject = new SyncMLCmdObject( SYNCML_ELEMENT_TARGET ); SyncMLCmdObject* locURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aLocURI ); targetObject->addChild( locURIObject ); addChild( targetObject ); } void SyncMLItem::insertSource( const SyncItemKey& aLocURI ) { SyncMLCmdObject* sourceObject = new SyncMLCmdObject( SYNCML_ELEMENT_SOURCE ); SyncMLCmdObject* locURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aLocURI ); sourceObject->addChild( locURIObject ); addChild( sourceObject ); } void SyncMLItem::insertTargetParent( const SyncItemKey& aLocURI ) { SyncMLCmdObject* targetObject = new SyncMLCmdObject( SYNCML_ELEMENT_TARGETPARENT ); SyncMLCmdObject* locURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aLocURI ); targetObject->addChild( locURIObject ); addChild( targetObject ); } void SyncMLItem::insertSourceParent( const SyncItemKey& aLocURI ) { SyncMLCmdObject* sourceObject = new SyncMLCmdObject( SYNCML_ELEMENT_SOURCEPARENT ); SyncMLCmdObject* locURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aLocURI ); sourceObject->addChild( locURIObject ); addChild( sourceObject ); } void SyncMLItem::insertData( const QByteArray& aData ) { // Data is always encoded in UTF-8, so make sure it's being read as such instead // of default behavior of latin QString data = QString::fromUtf8( aData.constData() ); SyncMLCmdObject* dataObject = new SyncMLCmdObject( SYNCML_ELEMENT_DATA, data ); dataObject->setCDATA( true ); addChild( dataObject ); } void SyncMLItem::insertData( SyncMLCmdObject* aData ) { SyncMLCmdObject* dataObject = new SyncMLCmdObject( SYNCML_ELEMENT_DATA ); dataObject->addChild( aData ); addChild( dataObject ); } void SyncMLItem::insertMoreData() { SyncMLCmdObject* moreDataObject = new SyncMLCmdObject( SYNCML_ELEMENT_MOREDATA ); addChild( moreDataObject ); } buteo-syncml-0.5.15/src/syncelements/SyncMLItem.h000066400000000000000000000065541433763642500217070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLITEM_H #define SYNCMLITEM_H #include "SyncMLCmdObject.h" #include "SyncItemKey.h" namespace DataSync { /*! \brief SyncMLItem is class for generating SyncML Item XML object */ class SyncMLItem : public SyncMLCmdObject { public: /*! \brief Constructor * */ SyncMLItem(); /*! \brief Destructor * */ virtual ~SyncMLItem(); /*! \brief Insert Target object as a child * * @param aLocURI Target locURI */ void insertTarget( const SyncItemKey& aLocURI ); /*! \brief Insert Source object as a child * * @param aLocURI Source locURI */ void insertSource( const SyncItemKey& aLocURI ); /*! \brief Insert TargetParent object as a child * * @param aLocURI TargetParent locURI */ void insertTargetParent( const SyncItemKey& aLocURI ); /*! \brief Insert SourceParent object as a child * * @param aLocURI SourceParent locURI */ void insertSourceParent( const SyncItemKey& aLocURI ); /*! \brief Insert Data object consisting of character data * as a child * * @param aData Character data to use */ void insertData( const QByteArray& aData ); /*! \brief Insert Data object consisting of mark-up data * as a child * * @param aData Mark-up data to use */ void insertData( SyncMLCmdObject* aData ); /*! \brief Insert MoreData object as a child * * MoreData object should be used when inserted data is only a part of the actual data of an item. * In other words, with large objects MoreData should be used to signal remote device that more data * should be expected * */ void insertMoreData(); protected: private: }; } #endif // SYNCMLITEM_H buteo-syncml-0.5.15/src/syncelements/SyncMLLocalChange.cpp000066400000000000000000000055761433763642500235070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLLocalChange.h" #include "SyncMLMeta.h" #include "datatypes.h" using namespace DataSync; SyncMLLocalChange::SyncMLLocalChange( const QString &aElementName, int aCmdID ) : SyncMLCmdObject( aElementName ), iMetaObject( NULL ) { addChild( generateCmdElement( aCmdID ) ); } SyncMLLocalChange::~SyncMLLocalChange() { } void SyncMLLocalChange::addMimeMetadata( const QString& aMimeType ) { ensureMetaElement(); iMetaObject->addType( aMimeType ); } void SyncMLLocalChange::addSizeMetadata( const qint64 aSize ) { ensureMetaElement(); iMetaObject->addSize( aSize ); } void SyncMLLocalChange::addFormatMetadata( const QString& aFormat ) { ensureMetaElement(); iMetaObject->addFormat( aFormat ); } SyncMLCmdObject* SyncMLLocalChange::generateCmdElement( int aCmdID ) const { SyncMLCmdObject* cmdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number( aCmdID ) ); return cmdObject; } void SyncMLLocalChange::ensureMetaElement() { if( !iMetaObject ) { iMetaObject = new SyncMLMeta(); addChild( iMetaObject ); } } void SyncMLLocalChange::addVersionMetadata(const QString& aVersion) { ensureMetaElement(); iMetaObject->addVersion(aVersion); } buteo-syncml-0.5.15/src/syncelements/SyncMLLocalChange.h000066400000000000000000000061461433763642500231460ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLLOCALCHANGE_H #define SYNCMLLOCALCHANGE_H #include "SyncMLCmdObject.h" namespace DataSync { class SyncMLMeta; /*! \brief SyncMLLocalChange is a base class for SyncML XML objects * related to local changes ( Add, Delete, Replace commands ) */ class SyncMLLocalChange : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aElementName Name of this element. Filled out by derived class * @param aCmdID Command id for this element */ SyncMLLocalChange( const QString &aElementName, int aCmdID ); /*! \brief Destructor * */ virtual ~SyncMLLocalChange(); /*! \brief Adds metadata element as child about content mime * * @param aMimeType Mime type of the content */ void addMimeMetadata( const QString& aMimeType ); /*! \brief Adds metadata element as child about content size * * @param aSize Size of the content */ void addSizeMetadata( const qint64 aSize ); /*! \brief Adds metadata element as child about content format * * @param aFormat Format of the content */ void addFormatMetadata( const QString& aFormat ); /*! \brief Adds version meta element as child about content format * * @param aVersion of the content */ void addVersionMetadata(const QString& aVersion); protected: private: SyncMLCmdObject* generateCmdElement( int aCmdID ) const; void ensureMetaElement(); SyncMLMeta* iMetaObject; }; } #endif // SYNCMLLOCALCHANGE_H buteo-syncml-0.5.15/src/syncelements/SyncMLLocalChanges.cpp000066400000000000000000000056401433763642500236620ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLLocalChanges.h" #include "datatypes.h" using namespace DataSync; SyncMLLocalChanges::SyncMLLocalChanges( const QString &aElementName, int aCmdID, const QString& aTarget, const QString& aSource ) : SyncMLCmdObject( aElementName ) { SyncMLCmdObject* cmdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number( aCmdID ) ); addChild( cmdObject ); addChild( generateTargetElement( aTarget ) ); addChild( generateSourceElement( aSource ) ); } SyncMLLocalChanges::~SyncMLLocalChanges() { } SyncMLCmdObject* SyncMLLocalChanges::generateTargetElement( const QString& aTargetDB ) { SyncMLCmdObject* targetLocURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aTargetDB ); SyncMLCmdObject* targetObject = new SyncMLCmdObject( SYNCML_ELEMENT_TARGET ); targetObject->addChild( targetLocURIObject ); return targetObject; } SyncMLCmdObject* SyncMLLocalChanges::generateSourceElement( const QString& aSourceDB ) { SyncMLCmdObject* sourceLocURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aSourceDB ); SyncMLCmdObject* sourceObject = new SyncMLCmdObject( SYNCML_ELEMENT_SOURCE ); sourceObject->addChild( sourceLocURIObject ); return sourceObject; } buteo-syncml-0.5.15/src/syncelements/SyncMLLocalChanges.h000066400000000000000000000050441433763642500233250ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLLOCALCHANGES_H #define SYNCMLLOCALCHANGES_H #include "SyncMLCmdObject.h" namespace DataSync { /*! \brief SyncMLLocalChanges is a base class for SyncML XML objects * related to local change containers ( Sync and Map commands ) */ class SyncMLLocalChanges : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aElementName Name of this element * @param aCmdID Command id for this element * @param aTarget Target database URI * @param aSource Source database URI */ SyncMLLocalChanges( const QString &aElementName, int aCmdID, const QString& aTarget, const QString& aSource ); /*! \brief Destructor * */ virtual ~SyncMLLocalChanges(); protected: private: SyncMLCmdObject* generateTargetElement( const QString& aTarget ); SyncMLCmdObject* generateSourceElement( const QString& aSource ); }; } #endif // SYNCMLLOCALCHANGES_H buteo-syncml-0.5.15/src/syncelements/SyncMLMap.cpp000066400000000000000000000035631433763642500220560ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMap.h" #include "datatypes.h" using namespace DataSync; SyncMLMap::SyncMLMap( int aCmdID, const QString& aTarget, const QString& aSource ) : SyncMLLocalChanges( SYNCML_ELEMENT_MAP, aCmdID, aTarget, aSource ) { } SyncMLMap::~SyncMLMap() { } buteo-syncml-0.5.15/src/syncelements/SyncMLMap.h000066400000000000000000000042631433763642500215210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMAP_H #define SYNCMLMAP_H #include "SyncMLLocalChanges.h" namespace DataSync { /*! \brief SyncMLMap is class for generating SyncML Map XML object */ class SyncMLMap : public SyncMLLocalChanges { public: /*! \brief Constructor * * @param aCmdID Command id for this element * @param aTarget Target database URI * @param aSource Source database URI */ SyncMLMap( int aCmdID, const QString& aTarget, const QString& aSource ); /*! \brief Destructor * */ virtual ~SyncMLMap(); private: }; } #endif // SYNCMLMAP_H buteo-syncml-0.5.15/src/syncelements/SyncMLMapItem.cpp000066400000000000000000000045521433763642500226740ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMapItem.h" #include "datatypes.h" using namespace DataSync; SyncMLMapItem::SyncMLMapItem( const QString& aGUID, const SyncItemKey& aLUID ) : SyncMLCmdObject( SYNCML_ELEMENT_MAPITEM ) { SyncMLCmdObject* targetLocURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aGUID ); SyncMLCmdObject* targetObject = new SyncMLCmdObject( SYNCML_ELEMENT_TARGET ); targetObject->addChild( targetLocURIObject ); addChild( targetObject ); SyncMLCmdObject* sourceLocURIObject = new SyncMLCmdObject( SYNCML_ELEMENT_LOCURI, aLUID ); SyncMLCmdObject* sourceObject = new SyncMLCmdObject( SYNCML_ELEMENT_SOURCE ); sourceObject->addChild( sourceLocURIObject ); addChild( sourceObject ); } SyncMLMapItem::~SyncMLMapItem() { } buteo-syncml-0.5.15/src/syncelements/SyncMLMapItem.h000066400000000000000000000043321433763642500223350ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMAPITEM_H #define SYNCMLMAPITEM_H #include "SyncMLCmdObject.h" #include "SyncItemKey.h" namespace DataSync { /*! \brief SyncMLMapItem is class for generating SyncML MapItem XML object */ class SyncMLMapItem : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aGUID Global UID of an item assigned by server * @param aLUID Local UID of an item assigned by client */ SyncMLMapItem( const QString& aGUID, const SyncItemKey& aLUID ); /*! \brief Destructor * */ virtual ~SyncMLMapItem(); protected: private: }; } #endif // SYNCMLMAPITEM_H buteo-syncml-0.5.15/src/syncelements/SyncMLMessage.cpp000066400000000000000000000054741433763642500227300ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMessage.h" #include "datatypes.h" #include "Fragments.h" #include "SyncMLHdr.h" #include "SyncMLBody.h" using namespace DataSync; SyncMLMessage::SyncMLMessage( const HeaderParams& aHeaderParams, ProtocolVersion aProtocolVersion) : SyncMLCmdObject(SYNCML_ELEMENT_SYNCML ), iMsgId( aHeaderParams.msgID ), iCmdId( 0 ), iProtocolVersion( aProtocolVersion ) { if( iProtocolVersion == SYNCML_1_1 ) { addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_SYNCML11 ); } else if( iProtocolVersion == SYNCML_1_2 ) { addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_SYNCML12 ); } iSyncHdr = new SyncMLHdr( aHeaderParams ); addChild( iSyncHdr ); iSyncBody = new SyncMLBody(); addChild( iSyncBody ); } SyncMLMessage::~SyncMLMessage() { } void SyncMLMessage::addToHeader( SyncMLCmdObject* aObject ) { iSyncHdr->addChild( aObject ); } void SyncMLMessage::addToBody( SyncMLCmdObject* aObject ) { iSyncBody->addChild( aObject ); } int SyncMLMessage::getNextCmdId() { return ++iCmdId; } int SyncMLMessage::getMsgId() const { return iMsgId; } ProtocolVersion SyncMLMessage::getProtocolVersion() const { return iProtocolVersion; } buteo-syncml-0.5.15/src/syncelements/SyncMLMessage.h000066400000000000000000000062441433763642500223710ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMESSAGE_H #define SYNCMLMESSAGE_H #include "SyncMLCmdObject.h" #include "SyncAgentConsts.h" namespace DataSync { class SyncMLHdr; class SyncMLBody; struct HeaderParams; /*! \brief SyncMLMessage is class for generating SyncML root XML object */ class SyncMLMessage : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aHeaderParams SyncML header parameters * @param aProtocolVersion Protocol version to use */ SyncMLMessage( const HeaderParams& aHeaderParams, ProtocolVersion aProtocolVersion ); /*! \brief Destructor * */ virtual ~SyncMLMessage(); /*! \brief Adds object to message header as a child * * @param aObject Object to add */ void addToHeader( SyncMLCmdObject* aObject ); /*! \brief Adds object to message body as a child * * @param aObject Object to add */ void addToBody( SyncMLCmdObject* aObject ); /*! \brief Assigns a command id that next command added to this * message should use * * @return */ int getNextCmdId(); /*! \brief Returns message id of this message * * @return */ int getMsgId() const; /*! \brief Returns the protocol version of this message * * @return Protocol version of this message */ ProtocolVersion getProtocolVersion() const; protected: private: const int iMsgId; int iCmdId; ProtocolVersion iProtocolVersion; SyncMLHdr* iSyncHdr; SyncMLBody* iSyncBody; }; } #endif // SYNCMLMESSAGE_H buteo-syncml-0.5.15/src/syncelements/SyncMLMeta.cpp000066400000000000000000000112431433763642500222210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMeta.h" #include "datatypes.h" using namespace DataSync; // @todo: The version information inside meta tag is not currently being written // to the ougoing SyncML messages (Although the information is put in the // SyncItem's for incoming messages). This may have to be changed in the future. SyncMLMeta::SyncMLMeta() : SyncMLCmdObject( SYNCML_ELEMENT_META) { } SyncMLMeta::~SyncMLMeta() { } void SyncMLMeta::addType( const QString& aType ) { SyncMLCmdObject* typeObject = new SyncMLCmdObject( SYNCML_ELEMENT_TYPE, aType ); addNamespace( *typeObject ); addChild( typeObject ); } void SyncMLMeta::addSize( qint64 aSize ) { SyncMLCmdObject* sizeObject = new SyncMLCmdObject( SYNCML_ELEMENT_SIZE, QString::number( aSize )); addNamespace( *sizeObject ); addChild( sizeObject ); } void SyncMLMeta::addFormat( const QString& aFormat ) { SyncMLCmdObject* formatObject = new SyncMLCmdObject( SYNCML_ELEMENT_FORMAT, aFormat ); addNamespace( *formatObject ); addChild( formatObject ); } void SyncMLMeta::addAnchors( const QString& aLastAnchor, const QString& aNextAnchor ) { SyncMLCmdObject* anchorObject = new SyncMLCmdObject(SYNCML_ELEMENT_ANCHOR); addNamespace( *anchorObject ); SyncMLCmdObject* lastAnchorObject = new SyncMLCmdObject( SYNCML_ELEMENT_LAST, aLastAnchor ); addNamespace( *lastAnchorObject ); anchorObject->addChild(lastAnchorObject); SyncMLCmdObject* nextAnchorObject = new SyncMLCmdObject( SYNCML_ELEMENT_NEXT, aNextAnchor ); addNamespace( *nextAnchorObject ); anchorObject->addChild(nextAnchorObject); addChild( anchorObject ); } void SyncMLMeta::addMaxMsgSize( qint64 aMaxMsgSize ) { SyncMLCmdObject* maxMsgSizeObject = new SyncMLCmdObject( SYNCML_ELEMENT_MAXMSGSIZE, QString::number( aMaxMsgSize ) ); addNamespace( *maxMsgSizeObject ); addChild( maxMsgSizeObject ); } void SyncMLMeta::addMaxObjSize( qint64 aMaxObjSize ) { SyncMLCmdObject* maxObjSizeObject = new SyncMLCmdObject( SYNCML_ELEMENT_MAXOBJSIZE, QString::number( aMaxObjSize ) ); addNamespace( *maxObjSizeObject ); addChild( maxObjSizeObject ); } void SyncMLMeta::addEMI( const QString& aEMI ) { SyncMLCmdObject* emiObject = new SyncMLCmdObject( SYNCML_ELEMENT_EMI, aEMI ); addNamespace( *emiObject ); addChild( emiObject ); } void SyncMLMeta::addNextNonce( const QString& aNextNonce ) { SyncMLCmdObject* nonceObject = new SyncMLCmdObject( SYNCML_ELEMENT_NEXTNONCE, aNextNonce ); addNamespace( *nonceObject ); addChild( nonceObject ); } void SyncMLMeta::addMark( const QString& aMark ) { SyncMLCmdObject* markObject = new SyncMLCmdObject( SYNCML_ELEMENT_MARK, aMark ); addNamespace( *markObject ); addChild( markObject ); } void SyncMLMeta::addNamespace( SyncMLCmdObject& aObject ) { aObject.addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_METINF ); } void SyncMLMeta::addVersion( const QString& aVersion ) { SyncMLCmdObject* versionObject = new SyncMLCmdObject( SYNCML_ELEMENT_VERSION, aVersion ); addNamespace( *versionObject ); addChild( versionObject ); } buteo-syncml-0.5.15/src/syncelements/SyncMLMeta.h000066400000000000000000000075441433763642500216770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMETA_H #define SYNCMLMETA_H #include "SyncMLCmdObject.h" namespace DataSync { /*! \brief SyncMLMeta is class for generating SyncML Meta XML object */ class SyncMLMeta : public SyncMLCmdObject { public: /*! \brief Constructor * */ SyncMLMeta(); /*! \brief Destructor * */ virtual ~SyncMLMeta(); /*! \brief Adds metadata element as child about type. This can be * for example content (MIME) type, or authentication type * * @param aType Type value */ void addType( const QString& aType ); /*! \brief Adds metadata element as child about content size * * @param aSize Size of the content */ void addSize( qint64 aSize ); /*! \brief Adds metadata element as child about content format * * @param aFormat Format of the content */ void addFormat( const QString& aFormat ); /*! \brief Adds metadata element as child about sync anchors * * @param aLastAnchor Last sync anchor. If empty, Last element is omitted * @param aNextAnchor Next sync anchor. If empty, Next element is omitted */ void addAnchors( const QString& aLastAnchor, const QString& aNextAnchor ); /*! \brief Adds metadata element as child about maximum message size * * @param aMaxMsgSize Maximum message size */ void addMaxMsgSize( qint64 aMaxMsgSize ); /*! \brief Adds metadata element as child about maximum object size * * @param aMaxObjSize Maximum object size */ void addMaxObjSize( qint64 aMaxObjSize ); /*! \brief Adds metadata element as child about EMI * * @param aEMI EMI field */ void addEMI( const QString& aEMI ); /*! \brief Adds metadata element as child about nonce for md5 authentication * * @param aNextNonce NextNonce field */ void addNextNonce( const QString& aNextNonce ); /*! \brief Adds metadat element as a child about mark * * @param aMark aMark field */ void addMark( const QString& aMark ); /*! \brief Adds version element as a child. * * @param aVersion field */ void addVersion( const QString& aVersion ); protected: private: void addNamespace( SyncMLCmdObject& aObject ); }; } #endif buteo-syncml-0.5.15/src/syncelements/SyncMLPut.cpp000066400000000000000000000047171433763642500221130ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLPut.h" #include "datatypes.h" #include "SyncMLMeta.h" #include "SyncMLDevInf.h" using namespace DataSync; SyncMLPut::SyncMLPut( int aCmdID, const QList &aDataStores, const DeviceInfo& aDeviceInfo, ProtocolVersion aVersion, Role aRole ) : SyncMLCmdObject( SYNCML_ELEMENT_PUT ) { SyncMLCmdObject* cmdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number( aCmdID ) ); addChild( cmdObject ); SyncMLMeta* metaObject = new SyncMLMeta; metaObject->addType( SYNCML_CONTTYPE_DEVINF_XML ); addChild( metaObject ); SyncMLDevInf* devInf = new SyncMLDevInf( aDataStores, aDeviceInfo, aVersion, aRole ); addChild( devInf ); } SyncMLPut::~SyncMLPut() { } buteo-syncml-0.5.15/src/syncelements/SyncMLPut.h000066400000000000000000000050461433763642500215540ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLPUT_H #define SYNCMLPUT_H #include "SyncMLCmdObject.h" #include "SyncAgentConsts.h" #include "datatypes.h" namespace DataSync { class StoragePlugin; class DeviceInfo; /*! \brief SyncMLPut is a class for generating SyncML Put XML object * used for sending device information */ class SyncMLPut : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aCmdID Command id for this element * @param aDataStores Datastores available to use in generation * @param aDeviceInfo Device info object * @param aVersion Protocol version to use * @param aRole Role in use */ SyncMLPut( int aCmdID, const QList &aDataStores, const DeviceInfo& aDeviceInfo, ProtocolVersion aVersion, Role aRole ); /*! \brief Destructor * */ virtual ~SyncMLPut(); protected: private: }; } #endif // SYNCMLPUT_H buteo-syncml-0.5.15/src/syncelements/SyncMLReplace.cpp000066400000000000000000000035101433763642500227040ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLReplace.h" #include "datatypes.h" using namespace DataSync; SyncMLReplace::SyncMLReplace( int aCmdID ) : SyncMLLocalChange( SYNCML_ELEMENT_REPLACE, aCmdID ) { } SyncMLReplace::~SyncMLReplace() { } buteo-syncml-0.5.15/src/syncelements/SyncMLReplace.h000066400000000000000000000042621433763642500223560ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLREPLACE_H #define SYNCMLREPLACE_H #include "SyncMLLocalChange.h" namespace DataSync { /*! \brief SyncMLReplace is a class for generating SyncML Replace XML object * * Does not support generation of FieldLevel, SourceParent and TargetParent elements */ class SyncMLReplace : public SyncMLLocalChange { public: /*! \brief Constructor * * @param aCmdID Command id for this element */ explicit SyncMLReplace( int aCmdID ); /*! \brief Destructor * */ virtual ~SyncMLReplace(); private: }; } #endif // SYNCMLREPLACE_H buteo-syncml-0.5.15/src/syncelements/SyncMLResults.cpp000066400000000000000000000067701433763642500230050ustar00rootroot00000000000000/*/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLResults.h" #include "datatypes.h" #include "SyncMLMeta.h" #include "SyncMLDevInf.h" using namespace DataSync; SyncMLResults::SyncMLResults( int aCmdID, int aMsgRef, int aCmdRef ) : SyncMLCmdObject( SYNCML_ELEMENT_RESULTS ) { SyncMLCmdObject* cmdIdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number( aCmdID ) ); addChild( cmdIdObject ); SyncMLCmdObject* msgRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_MSGREF, QString::number( aMsgRef ) ); addChild(msgRefObject); SyncMLCmdObject* cmdRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDREF, QString::number( aCmdRef ) ); addChild(cmdRefObject); } SyncMLResults::SyncMLResults( int aCmdID, int aMsgRef, int aCmdRef, const QList &aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole ) : SyncMLCmdObject( SYNCML_ELEMENT_RESULTS ) { SyncMLCmdObject* cmdIdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number( aCmdID ) ); addChild( cmdIdObject ); SyncMLCmdObject* msgRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_MSGREF, QString::number( aMsgRef ) ); addChild(msgRefObject); SyncMLCmdObject* cmdRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDREF, QString::number( aCmdRef ) ); addChild(cmdRefObject); SyncMLCmdObject* targetRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_TARGETREF, aVersion == SYNCML_1_1 ? SYNCML_DEVINF_PATH_11 : SYNCML_DEVINF_PATH_12 ); addChild( targetRefObject ); SyncMLMeta* metaObject = new SyncMLMeta; metaObject->addType( SYNCML_CONTTYPE_DEVINF_XML ); addChild( metaObject ); SyncMLDevInf* devInf = new SyncMLDevInf( aDataStores, aDeviceInfo, aVersion, aRole ); addChild( devInf ); } SyncMLResults::~SyncMLResults() { } buteo-syncml-0.5.15/src/syncelements/SyncMLResults.h000066400000000000000000000057351433763642500224520ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLRESULTS_H #define SYNCMLRESULTS_H #include "SyncMLCmdObject.h" #include "SyncAgentConsts.h" #include "datatypes.h" namespace DataSync { class StoragePlugin; class DeviceInfo; /*! \brief SyncMLResults is a class for generating SyncML * Resulst XML object */ class SyncMLResults : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aCmdID Command id for this element * @param aMsgRef Message referenced by this element * @param aCmdRef Command referenced by this element */ SyncMLResults( int aCmdID, int aMsgRef, int aCmdRef ); /*! \brief Constructor * * @param aCmdID Command id for this element * @param aMsgRef Message referenced by this element * @param aCmdRef Command referenced by this element * @param aDataStores Datastores available to use in generation * @param aDeviceInfo Device info object * @param aVersion Protocol version to use * @param aRole Role to use */ SyncMLResults( int aCmdID, int aMsgRef, int aCmdRef, const QList &aDataStores, const DeviceInfo& aDeviceInfo, const ProtocolVersion& aVersion, const Role& aRole ); /*! \brief Destructor * */ virtual ~SyncMLResults(); protected: private: }; } #endif // SYNCMLRESULTS_H buteo-syncml-0.5.15/src/syncelements/SyncMLStatus.cpp000066400000000000000000000112201433763642500226110ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLStatus.h" #include "SyncMLMeta.h" #include "SyncMLItem.h" #include "Fragments.h" #include "datatypes.h" using namespace DataSync; SyncMLStatus::SyncMLStatus(const StatusParams& aParams) : SyncMLCmdObject(SYNCML_ELEMENT_STATUS) { SyncMLCmdObject* cmdIdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDID, QString::number(aParams.cmdId) ); addChild(cmdIdObject); SyncMLCmdObject* msgRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_MSGREF, QString::number(aParams.msgRef) ); addChild(msgRefObject); SyncMLCmdObject* cmdRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMDREF, QString::number(aParams.cmdRef) ); addChild(cmdRefObject); SyncMLCmdObject* cmdObject = new SyncMLCmdObject( SYNCML_ELEMENT_CMD, aParams.cmd ); addChild(cmdObject); if( !aParams.targetRef.isEmpty() ) { SyncMLCmdObject* targetRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_TARGETREF, aParams.targetRef ); addChild(targetRefObject); } if( !aParams.sourceRef.isEmpty() ) { SyncMLCmdObject* sourceRefObject = new SyncMLCmdObject( SYNCML_ELEMENT_SOURCEREF, aParams.sourceRef ); addChild(sourceRefObject); } SyncMLCmdObject* dataObject = new SyncMLCmdObject( SYNCML_ELEMENT_DATA, QString::number(aParams.data) ); dataObject->setCDATA( true ); addChild(dataObject); if( !aParams.nextAnchor.isEmpty() ) { SyncMLCmdObject* item = new SyncMLCmdObject(SYNCML_ELEMENT_ITEM); SyncMLCmdObject* data = new SyncMLCmdObject(SYNCML_ELEMENT_DATA); SyncMLCmdObject* anc = new SyncMLCmdObject(SYNCML_ELEMENT_ANCHOR); anc->addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_METINF ); SyncMLCmdObject* next = new SyncMLCmdObject( SYNCML_ELEMENT_NEXT, aParams.nextAnchor ); next->addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_METINF ); anc->addChild(next); data->addChild(anc); item->addChild(data); addChild(item); } for( int i = 0; i < aParams.items.count(); ++i ) { SyncMLItem* itemObject = new SyncMLItem(); if( !aParams.items[i].source.isEmpty() ) { itemObject->insertSource( aParams.items[i].source ); } if( !aParams.items[i].target.isEmpty() ) { itemObject->insertTarget( aParams.items[i].target ); } if( !aParams.items[i].data.isEmpty() ) { itemObject->insertData( aParams.items[i].data.toUtf8() ); } addChild( itemObject ); } if( !aParams.chal.meta.type.isEmpty() ) { SyncMLCmdObject* chalObject = new SyncMLCmdObject( SYNCML_ELEMENT_CHAL ); SyncMLMeta* metaObject = new SyncMLMeta(); metaObject->addType( aParams.chal.meta.type ); metaObject->addFormat( aParams.chal.meta.format ); if( !aParams.chal.meta.nextNonce.isEmpty() ) { metaObject->addNextNonce( aParams.chal.meta.nextNonce ); } chalObject->addChild( metaObject ); addChild( chalObject ); } } SyncMLStatus::~SyncMLStatus() { } buteo-syncml-0.5.15/src/syncelements/SyncMLStatus.h000066400000000000000000000041651433763642500222700ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLSTATUS_H #define SYNCMLSTATUS_H #include "SyncMLCmdObject.h" namespace DataSync { struct StatusParams; /*! \brief SyncMLStatus is class for generating SyncML Status XML object */ class SyncMLStatus : public SyncMLCmdObject { public: /*! \brief Constructor * * @param aParams Status parameters to use in construction */ explicit SyncMLStatus( const StatusParams& aParams); /*! \brief Destructor * */ virtual ~SyncMLStatus(); }; } #endif // SYNCMLSTATUS_H buteo-syncml-0.5.15/src/syncelements/SyncMLSync.cpp000066400000000000000000000042511433763642500222500ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLSync.h" #include "datatypes.h" using namespace DataSync; SyncMLSync::SyncMLSync( int aCmdID, const QString& aTarget, const QString& aSource ) : SyncMLLocalChanges( SYNCML_ELEMENT_SYNC, aCmdID, aTarget, aSource ) { } SyncMLSync::~SyncMLSync() { } void SyncMLSync::addNumberOfChanges( int aNumberOfChanges ) { SyncMLCmdObject* numberOfChangesObject = new SyncMLCmdObject( SYNCML_ELEMENT_NUMOFCHANGES, QString::number( aNumberOfChanges ) ); addChild( numberOfChangesObject ); } buteo-syncml-0.5.15/src/syncelements/SyncMLSync.h000066400000000000000000000046501433763642500217200ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLSYNC_H #define SYNCMLSYNC_H #include "SyncMLLocalChanges.h" namespace DataSync { /*! \brief SyncMLSync is class for generating SyncML Sync XML object * * Does not support generation of FreeMem and FreeId elements */ class SyncMLSync : public SyncMLLocalChanges { public: /*! \brief Constructor * * @param aCmdID Command id for this element * @param aTarget Target database URI * @param aSource Source database URI */ SyncMLSync( int aCmdID, const QString& aTarget, const QString& aSource ); /*! \brief Destructor * */ virtual ~SyncMLSync(); /*! \brief Add NumberOfChanges object as a child * * @param aNumberOfChanges Number of changes */ void addNumberOfChanges( int aNumberOfChanges ); private: }; } #endif // SYNCMLSYNC_H buteo-syncml-0.5.15/src/syncelements/syncelements.pro000066400000000000000000000015421433763642500227750ustar00rootroot00000000000000SOURCES += SyncMLCmdObject.cpp \ SyncMLMessage.cpp \ SyncMLBody.cpp \ SyncMLMeta.cpp \ SyncMLAlert.cpp \ SyncMLStatus.cpp \ SyncMLHdr.cpp \ SyncMLSync.cpp \ SyncMLCred.cpp \ SyncMLLocalChange.cpp \ SyncMLAdd.cpp \ SyncMLDelete.cpp \ SyncMLReplace.cpp \ SyncMLMap.cpp \ SyncMLPut.cpp \ SyncMLItem.cpp \ SyncMLMapItem.cpp\ SyncMLLocalChanges.cpp \ SyncMLDevInf.cpp \ SyncMLResults.cpp \ SyncMLCTCap.cpp \ SyncMLGet.cpp \ SyncMLExt.cpp HEADERS += SyncMLCmdObject.h \ SyncMLMessage.h \ SyncMLHdr.h \ SyncMLMeta.h \ SyncMLAlert.h \ SyncMLStatus.h \ SyncMLMap.h \ SyncMLLocalChanges.h \ SyncMLSync.h \ SyncMLCred.h \ SyncMLLocalChange.h \ SyncMLAdd.h \ SyncMLDelete.h \ SyncMLReplace.h \ SyncMLPut.h \ SyncMLItem.h \ SyncMLMapItem.h \ SyncMLBody.h \ SyncMLDevInf.h \ SyncMLResults.h \ SyncMLCTCap.h \ SyncMLGet.h \ SyncMLExt.h buteo-syncml-0.5.15/src/transport/000077500000000000000000000000001433763642500170635ustar00rootroot00000000000000buteo-syncml-0.5.15/src/transport/BaseTransport.cpp000066400000000000000000000237201433763642500223620ustar00rootroot00000000000000 /* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "BaseTransport.h" #include #include #include "SyncMLMessage.h" #include "LibWbXML2Encoder.h" #include "QtEncoder.h" #include "datatypes.h" #include "SyncMLLogging.h" using namespace DataSync; BaseTransport::BaseTransport( const ProtocolContext& aContext, QObject* aParent ) : Transport( aParent ), iContext( aContext ), iHandleIncomingData( false ), iWbXml( false ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } BaseTransport::~BaseTransport() { FUNCTION_CALL_TRACE(lcSyncMLTrace); iIODevice.close(); } void BaseTransport::setRemoteLocURI( const QString& aURI ) { iRemoteLocURI = aURI; } bool BaseTransport::usesWbXML() { return iWbXml; } bool BaseTransport::sendSyncML( SyncMLMessage* aMessage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !aMessage ) { return false; } if( !prepareSend() ) { qCCritical(lcSyncML) << "prepareSend() failed, cannot send message"; return false; } QByteArray data; if( !encodeMessage(*aMessage, data ) ) { return false; } delete aMessage; aMessage = NULL; QString contentType; if( useWbXml() ) { if( iContext== CONTEXT_DM ) { contentType = SYNCML_CONTTYPE_DM_WBXML; } else { contentType = SYNCML_CONTTYPE_DS_WBXML; } } else { if( iContext == CONTEXT_DM ) { contentType = SYNCML_CONTTYPE_DM_XML; } else { contentType = SYNCML_CONTTYPE_DS_XML; } } return doSend( data, contentType ); } bool BaseTransport::sendSAN( const QByteArray& aMessage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); #ifndef QT_NO_DEBUG qCDebug(lcSyncMLProtocol) << "\nSending SAN message:\n=========\n" << aMessage.toHex() << "\n========="; #endif // QT_NO_DEBUG return doSend( aMessage, SYNCML_CONTTYPE_SAN_DS ); } bool BaseTransport::receive() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iIncomingData.size() > 0 ) { emitReadSignal(); return true; } else { iHandleIncomingData = true; QString contentType; if( useWbXml() ) { if( iContext == CONTEXT_DM ) { contentType = SYNCML_CONTTYPE_DM_WBXML; } else { contentType = SYNCML_CONTTYPE_DS_WBXML; } } else { if( iContext == CONTEXT_DM ) { contentType = SYNCML_CONTTYPE_DM_XML; } else { contentType = SYNCML_CONTTYPE_DS_XML; } } if( doReceive(contentType) ) { return true; } else { iHandleIncomingData = false; return false; } } } void BaseTransport::receive( const QByteArray& aData, const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iIODevice.close(); if( aData.isEmpty() ) { emit sendEvent( TRANSPORT_DATA_INVALID_CONTENT, "" ); return; } if( aContentType.contains( SYNCML_CONTTYPE_DS_WBXML ) || aContentType.contains( SYNCML_CONTTYPE_DM_WBXML ) ) { receiveWbXMLData( aData ); } else if( aContentType.contains( SYNCML_CONTTYPE_DS_XML ) || aContentType.contains( SYNCML_CONTTYPE_DM_XML)) { receiveXMLData( aData ); } else if( aContentType.contains( SYNCML_CONTTYPE_SAN_DS ) ) { receiveSANData( aData ); } else { iIncomingData.clear(); emit sendEvent( TRANSPORT_DATA_INVALID_CONTENT_TYPE, "" ); return; } if( iHandleIncomingData ) { iHandleIncomingData = false; emitReadSignal(); } } const QString& BaseTransport::getRemoteLocURI() const { return iRemoteLocURI; } bool BaseTransport::encodeMessage( const SyncMLMessage& aMessage, QByteArray& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); bool success = false; if( useWbXml() ) { LibWbXML2Encoder encoder; if( encoder.encodeToWbXML( aMessage, aMessage.getProtocolVersion(), aData ) ) { qCDebug(lcSyncML) << "WbXML encoding successful"; #ifndef QT_NO_DEBUG QByteArray xml; if( encoder.encodeToXML( aMessage, aMessage.getProtocolVersion(), xml, true ) ) { qCDebug(lcSyncMLProtocol) << "\nSending message:\n=========\n" << xml << "\n=========size:"< 0) { QString dataString = QString::fromUtf8(iIODeviceData, iIODeviceData.size()); // Strip illegal XML characters dataString.remove(QChar(0x00)); dataString.remove(QRegExp("[\x0001-\x0008,\x000B-\x000C,\x000E-\x001F]")); iIODeviceData = dataString.toUtf8(); #ifndef QT_NO_DEBUG qCDebug(lcSyncMLProtocol) << "\nPurged XML message:\n=========\n" << iIODeviceData << "\n========="; #endif // QT_NO_DEBUG // Put the new buffer into the IO device iIODevice.close(); iIODevice.setBuffer( &iIODeviceData ); iIODevice.open( QIODevice::ReadOnly ); emit readXMLData( &iIODevice, false ); } } buteo-syncml-0.5.15/src/transport/BaseTransport.h000066400000000000000000000117751433763642500220360ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef BASETRANSPORT_H #define BASETRANSPORT_H #include "Transport.h" #include "SyncAgentConsts.h" #include namespace DataSync { /*! \brief Base implementation class for all transports * * Handles WbXml and other common operations */ class BaseTransport : public Transport { Q_OBJECT public: /*! \brief Constructor * * @param aContext Protocol context * @param aParent Parent of this object */ BaseTransport( const ProtocolContext& aContext, QObject* aParent ); /*! \brief Destructor * */ virtual ~BaseTransport(); virtual void setRemoteLocURI( const QString& aURI ); virtual bool usesWbXML(); virtual bool sendSyncML( SyncMLMessage* aMessage ); virtual bool sendSAN( const QByteArray& aMessage ); virtual bool receive(); /*! \brief Enable/disable WbXML * * @param aUse True/false to enable/disable WbXML encoding */ void setWbXml( bool aUse ); private slots: /*! \brief Remove any illegal XML characters from the previous message * * Removes illegal XML characters (NULLs and control characters) */ void purgeAndResendBuffer(); protected: /*! \brief Prepare for sending data * * If problems occur in preparation, this function should return false. It should also * emit sendEvent() signal related to the error * * @return True on success, otherwise false */ virtual bool prepareSend() = 0; /*! \brief Send via network layer * * All transports derived from BaseTransport must implement this function. It should do * the actual sending of data * * @param aData Content data * @param aContentType Content type */ virtual bool doSend( const QByteArray& aData, const QString& aContentType ) = 0; /*! \brief Receive via network layer * * All transports derived from BaseTransport must implement this function. It should start * the actual receiving of data * * @param aContentType Content type */ virtual bool doReceive( const QString& aContentType ) = 0; /*! \brief Receive incoming data * * All transports derived from BaseTransport. Data received should be passed to this function * * @param aData Content data * @param aContentType Content type */ void receive( const QByteArray& aData, const QString& aContentType ); /*! \brief Retrieves remote location URI * * @return Remote URI */ const QString& getRemoteLocURI() const; /*! \brief Encodes a SyncML message * * SyncML message can be encoded to either XML or WbXML, depending on the current mode * * @param aMessage Message to encode * @param aData Resulting data * @return True on success, false otherwise */ bool encodeMessage( const SyncMLMessage& aMessage, QByteArray& aData ); private: void emitReadSignal(); bool useWbXml() const; void receiveWbXMLData( const QByteArray& aData ); void receiveXMLData( const QByteArray& aData ); void receiveSANData( const QByteArray& aData ); ProtocolContext iContext; QString iRemoteLocURI; QString iContentType; QByteArray iIncomingData; QByteArray iIODeviceData; QBuffer iIODevice; bool iHandleIncomingData; bool iWbXml; }; } #endif // BASETRANSPORT_H buteo-syncml-0.5.15/src/transport/HTTPTransport.cpp000066400000000000000000000303071433763642500222660ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "HTTPTransport.h" #include #include "datatypes.h" #include "SyncAgentConfigProperties.h" #include "SyncMLLogging.h" using namespace DataSync; HTTPTransport::HTTPTransport( const ProtocolContext& aContext, QObject* aParent ) : BaseTransport( aContext, aParent), iManager( 0 ), iFirstMessageSent( false ), iMaxNumberOfResendAttempts( 0 ), iNumberOfResendAttempts( 0 ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iManager = new QNetworkAccessManager; iManager->setConfiguration(QNetworkConfiguration()); iManager->setProxy(QNetworkProxy(QNetworkProxy::NoProxy)); } HTTPTransport::~HTTPTransport() { FUNCTION_CALL_TRACE(lcSyncMLTrace); delete iManager; iManager = NULL; } void HTTPTransport::setProperty( const QString& aProperty, const QString& aValue ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aProperty == HTTPNUMBEROFRESENDATTEMPTSPROP ) { qCDebug(lcSyncML) << "Setting property" << aProperty <<":" << aValue; iMaxNumberOfResendAttempts = aValue.toInt(); } else if( aProperty == HTTPPROXYHOSTPROP ) { qCDebug(lcSyncML) << "Setting property" << aProperty <<":" << aValue; QNetworkProxy proxy = iManager->proxy(); proxy.setType( QNetworkProxy::HttpProxy ); proxy.setHostName(aValue); iManager->setProxy(proxy); } else if( aProperty == HTTPPROXYPORTPROP ) { qCDebug(lcSyncML) << "Setting property" << aProperty <<":" << aValue; QNetworkProxy proxy = iManager->proxy(); proxy.setType( QNetworkProxy::HttpProxy ); proxy.setPort( aValue.toInt() ); iManager->setProxy(proxy); } } bool HTTPTransport::init() { FUNCTION_CALL_TRACE(lcSyncMLTrace); connect( iManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(httpRequestFinished(QNetworkReply *)), Qt::QueuedConnection); connect( iManager,SIGNAL(authenticationRequired(QNetworkReply *,QAuthenticator *)), this,SLOT(authRequired(QNetworkReply *,QAuthenticator * )), Qt::QueuedConnection); #ifndef QT_NO_OPENSSL connect( iManager, SIGNAL(sslErrors(QNetworkReply*, const QList& )), this, SLOT(sslErrors(QNetworkReply*, const QList& ))); #endif iFirstMessageSent = false; return true; } void HTTPTransport::close() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool HTTPTransport::prepareSend() { // Don't need to do nothing in prepareSend as HTTP is sessionless return true; } bool HTTPTransport::doSend( const QByteArray& aData, const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( sendRequest( aData, aContentType ) ) { // If this is the first message to be sent, save it if( !iFirstMessageSent ) { iNumberOfResendAttempts = 0; iFirstMessageData = aData; iFirstMessageContentType = aContentType; } return true; } else { return false; } } bool HTTPTransport::doReceive( const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_UNUSED( aContentType ); return true; } void HTTPTransport::setProxyConfig( const QNetworkProxy& aProxy ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iManager->setProxy( aProxy ); } QNetworkProxy HTTPTransport::getProxyConfig() { return iManager->proxy(); } void HTTPTransport::addXheader(const QString& aName, const QString& aValue) { iXheaders.insert(aName, aValue); } void HTTPTransport::prepareRequest( QNetworkRequest& aRequest, const QByteArray& aContentType, int aContentLength ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); QUrl url; // The URL might be percent encoded url = QUrl::fromEncoded( getRemoteLocURI().toLatin1() ); if( !url.isValid() ) { url = QUrl( getRemoteLocURI() ); } aRequest.setRawHeader( HTTP_HDRSTR_POST, url.path().toLatin1()); aRequest.setUrl( url ); aRequest.setRawHeader( HTTP_HDRSTR_UA, HTTP_UA_VALUE); aRequest.setRawHeader( HTTP_HDRSTR_CONTENT_TYPE, aContentType ); aRequest.setRawHeader( HTTP_HDRSTR_ACCEPT,HTTP_ACCEPT_VALUE ); aRequest.setHeader( QNetworkRequest::ContentLengthHeader, QVariant( aContentLength ) ); QMap::const_iterator i; for (i = iXheaders.constBegin(); i != iXheaders.constEnd(); i++) { aRequest.setRawHeader(i.key().toLatin1(), i.value().toLatin1()); } #ifndef QT_NO_OPENSSL //do it only for https if( url.toString().contains(SYNCML_SCHEMA_HTTPS)) { qCDebug(lcSyncML) << "HTTPS protocol detected"; // Don't remove the below commented code. // this can be used while adding full fledged ssl support. // QNetworkAccessManager sets the default configuration needed for https // if we want to change the protocol , we will have do it as follows. // QSslConfiguration ssl = request.sslConfiguration(); // if( ssl.isNull() ) // { // ssl.setProtocol(QSsl::SslV3); // } // request.setSslConfiguration(ssl); } #endif // QT_NO_OPENSSL } bool HTTPTransport::sendRequest( const QByteArray& aData, const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // build the message, and send it QNetworkRequest request; prepareRequest( request, aContentType.toLatin1(), aData.size() ); #ifndef QT_NO_DEBUG // Print the message qCDebug(lcSyncMLProtocol) << "Sending request to" << request.url().host(); qCDebug(lcSyncMLProtocol) << "Headers:"; QList headers = request.rawHeaderList(); foreach( const QByteArray& ar, headers ) { qCDebug(lcSyncMLProtocol) << ar << ": " << request.rawHeader(ar); } #endif // QT_NO_DEBUG if( iManager->post(request, aData) ) { // send succeeded return true; } else { // send failed return false; } } bool HTTPTransport::shouldResend() const { FUNCTION_CALL_TRACE(lcSyncMLTrace); // We should try to re-send a message if it's the first message to be sent, // and if we have some retry attempts left if( !iFirstMessageSent && iNumberOfResendAttempts < iMaxNumberOfResendAttempts ) { return true; } else { return false; } } bool HTTPTransport::resend() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Attempting to re-send initialization package, attempt number:" << iNumberOfResendAttempts + 1; if( sendRequest( iFirstMessageData, iFirstMessageContentType ) ) { ++iNumberOfResendAttempts; return true; } else { return false; } } void HTTPTransport::slotNetworkStateChanged(bool aState) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if (aState == false) { qCDebug(lcSyncML) << "Network accessible state:"<error() != QNetworkReply::NoError ) { switch( aReply->error() ) { case QNetworkReply::TimeoutError: { // In case the remote side times out, possibly try to re-send the message. // If message should not be re-sent, or the re-send fails, handle as // an error if( !shouldResend() || !resend() ) { qCDebug(lcSyncML) << "Connection timeout:" << aReply->errorString(); emit sendEvent(TRANSPORT_CONNECTION_TIMEOUT, aReply->errorString()); } break; } default: { qCDebug(lcSyncML) << "TRANSPORT ERROR REASON:" << aReply->errorString(); emit sendEvent(TRANSPORT_CONNECTION_FAILED, aReply->errorString()); break; } }; } else { #ifndef QT_NO_DEBUG qCDebug(lcSyncMLProtocol) << "Received response" ; qCDebug(lcSyncMLProtocol) << "Headers:" ; QList headers = aReply->rawHeaderList(); foreach( const QByteArray& ar, headers ) { qCDebug(lcSyncMLProtocol) << ar << ": " << aReply->rawHeader(ar); } #endif // QT_NO_DEBUG QByteArray data = aReply->readAll(); // In case of zero-length response, possibly try to re-send the message. If the message // should not be re-sent, or if re-send fails, let the zero-length response through. // BaseTransport::receive() will mark it as TRANSPORT_DATA_INVALID_CONTENT error. if( !data.isEmpty() || !shouldResend() || !resend() ) { QString contentType = aReply->header( QNetworkRequest::ContentTypeHeader).toString(); if( !iFirstMessageSent ) { iFirstMessageSent = true; iFirstMessageData.clear(); iFirstMessageContentType.clear(); } receive( data, contentType ); } } aReply->deleteLater(); } void HTTPTransport::authRequired(QNetworkReply* /*aReply*/, QAuthenticator* /*aAuth*/ ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Network Connection needs authentication"; emit sendEvent( TRANSPORT_CONNECTION_AUTHENTICATION_NEEDED, "Authentication required" ); } void HTTPTransport::handleProxyAuthentication(QNetworkProxy& /*aProxy*/, QAuthenticator* /*aAuth*/ ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Proxy needs authentication"; sendEvent( TRANSPORT_CONNECTION_AUTHENTICATION_NEEDED, "Authentication required" ); } #ifndef QT_NO_OPENSSL void HTTPTransport::sslErrors( QNetworkReply* aReply, const QList& aErrors ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "SSL Errors received"; qCDebug(lcSyncML) << "list size :" << aErrors.size(); foreach( const QSslError& sslError , aErrors) { qCDebug(lcSyncML) << sslError.errorString(); // the original version used isValid(), which would check if the certificate is not expired // or blacklisted; as that information might be useful in the log I guess that the intention // here was to check for a certificate if (!sslError.certificate().isNull()) { qCDebug(lcSyncML) << "StartDate: " << sslError.certificate().effectiveDate(); qCDebug(lcSyncML) << "ExpiryDate:" << sslError.certificate().expiryDate(); qCDebug(lcSyncML) << "Issuer Info:"; qCDebug(lcSyncML) << "Organization:" << sslError.certificate().issuerInfo( QSslCertificate::Organization ); } } qCDebug(lcSyncML) << "Ignoring SSL Errors"; aReply->ignoreSslErrors(); } #endif buteo-syncml-0.5.15/src/transport/HTTPTransport.h000066400000000000000000000100471433763642500217320ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef HTTPTRANSPORT_H #define HTTPTRANSPORT_H #include #include "BaseTransport.h" #include class QNetworkProxy; class QNetworkReply; class QNetworkRequest; class QAuthenticator; namespace DataSync { /*! \brief HTTP Implementation of the Transport class */ class HTTPTransport : public BaseTransport { Q_OBJECT public: /*! \brief Constructor * * @param aContext Protocol context * @param aParent Parent of this object */ HTTPTransport( const ProtocolContext& aContext = CONTEXT_DS, QObject* aParent = 0 ); /*! \brief Destructor * */ virtual ~HTTPTransport(); virtual void setProperty( const QString& aProperty, const QString& aValue ); virtual bool init(); virtual void close(); /*! \brief Sets proxy config to use * * @param aProxy Proxy configuration */ void setProxyConfig( const QNetworkProxy& aProxy ); /*! \brief Returns the proxy config in use * * @return Proxy configuration */ QNetworkProxy getProxyConfig(); /*! \brief Adds x-header in the form name - value * * @param aName X-header field name * @param aValue X-header field value */ void addXheader(const QString& aName, const QString& aValue); protected: virtual bool prepareSend(); virtual bool doSend( const QByteArray& aData, const QString& aContentType ); virtual bool doReceive( const QString& aContentType ); private slots: void httpRequestFinished( QNetworkReply* aReply ); void slotNetworkStateChanged(bool aState); void handleProxyAuthentication( QNetworkProxy& aProxy, QAuthenticator* aAuth ); void authRequired(QNetworkReply* aReply, QAuthenticator* aAuth ); #ifndef QT_NO_OPENSSL void sslErrors( QNetworkReply* aReply, const QList& aErrors ); #endif private: void prepareRequest( QNetworkRequest& aRequest, const QByteArray& aContentType, int aContentLength ); bool sendRequest( const QByteArray& aData, const QString& aContentType ); bool shouldResend() const; bool resend(); QNetworkAccessManager* iManager; bool iFirstMessageSent; QByteArray iFirstMessageData; QString iFirstMessageContentType; int iMaxNumberOfResendAttempts; int iNumberOfResendAttempts; QMap iXheaders; }; } #endif // HTTPTRANSPORT_H buteo-syncml-0.5.15/src/transport/LibWbXML2Encoder.cpp000066400000000000000000000323711433763642500225370ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "LibWbXML2Encoder.h" #include "SyncMLMessage.h" #include "datatypes.h" #include #include "SyncMLLogging.h" using namespace DataSync; LibWbXML2Encoder::LibWbXML2Encoder() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } LibWbXML2Encoder::~LibWbXML2Encoder() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool LibWbXML2Encoder::encodeToXML( const SyncMLCmdObject& aRootObject, ProtocolVersion aVersion, QByteArray& aXMLDocument, bool aPrettyPrint ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Encoding to XML"; WBXMLTree* tree = generateTree( aRootObject, aVersion ); if( !tree ) { qCCritical(lcSyncML) << "Could not generate WBXMLTree"; return false; } WBXMLEncoder* encoder = wbxml_encoder_create(); if( !encoder ) { qCCritical(lcSyncML) << "Could not create WBXMLEncoder"; wbxml_tree_destroy( tree ); return false; } wbxml_encoder_set_wbxml_version(encoder, WBXML_VERSION_12); if( aPrettyPrint ) { wbxml_encoder_set_xml_gen_type( encoder, WBXML_GEN_XML_INDENT ); wbxml_encoder_set_indent( encoder, 3 ); } else { wbxml_encoder_set_xml_gen_type( encoder, WBXML_GEN_XML_COMPACT ); wbxml_encoder_set_indent( encoder, 0 ); } wbxml_encoder_set_tree( encoder, tree ); WB_UTINY* xml; WB_ULONG xml_len; WBXMLError error = wbxml_encoder_encode_tree_to_xml( encoder, &xml, &xml_len ); bool success = false; if( error == WBXML_OK ) { aXMLDocument.append( (char *)xml, xml_len ); wbxml_free( xml ); success = true; qCDebug(lcSyncML) << "Encoding successful"; qCDebug(lcSyncML) << "XML buffer size:" << xml_len; } else { success = false; qCCritical(lcSyncML) << "XML conversion failed:" << (const char* )wbxml_errors_string( error ); } wbxml_tree_destroy( tree ); wbxml_encoder_destroy( encoder ); return success; } bool LibWbXML2Encoder::encodeToWbXML( const SyncMLCmdObject& aRootObject, ProtocolVersion aVersion, QByteArray& aWbXMLDocument ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Encoding to wbXML"; WBXMLTree* tree = generateTree( aRootObject, aVersion ); if( !tree ) { qCCritical(lcSyncML) << "Could not generate WBXMLTree"; return false; } WBXMLEncoder* encoder = wbxml_encoder_create(); if( !encoder ) { qCCritical(lcSyncML) << "Could not create WBXMLEncoder"; wbxml_tree_destroy( tree ); return false; } wbxml_encoder_set_wbxml_version(encoder, WBXML_VERSION_12); //Workaround : For N900 combo sync wbxml_encoder_set_use_strtbl (encoder, false); wbxml_encoder_set_tree( encoder, tree ); WB_UTINY* wbxml; WB_ULONG wbxml_len; WBXMLError error = wbxml_encoder_encode_tree_to_wbxml( encoder, &wbxml, &wbxml_len ); bool success = false; if( error == WBXML_OK ) { aWbXMLDocument.append( (char *)wbxml, wbxml_len ); wbxml_free( wbxml ); success = true; qCDebug(lcSyncML) << "Encoding successful"; qCDebug(lcSyncML) << "wbXML buffer size:" << wbxml_len; } else { qCCritical(lcSyncML) << "wbXML conversion failed:" << (const char* )wbxml_errors_string( error ); success = false; } destroyTree( tree ); wbxml_encoder_destroy( encoder ); return success; } bool LibWbXML2Encoder::decodeFromWbXML( const QByteArray& aWbXMLDocument, QByteArray& aXMLDocument, bool aPrettyPrint ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "Converting WbXML to XML"; WBXMLError error = WBXML_OK; WBXMLConvWBXML2XML *conv = NULL; error = wbxml_conv_wbxml2xml_create( &conv ); if (error != WBXML_OK) { qCDebug(lcSyncML) << "WbXML to XML conversion failed: " << (const char* )wbxml_errors_string( error ); return false; } wbxml_conv_wbxml2xml_set_language( conv, WBXML_LANG_UNKNOWN ); if( aPrettyPrint ) { wbxml_conv_wbxml2xml_set_gen_type( conv, WBXML_GEN_XML_INDENT ); wbxml_conv_wbxml2xml_set_indent( conv, 3 ); } else { wbxml_conv_wbxml2xml_set_gen_type( conv, WBXML_GEN_XML_COMPACT ); wbxml_conv_wbxml2xml_set_indent( conv, 0 ); } wbxml_conv_wbxml2xml_enable_preserve_whitespaces( conv ); wbxml_conv_wbxml2xml_set_charset( conv, WBXML_CHARSET_UNKNOWN ); const WB_UTINY* wbxml = reinterpret_cast( aWbXMLDocument.constData() ); WB_ULONG wbxml_len = aWbXMLDocument.size(); WB_UTINY* xml; WB_ULONG xml_len; qCDebug(lcSyncML) << "WbXML buffer size: " << wbxml_len; error = wbxml_conv_wbxml2xml_run( conv, const_cast( wbxml ), wbxml_len, &xml, &xml_len); wbxml_conv_wbxml2xml_destroy(conv); QByteArray data; if( error == WBXML_OK ) { qCDebug(lcSyncML) << "WbXML to XML conversion succeeded"; qCDebug(lcSyncML) << "XML buffer size: " << xml_len; aXMLDocument.append( reinterpret_cast( xml ), xml_len ); wbxml_free( xml ); return true; } else { qCDebug(lcSyncML) << "WbXML to XML conversion failed: " << (const char* )wbxml_errors_string( error ); return false; } } WBXMLTree* LibWbXML2Encoder::generateTree( const SyncMLCmdObject& aRootObject, ProtocolVersion aVersion ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); WBXMLTree* tree = createTree( aRootObject, aVersion ); if( !tree ) { return NULL; } if( !createNode( aRootObject, tree, NULL, aVersion) ) { destroyTree( tree ); tree = NULL; } return tree; } WBXMLTree* LibWbXML2Encoder::createTree( const SyncMLCmdObject& aObject, ProtocolVersion aVersion ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); WBXMLLanguage language = namespaceToLanguage( aObject, aVersion ); if( language == WBXML_LANG_UNKNOWN ) { qCCritical(lcSyncML) << "Cannot create tree, unknown language!"; return NULL; } else { return wbxml_tree_create( language, WBXML_CHARSET_UTF_8 ); } } void LibWbXML2Encoder::destroyTree( WBXMLTree* aTree ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); wbxml_tree_destroy( aTree ); } bool LibWbXML2Encoder::createNode( const SyncMLCmdObject& aObject, WBXMLTree* aTree, WBXMLTreeNode* aParent, ProtocolVersion aVersion ) const { // ** Write element name QByteArray name = aObject.getName().toUtf8(); WBXMLTreeNode* node = wbxml_tree_add_xml_elt( aTree, aParent, (unsigned char*)name.constData() ); if( !node ) { qCCritical(lcSyncML) << "Could not create tree node for element" << aObject.getName(); return false; } // ** Write element attributes const QMap& attributes = aObject.getAttributes(); bool attributesOk = true; QMapIterator i( attributes ); while( i.hasNext() ) { i.next(); QByteArray attrName = i.key().toUtf8(); QByteArray attrValue = i.value().toUtf8(); WBXMLError error = wbxml_tree_node_add_xml_attr( aTree->lang, node, (unsigned char*)attrName.constData(), (unsigned char*)attrValue.constData() ); if( error != WBXML_OK ) { qCCritical(lcSyncML) << "Could not add attribute" << attrName << "for element" << name; attributesOk = false; break; } } if( !attributesOk ) { return false; } // ** Write element value QByteArray value = aObject.getValue().toUtf8(); bool valueOk = true; if( !value.isEmpty() ) { if( aObject.getCDATA() ) { WBXMLTreeNode* cdata = wbxml_tree_add_cdata( aTree, node ); if( !cdata || !wbxml_tree_add_text( aTree, cdata, (unsigned char*)value.constData(), value.length() ) ) { qCCritical(lcSyncML) << "Could not add CDATA for element" << aObject.getName(); valueOk = false; } } else if( !wbxml_tree_add_text( aTree, node, (unsigned char*)value.constData(), value.length() ) ) { qCCritical(lcSyncML) << "Could not add TEXT for element" << aObject.getName(); valueOk = false; } } if( !valueOk ) { return false; } // ** Process element children const QList& children = aObject.getChildren(); for( int i = 0; i < children.count(); ++i ) { SyncMLCmdObject* child = children[i]; WBXMLLanguage language = namespaceToLanguage( *child, aVersion ); if( language != WBXML_LANG_UNKNOWN && language != aTree->lang->langID ) { qCDebug(lcSyncML) << "Children using language" << language << "while parent is using" << aTree->lang->langID; qCDebug(lcSyncML) << "Creating subtree for children"; WBXMLTree* subTree = createTree( *child, aVersion ); if( !subTree ) { qCCritical(lcSyncML) << "Could not create subtree for" << child->getName(); return false; } if( !createNode( *child, subTree, NULL, aVersion ) ) { qCCritical(lcSyncML) << "Could not add child to subtree" << child->getName() << "for element" << name; return false; } if( !wbxml_tree_add_tree( aTree, node, subTree ) ) { destroyTree( subTree ); qCCritical(lcSyncML) << "Could not add subtree for" << child->getName(); return false; } } else { if( !createNode( *child, aTree, node, aVersion ) ) { qCCritical(lcSyncML) << "Could not add child" << child->getName() << "for element" << name; return false; } } } return true; } WBXMLLanguage LibWbXML2Encoder::namespaceToLanguage( const SyncMLCmdObject& aObject, ProtocolVersion aVersion ) const { QString ns = aObject.getAttributes().value( XML_NAMESPACE ); if( ns == XML_NAMESPACE_VALUE_SYNCML11 ) { return WBXML_LANG_SYNCML_SYNCML11; } else if( ns == XML_NAMESPACE_VALUE_SYNCML12 ) { return WBXML_LANG_SYNCML_SYNCML12; } else if( ns == XML_NAMESPACE_VALUE_METINF ) { if( aVersion == SYNCML_1_1 ) { return WBXML_LANG_SYNCML_SYNCML11; } else if( aVersion == SYNCML_1_2 ) { return WBXML_LANG_SYNCML_SYNCML12; } else { return WBXML_LANG_UNKNOWN; } } else if( ns == XML_NAMESPACE_VALUE_DEVINF ) { if( aVersion == SYNCML_1_1 ) { return WBXML_LANG_SYNCML_DEVINF11; } else if( aVersion == SYNCML_1_2 ) { return WBXML_LANG_SYNCML_DEVINF12; } else { return WBXML_LANG_UNKNOWN; } } else if( ns == XML_NAMESPACE_VALUE_DMDDF ) { if( aVersion == SYNCML_1_2 ) { return WBXML_LANG_SYNCML_DMDDF12; } else { return WBXML_LANG_UNKNOWN; } } else { return WBXML_LANG_UNKNOWN; } } buteo-syncml-0.5.15/src/transport/LibWbXML2Encoder.h000066400000000000000000000103171433763642500222000ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LIBWBXML2ENCODER_H #define LIBWBXML2ENCODER_H #include // Needed for compilation outside scratchbox, as only scratchbox version of // libwbxml2-0 includes wbxml_config.h in wbxml.h. #define WBXML_SUPPORT_SYNCML #include #include "SyncAgentConsts.h" // Defined opaquely to match the full definitions in typedef struct WBXMLTree_s WBXMLTree; typedef struct WBXMLTreeNode_s WBXMLTreeNode; namespace DataSync { class SyncMLCmdObject; /*! \brief XML and WbXML encoder that uses libwbxml2 * */ class LibWbXML2Encoder { public: /*! \brief Constructor * */ LibWbXML2Encoder(); /*! \brief Destructor * */ ~LibWbXML2Encoder(); /*! \brief Encode a SyncML message to XML document * * @param aRootObject Root object of the document * @param aVersion SyncML version * @param aXMLDocument Output XML document * @param aPrettyPrint If true prefer human-readable output, otherwise prefer compact size * @return True on success, otherwise false */ bool encodeToXML( const SyncMLCmdObject& aRootObject, ProtocolVersion aVersion, QByteArray& aXMLDocument, bool aPrettyPrint ) const; /*! \brief Encode a SyncML message to WbXML document * * @param aRootObject Root object of the document * @param aVersion SyncML version * @param aWbXMLDocument Output WbXML document * @return True on success, otherwise false */ bool encodeToWbXML( const SyncMLCmdObject& aRootObject, ProtocolVersion aVersion, QByteArray& aWbXMLDocument ) const; /*! \brief Decode a SyncML message from WbXML document * * @param aWbXMLDocument Message to decode * @param aXMLDocument Output XML document * @param aPrettyPrint If true prefer human-readable output, otherwise prefer compact size * @return True on success, otherwise false */ bool decodeFromWbXML( const QByteArray& aWbXMLDocument, QByteArray& aXMLDocument, bool aPrettyPrint ) const; protected: private: WBXMLTree* generateTree( const SyncMLCmdObject& aRootObject, ProtocolVersion aVersion ) const; WBXMLTree* createTree( const SyncMLCmdObject& aObject, ProtocolVersion aVersion ) const; void destroyTree( WBXMLTree* aTree ) const; bool createNode( const SyncMLCmdObject& aObject, WBXMLTree* aTree, WBXMLTreeNode* aParent, ProtocolVersion aVersion ) const; WBXMLLanguage namespaceToLanguage( const SyncMLCmdObject& aObject, ProtocolVersion aVersion ) const; }; } #endif // LIBWBXML2ENCODER_H buteo-syncml-0.5.15/src/transport/OBEXClientWorker.cpp000066400000000000000000000252131433763642500226600ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "OBEXClientWorker.h" #include "OBEXConnection.h" #include "OBEXDataHandler.h" #include "SyncMLLogging.h" #define SYNCMLTARGET "SYNCML-SYNC" #define LINKERRORRESULT -2 using namespace DataSync; OBEXClientWorker::OBEXClientWorker( int aFd, qint32 aMTU, int aTimeOut ) : iFd( aFd ), iMTU( aMTU ), iTimeOut( aTimeOut ), iConnectionId( -1 ), iProcessing( false ) { } OBEXClientWorker::~OBEXClientWorker() { } void OBEXClientWorker::connect() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( isConnected() ) { qCDebug(lcSyncML) << "Already connected, ignoring connect attempt"; return; } if( !setupOpenOBEX( iFd, iMTU, OBEXClientWorker::handleEvent ) ) { qCCritical(lcSyncML) << "Could not set up OBEX link, aborting CONNECT"; return; } OBEX_SetUserData( getHandle(), this ); qCDebug(lcSyncML) << "Sending OBEX CONNECT"; OBEXDataHandler handler; OBEXDataHandler::ConnectCmdData data; data.iTarget = SYNCMLTARGET; obex_object_t* object = handler.createConnectCmd( getHandle(), data ); if( !object || OBEX_Request( getHandle(), object ) < 0 ) { qCCritical(lcSyncML) << "Failed in OBEX_Request while doing CONNECT"; return; } // Ignore return value; connect() should not emit errors, consecutive // calls to send() / receive() will emit them as connection is not up process(); } void OBEXClientWorker::disconnect() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( isConnected() ) { OBEXDataHandler handler; OBEXDataHandler::DisconnectCmdData data; data.iConnectionId = iConnectionId; obex_object_t* object = handler.createDisconnectCmd( getHandle(), data ); if( !object || OBEX_Request( getHandle(), object ) < 0 ) { // Cannot send disconnect, then we have no choice but to force transport // disconnection qCCritical(lcSyncML) << "Failed in OBEX_Request while doing DISCONNECT"; qCCritical(lcSyncML) << "Forcing link disconnect"; } else { // Ignore return value; we're disconnecting so even if something goes wrong, // there's nothing else to do but to close openobex process(); } closeOpenOBEX(); } else { qCDebug(lcSyncML) << "Not connected, ignoring sending OBEX DISCONNECT"; } } void OBEXClientWorker::send( const QByteArray& aBuffer, const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !isConnected() ) { qCWarning(lcSyncML) << "Connection not established, cannot send"; emit connectionFailed(); return; } OBEXDataHandler handler; OBEXDataHandler::PutCmdData data; data.iConnectionId = iConnectionId; data.iContentType = aContentType.toLatin1(); data.iLength = aBuffer.size(); data.iBody = aBuffer; obex_object_t* object = handler.createPutCmd( getHandle(), data ); if( !object || OBEX_Request( getHandle(), object ) < 0 ) { qCWarning(lcSyncML) << "Failed in OBEX_Request while doing PUT"; emit connectionError(); return; } int result = process(); if( result < 0 ) { qCWarning(lcSyncML) << "OBEX PUT failed"; emit connectionError(); } else if( result == 0 ) { qCWarning(lcSyncML) << "OBEX PUT timed out"; emit connectionTimeout(); } } void OBEXClientWorker::receive( const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !isConnected() ) { qCWarning(lcSyncML) << "Connection not established, cannot receive"; emit connectionFailed(); return; } OBEXDataHandler handler; OBEXDataHandler::GetCmdData data; data.iConnectionId = iConnectionId; data.iContentType = aContentType.toLatin1(); obex_object_t* object = handler.createGetCmd( getHandle(), data ); if( !object || OBEX_Request( getHandle(), object ) < 0 ) { qCWarning(lcSyncML) << "Failed in OBEX_Request while doing GET"; emit connectionError(); return; } iGetContentType = aContentType; int result = process(); if( result < 0 ) { qCWarning(lcSyncML) << "OBEX GET failed"; emit connectionError(); } else if( result == 0 ) { qCWarning(lcSyncML) << "OBEX GET timed out"; emit connectionTimeout(); } } int OBEXClientWorker::process() { FUNCTION_CALL_TRACE(lcSyncMLTrace); iProcessing = true; int result = 0; while( iProcessing ) { result = OBEX_HandleInput( getHandle(), iTimeOut ); if( isLinkError() ) { iProcessing = false; linkError(); result = LINKERRORRESULT; break; } else if( result <= 0 ) { iProcessing = false; break; } } return result; } void OBEXClientWorker::handleEvent( obex_t *aHandle, obex_object_t *aObject, int aMode, int aEvent, int aObexCmd, int aObexRsp ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); OBEXClientWorker* worker= (OBEXClientWorker*)OBEX_GetUserData( aHandle ); qCDebug(lcSyncML) << "OBEX Event: " << aEvent <<" Mode: " << aMode <<" Cmd: " << aObexCmd << " Resp: " << aObexRsp; switch( aEvent ) { // Request is done case OBEX_EV_REQDONE: { worker->RequestCompleted(aObject, aMode, aObexCmd, aObexRsp); break; } case OBEX_EV_LINKERR: case OBEX_EV_PARSEERR: case OBEX_EV_ABORT: { worker->setLinkError( true ); break; } default: { break; } } } void OBEXClientWorker::linkError() { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCCritical(lcSyncML) << "Link error occurred"; closeOpenOBEX(); setConnected( false ); } void OBEXClientWorker::RequestCompleted( obex_object_t *aObject, int aMode, int aObexCmd, int aObexRsp ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_UNUSED(aMode); Q_UNUSED(aObject); switch( aObexCmd ) { case OBEX_CMD_CONNECT: { ConnectResponse( aObject, aObexRsp ); break; } case OBEX_CMD_DISCONNECT: { DisconnectResponse( aObject, aObexRsp ); break; } case OBEX_CMD_PUT: { PutResponse( aObject, aObexRsp ); break; } case OBEX_CMD_GET: { GetResponse( aObject, aObexRsp ); break; } default: { break; } } } void OBEXClientWorker::ConnectResponse( obex_object_t *aObject, int aObexRsp ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aObexRsp == OBEX_RSP_SUCCESS ) { OBEXDataHandler handler; OBEXDataHandler::ConnectRspData data; if( handler.parseConnectRsp( getHandle(), aObject, data ) ) { iConnectionId = data.iConnectionId; qCDebug(lcSyncML) << "OBEX session established as client"; setConnected( true ); } else { qCWarning(lcSyncML) << "OBEX Connect: failed, remote device sent invalid response"; } } else { qCWarning(lcSyncML) << "OBEX Connect: failed, remote device sent " << aObexRsp; } iProcessing = false; } void OBEXClientWorker::DisconnectResponse( obex_object_t */*aObject*/, int /*aObexRsp*/ ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); qCDebug(lcSyncML) << "OBEX session disconnected as client"; iConnectionId = -1; setConnected( false ); iProcessing = false; } void OBEXClientWorker::PutResponse( obex_object_t *aObject, int aObexRsp ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_UNUSED(aObject); if( aObexRsp == OBEX_RSP_SUCCESS ) { qCDebug(lcSyncML) << "OBEX PUT succeeded"; } else { qCWarning(lcSyncML) << "OBEX PUT failed, remote device sent: " << aObexRsp; emit connectionError(); } iProcessing = false; } void OBEXClientWorker::GetResponse( obex_object_t *aObject, int aObexRsp ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( aObexRsp == OBEX_RSP_SUCCESS ) { qCDebug(lcSyncML) << "OBEX GET succeeded"; OBEXDataHandler handler; OBEXDataHandler::GetRspData rspData; if( handler.parseGetRsp( getHandle(), aObject, rspData ) ) { emit incomingData( rspData.iBody, iGetContentType ); } else { qCWarning(lcSyncML) << "Unexpected data in OBEX GET"; emit connectionError(); } } else { qCWarning(lcSyncML) << "OBEX GET failed, remote device sent: " << aObexRsp; if( aObexRsp == OBEX_RSP_NOT_FOUND ) { qCWarning(lcSyncML) << "Treating failure as session rejection"; emit sessionRejected(); } else { qCWarning(lcSyncML) << "Treating failure as generic connection error"; emit connectionError(); } } iProcessing = false; } buteo-syncml-0.5.15/src/transport/OBEXClientWorker.h000066400000000000000000000077151433763642500223340ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OBEXCLIENTWORKER_H #define OBEXCLIENTWORKER_H #include "OBEXWorker.h" namespace DataSync { /*! \brief Worker class for handling OBEX client functionality * */ class OBEXClientWorker : public OBEXWorker { Q_OBJECT; public: /*! \brief Constructor * * @param aFd File descriptor to use * @param aMTU MTU to use * @param aTimeOut Timeout to use in OBEX operations */ OBEXClientWorker( int aFd, qint32 aMTU, int aTimeOut ); /*! \brief Destructor * */ virtual ~OBEXClientWorker(); public slots: /*! \brief Slot for doing OBEX CONNECT * */ void connect(); /*! \brief Slot for doing OBEX DISCONNECT * */ void disconnect(); /*! \brief Slot for doing OBEX PUT * */ void send( const QByteArray& aBuffer, const QString& aContentType ); /*! \brief Slot for doing OBEX GET * */ void receive( const QString& aContentType ); signals: /*! \brief Emitted when data is available as a response to OBEX GET * * @param aData Data received * @param aContentType Content type of data */ void incomingData( QByteArray aData, QString aContentType ); /*! \brief Emitted when connection cannot be established * */ void connectionFailed(); /*! \brief Emitted when connection times out * */ void connectionTimeout(); /*! \brief Emitted when error occurs in connection * */ void connectionError(); /*! \brief Emitted when remote side has rejected the session * */ void sessionRejected(); private: int process(); static void handleEvent( obex_t *aHandle, obex_object_t *aObject, int aMode, int aEvent, int aObexCmd, int aObexRsp ); void linkError(); void RequestCompleted( obex_object_t *aObject, int aMode, int aObexCmd, int aObexRsp ); void ConnectResponse( obex_object_t *aObject, int aObexRsp ); void DisconnectResponse( obex_object_t *aObject, int aObexRsp ); void PutResponse( obex_object_t *aObject, int aObexRsp ); void GetResponse( obex_object_t *aObject, int aObexRsp ); int iFd; qint32 iMTU; int iTimeOut; int iConnectionId; bool iProcessing; QString iGetContentType; }; } #endif // OBEXCLIENTWORKER_H buteo-syncml-0.5.15/src/transport/OBEXConnection.h000066400000000000000000000047021433763642500220140ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OBEXCONNECTION_H #define OBEXCONNECTION_H namespace DataSync { /*! \brief Interface for OBEX transport layer * */ class OBEXConnection { public: /*! \brief Connect transport layer * * Invoked by SyncAgent when it requires a transport connection * * @return File descriptor of the opened connection on success, otherwise -1 */ virtual int connect() = 0; /*! \brief Returns whether connection is established * * @return True if currently connected, otherwise false */ virtual bool isConnected() const = 0; /*! \brief Disconnects connection * * Invoked by SyncAgent when it no longer requires a transport connection */ virtual void disconnect() = 0; /*! \brief Destructor * */ virtual ~OBEXConnection() { } }; } #endif // OBEXCONNECTION_H buteo-syncml-0.5.15/src/transport/OBEXDataHandler.cpp000066400000000000000000000351301433763642500224160ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "OBEXDataHandler.h" #include "SyncMLLogging.h" using namespace DataSync; OBEXDataHandler::OBEXDataHandler() { } OBEXDataHandler:: ~OBEXDataHandler() { } obex_object_t* OBEXDataHandler::createConnectCmd( obex_t* aHandle, const ConnectCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); obex_headerdata_t header; obex_object_t* object = OBEX_ObjectNew( aHandle, OBEX_CMD_CONNECT ); if( object ) { // Target header QByteArray target = aData.iTarget; header.bs = (uint8_t*)target.constData(); int err = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_TARGET, header, target.size(), OBEX_FL_FIT_ONE_PACKET ); if( err == -1 ) { OBEX_ObjectDelete( aHandle, object ); object = NULL; } } return object; } bool OBEXDataHandler::parseConnectCmd( obex_t* aHandle, obex_object_t* aObject, ConnectCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); uint8_t headertype; obex_headerdata_t header; uint32_t len; bool targetFound = false; while( OBEX_ObjectGetNextHeader( aHandle, aObject, &headertype, &header, &len ) ) { switch( headertype ) { case OBEX_HDR_TARGET: { aData.iTarget = QByteArray( (char *)header.bs, len ); targetFound = true; qCDebug(lcSyncML) << "Found target: " << aData.iTarget; break; } default: { qCDebug(lcSyncML) << "Unknown header: " << headertype; break; } } } if( targetFound ) { return true; } else { return false; } } bool OBEXDataHandler::createConnectRsp( obex_t* aHandle, obex_object_t* aObject, const ConnectRspData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); obex_headerdata_t header; header.bq4 = aData.iConnectionId; int err1 = OBEX_ObjectAddHeader( aHandle, aObject, OBEX_HDR_CONNECTION, header, sizeof( header.bq4 ), OBEX_FL_FIT_ONE_PACKET ); QByteArray who = aData.iWho; header.bs = (uint8_t*)who.constData(); int err2 = OBEX_ObjectAddHeader( aHandle, aObject, OBEX_HDR_WHO, header, who.size(), OBEX_FL_FIT_ONE_PACKET ); if( err1 == -1 || err2 == -1 ) { return false; } else { return true; } } bool OBEXDataHandler::parseConnectRsp( obex_t* aHandle, obex_object_t* aObject, ConnectRspData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); uint8_t headertype; obex_headerdata_t header; uint32_t len; bool connIdFound = false; bool whoFound = false; while( OBEX_ObjectGetNextHeader( aHandle, aObject, &headertype, &header, &len ) ) { switch( headertype ) { case OBEX_HDR_CONNECTION: { aData.iConnectionId = header.bq4; connIdFound = true; qCDebug(lcSyncML) << "Found connection id: " << aData.iConnectionId; break; } case OBEX_HDR_WHO: { aData.iWho = QByteArray( (char *)header.bs, len ); whoFound = true; qCDebug(lcSyncML) << "Found who: " << aData.iWho; break; } default: { qCDebug(lcSyncML) << "Unknown header: " << headertype; break; } } } if( connIdFound && whoFound ) { return true; } else { return false; } } obex_object_t* OBEXDataHandler::createDisconnectCmd( obex_t* aHandle, const DisconnectCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); obex_headerdata_t header; obex_object_t* object = OBEX_ObjectNew( aHandle, OBEX_CMD_DISCONNECT ); if( object ) { // Connection ID header header.bq4 = aData.iConnectionId; int err = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_CONNECTION, header, sizeof( header.bq4 ), OBEX_FL_FIT_ONE_PACKET ); if( err == -1 ) { OBEX_ObjectDelete( aHandle, object ); object = NULL; } } return object; } bool OBEXDataHandler::parseDisconnectCmd( obex_t* aHandle, obex_object_t* aObject, DisconnectCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); uint8_t headertype; obex_headerdata_t header; uint32_t len; bool connIdFound = false; while( OBEX_ObjectGetNextHeader( aHandle, aObject, &headertype, &header, &len ) ) { switch( headertype ) { case OBEX_HDR_CONNECTION: { aData.iConnectionId = header.bq4; connIdFound = true; qCDebug(lcSyncML) << "Found connection id: " << aData.iConnectionId; break; } default: { qCDebug(lcSyncML) << "Unknown header: " << headertype; break; } } } if( connIdFound ){ return true; } else { return false; } } obex_object_t* OBEXDataHandler::createPutCmd( obex_t* aHandle, const PutCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); obex_headerdata_t header; obex_object_t* object = OBEX_ObjectNew( aHandle, OBEX_CMD_PUT ); if( object ) { // Connection ID header header.bq4 = aData.iConnectionId; int err1 = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_CONNECTION, header, sizeof( header.bq4 ), OBEX_FL_FIT_ONE_PACKET ); // Content type header QByteArray contentType = aData.iContentType; header.bs = (uint8_t*)contentType.constData(); int err2 = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_TYPE, header, contentType.size()+1, OBEX_FL_FIT_ONE_PACKET ); // Length header header.bq4 = aData.iLength; int err3 = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_LENGTH, header, sizeof( header.bq4 ), OBEX_FL_FIT_ONE_PACKET ); // Add body header.bs = (uint8_t*)aData.iBody.constData(); int err4 = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_BODY, header, aData.iBody.size(), 0 ); if( err1 == -1 || err2 == -1 || err3 == -1 || err4 == -1 ) { OBEX_ObjectDelete( aHandle, object ); object = NULL; } } return object; } bool OBEXDataHandler::parsePutCmd( obex_t* aHandle, obex_object_t* aObject, PutCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); uint8_t headertype; obex_headerdata_t header; uint32_t len; bool connIdFound = false; bool typeFound = false; bool lengthFound = false; aData.iLength = -1; aData.iUnsupportedHeaders = false; while( OBEX_ObjectGetNextHeader( aHandle, aObject, &headertype, &header, &len ) ) { switch( headertype ) { case OBEX_HDR_CONNECTION: { aData.iConnectionId = header.bq4;; connIdFound = true; qCDebug(lcSyncML) << "Found connection id: " << aData.iConnectionId; break; } case OBEX_HDR_TYPE: { aData.iContentType = QByteArray( (char *)header.bs ); typeFound = true; qCDebug(lcSyncML) << "Found type: " << aData.iContentType; break; } case OBEX_HDR_LENGTH: { aData.iLength = header.bq4; lengthFound = true; qCDebug(lcSyncML) << "Found length: " << aData.iLength; break; } case OBEX_HDR_BODY: { QByteArray body( (char*)header.bs, len ); aData.iBody.append( body ); qCDebug(lcSyncML) << "Found body with length of " << len << " bytes"; break; } case OBEX_HDR_BODY_END: { QByteArray body( (char*)header.bs, len ); aData.iBody.append( body ); qCDebug(lcSyncML) << "Found end of body"; break; } default: { qCDebug(lcSyncML) << "Unknown header: " << headertype; aData.iUnsupportedHeaders = true; break; } } } if( !connIdFound ) { qCDebug(lcSyncML) << "Warning: no connection id header found"; } if( typeFound ) { return true; } else { qCWarning(lcSyncML) << "Request did not include TYPE header as expected"; return false; } } obex_object_t* OBEXDataHandler::createGetCmd( obex_t* aHandle, const GetCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); obex_headerdata_t header; obex_object_t* object = OBEX_ObjectNew( aHandle, OBEX_CMD_GET ); if( object ) { // Connection ID header header.bq4 = aData.iConnectionId; int err1 = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_CONNECTION, header, sizeof( header.bq4 ), OBEX_FL_FIT_ONE_PACKET ); // Content type header QByteArray contentType = aData.iContentType; header.bs = (uint8_t*)contentType.constData(); int err2 = OBEX_ObjectAddHeader( aHandle, object, OBEX_HDR_TYPE, header, contentType.size()+1, OBEX_FL_FIT_ONE_PACKET ); if( err1 == -1 || err2 == -1 ) { OBEX_ObjectDelete( aHandle, object ); object = NULL; } } return object; } bool OBEXDataHandler::parseGetCmd( obex_t* aHandle, obex_object_t* aObject, GetCmdData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); uint8_t headertype; obex_headerdata_t header; uint32_t len; bool connIdFound = false; bool typeFound = false; while( OBEX_ObjectGetNextHeader( aHandle, aObject, &headertype, &header, &len ) ) { switch( headertype ) { case OBEX_HDR_CONNECTION: { aData.iConnectionId = header.bq4;; connIdFound = true; qCDebug(lcSyncML) << "Found connection id: " << aData.iConnectionId; break; } case OBEX_HDR_TYPE: { aData.iContentType = QByteArray( (char *)header.bs ); typeFound = true; qCDebug(lcSyncML) << "Found type: " << aData.iContentType; break; } } } if( !connIdFound ) { qCDebug(lcSyncML) << "Warning: no connection id header found"; } if( typeFound ) { return true; } else { return false; } } bool OBEXDataHandler::createGetRsp( obex_t* aHandle, obex_object_t* aObject, const GetRspData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); obex_headerdata_t header; // Length header header.bq4 = aData.iLength; int err1 = OBEX_ObjectAddHeader( aHandle, aObject, OBEX_HDR_LENGTH, header, sizeof( header.bq4 ), OBEX_FL_FIT_ONE_PACKET ); // Add body header.bs = (uint8_t*)aData.iBody.constData(); int err2 = OBEX_ObjectAddHeader( aHandle, aObject, OBEX_HDR_BODY, header, aData.iBody.size(), 0 ); if( err1 == -1 || err2 == -1 ) { return false; } else { return true; } } bool OBEXDataHandler::parseGetRsp( obex_t* aHandle, obex_object_t* aObject, GetRspData& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); uint8_t headertype; obex_headerdata_t header; uint32_t len; aData.iLength = -1; bool lengthFound = false; while( OBEX_ObjectGetNextHeader( aHandle, aObject, &headertype, &header, &len ) ) { switch( headertype ) { case OBEX_HDR_LENGTH: { aData.iLength = header.bq4; lengthFound = true; qCDebug(lcSyncML) << "Found length: " << aData.iLength; break; } case OBEX_HDR_BODY: { QByteArray body( (char*)header.bs, len ); aData.iBody.append( body ); qCDebug(lcSyncML) << "Found body with length of " << len << " bytes"; break; } case OBEX_HDR_BODY_END: { QByteArray body( (char*)header.bs, len ); aData.iBody.append( body ); qCDebug(lcSyncML) << "Found end of body"; break; } default: { qCDebug(lcSyncML) << "Unknown header: " << headertype; break; } } } return true; } buteo-syncml-0.5.15/src/transport/OBEXDataHandler.h000066400000000000000000000170271433763642500220700ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OBEXDATAHANDLER_H #define OBEXDATAHANDLER_H #include #include namespace DataSync { /*! \brief Utility class for doing various OBEX operations * */ class OBEXDataHandler { public: /*! \brief Constructor * */ OBEXDataHandler(); /*! \brief Destructor * */ virtual ~OBEXDataHandler(); /*! \brief Structure for sending SyncML Connect * */ struct ConnectCmdData { QByteArray iTarget; ///< OBEX Target header }; /*! \brief Structure for responding to SyncML Connect * */ struct ConnectRspData { unsigned int iConnectionId; ///< OBEX Connection header QByteArray iWho; ///< OBEX Who header }; /*! \brief Structure for sending SyncML Disconnect * */ struct DisconnectCmdData { unsigned int iConnectionId; ///< OBEX Connection header }; /*! \brief Structure for sending SyncML Put * */ struct PutCmdData { unsigned int iConnectionId; ///< OBEX Connection header QByteArray iContentType; ///< OBEX Type header int iLength; ///< OBEX Length header QByteArray iBody; ///< OBEX Body header bool iUnsupportedHeaders; ///< True if PUT included unsupported headers }; /*! \brief Structure for sending SyncML Get * */ struct GetCmdData { unsigned int iConnectionId; ///< OBEX Connection header QByteArray iContentType; ///< OBEX Type header }; /*! \brief Structure for responding to SyncML Get * */ struct GetRspData { unsigned int iLength; ///< OBEX Length header QByteArray iBody; ///< OBEX Body header }; /*! \brief Generate OBEX object representing SyncML Connect * * @param aHandle OBEX handle * @param aData SyncML Connect data * @return OBEX object if successful, otherwise NULL */ obex_object_t* createConnectCmd( obex_t* aHandle, const ConnectCmdData& aData ); /*! \brief Parse OBEX object representing SyncML Connect * * @param aHandle OBEX handle * @param aObject OBEX object * @param aData Structure where to place parsing results * @return True if object is valid SyncML Connect, otherwise false */ bool parseConnectCmd( obex_t* aHandle, obex_object_t* aObject, ConnectCmdData& aData ); /*! \brief Generate a response object for SyncML Connect * * @param aHandle OBEX handle * @param aObject OBEX object to append data to * @param aData SyncML Connect response data * @return True if operation was successful, false otherwise */ bool createConnectRsp( obex_t* aHandle, obex_object_t* aObject, const ConnectRspData& aData ); /*! \brief Parse OBEX object representing response to SyncML Connect * * @param aHandle OBEX handle * @param aObject OBEX object * @param aData Structure where to place parsing results * @return True if object is valid response to SyncML Connect, otherwise false */ bool parseConnectRsp( obex_t* aHandle, obex_object_t* aObject, ConnectRspData& aData ); /*! \brief Generate OBEX object representing SyncML Disconnect * * @param aHandle OBEX handle * @param aData SyncML Disconnect data * @return OBEX object if successful, otherwise NULL */ obex_object_t* createDisconnectCmd( obex_t* aHandle, const DisconnectCmdData& aData ); /*! \brief Parse OBEX object representing SyncML Disconnect * * @param aHandle OBEX handle * @param aObject OBEX object * @param aData Structure where to place parsing results * @return True if object is valid SyncML Disconnect, otherwise false */ bool parseDisconnectCmd( obex_t* aHandle, obex_object_t* aObject, DisconnectCmdData& aData ); /*! \brief Generate OBEX object representing SyncML Put * * @param aHandle OBEX handle * @param aData SyncML Put data * @return OBEX object if successful, otherwise NULL */ obex_object_t* createPutCmd( obex_t* aHandle, const PutCmdData& aData ); /*! \brief Parse OBEX object representing SyncML Put * * @param aHandle OBEX handle * @param aObject OBEX object * @param aData Structure where to place parsing results * @return True if object is valid SyncML Put, otherwise false */ bool parsePutCmd( obex_t* aHandle, obex_object_t* aObject, PutCmdData& aData ); /*! \brief Generate OBEX object representing SyncML Get * * @param aHandle OBEX handle * @param aData SyncML Get data * @return OBEX object if successful, otherwise NULL */ obex_object_t* createGetCmd( obex_t* aHandle, const GetCmdData& aData ); /*! \brief Parse OBEX object representing SyncML Get * * @param aHandle OBEX handle * @param aObject OBEX object * @param aData Structure where to place parsing results * @return True if object is valid SyncML Get, otherwise false */ bool parseGetCmd( obex_t* aHandle, obex_object_t* aObject, GetCmdData& aData ); /*! \brief Generate a response object for SyncML Get * * @param aHandle OBEX handle * @param aObject OBEX object to append data to * @param aData SyncML Get response data * @return True if operation was successful, otherwise false */ bool createGetRsp( obex_t* aHandle, obex_object_t* aObject, const GetRspData& aData ); /*! \brief Parse OBEX object representing response to SyncML Get * * @param aHandle OBEX handle * @param aObject OBEX object * @param aData Structure where to place parsing results * @return True if object is valid response to SyncML Get, otherwise false */ bool parseGetRsp( obex_t* aHandle, obex_object_t* aObject, GetRspData& aData ); }; } #endif // OBEXDATAHANDLER_H buteo-syncml-0.5.15/src/transport/OBEXServerWorker.cpp000066400000000000000000000334751433763642500227210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "OBEXServerWorker.h" #include "OBEXDataHandler.h" #include "SyncMLLogging.h" #define SYNCMLTARGET "SYNCML-SYNC" using namespace DataSync; OBEXServerWorker::OBEXServerWorker( OBEXServerDataSource& aSource, int aFd, qint32 aMTU, int aTimeOut ) : iSource( aSource ), iFd( aFd ), iMTU( aMTU ), iTimeOut( aTimeOut ), iConnectionId( 1 ), iProcessing( false ), iState( STATE_IDLE ) { } OBEXServerWorker::~OBEXServerWorker() { } void OBEXServerWorker::waitForConnect() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( isConnected() ) { qCDebug(lcSyncML) << "Already connected, ignoring connect attempt"; return; } if( !setupOpenOBEX( iFd, iMTU, OBEXServerWorker::handleEvent ) ) { qCCritical(lcSyncML) << "Could not set up OBEX link, aborting CONNECT"; return; } OBEX_SetUserData( getHandle(), this ); qCDebug(lcSyncML) << "Waiting for OBEX CONNECT"; process( STATE_CONNECT ); } void OBEXServerWorker::waitForDisconnect() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( isConnected() ) { qCDebug(lcSyncML) << "Waiting for OBEX DISCONNECT"; process( STATE_DISCONNECT ); } else { qCDebug(lcSyncML) << "Not connected, ignoring disconnect attempt"; } closeOpenOBEX(); } void OBEXServerWorker::waitForPut() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( isConnected() ) { qCDebug(lcSyncML) << "Waiting for OBEX PUT"; process( STATE_PUT ); } else { qCWarning(lcSyncML) << "Connection not established, cannot wait for PUT"; emit connectionFailed(); } } void OBEXServerWorker::waitForGet() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( isConnected() ) { qCDebug(lcSyncML) << "Waiting for OBEX GET"; process( STATE_GET ); } else { qCWarning(lcSyncML) << "Connection not established, cannot wait for GET"; emit connectionFailed(); } } void OBEXServerWorker::process( State aNextState ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); int result = 0; iState = aNextState; iProcessing = true; while( iProcessing ) { result = OBEX_HandleInput( getHandle(), iTimeOut ); if( isLinkError() ) { iState = STATE_IDLE; iProcessing = false; linkError(); emit connectionError(); break; } else if( result < 0 ) { qCWarning(lcSyncML) << "OBEX operation failed"; iState = STATE_IDLE; iProcessing = false; emit connectionError(); } else if( result == 0 ) { qCWarning(lcSyncML) << "OBEX timeout"; iState = STATE_IDLE; iProcessing = false; emit connectionTimeout(); } } } void OBEXServerWorker::handleEvent( obex_t *aHandle, obex_object_t *aObject, int aMode, int aEvent, int aObexCmd, int aObexRsp ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); OBEXServerWorker* worker= (OBEXServerWorker*)OBEX_GetUserData( aHandle ); qCDebug(lcSyncML) << "OBEX Event: " << aEvent <<" Mode: " << aMode <<" Cmd: " << aObexCmd << " Resp: " << aObexRsp; switch( aEvent ) { case OBEX_EV_REQHINT: { if( aObexCmd == OBEX_CMD_CONNECT || aObexCmd == OBEX_CMD_DISCONNECT || aObexCmd == OBEX_CMD_PUT || aObexCmd == OBEX_CMD_GET ) { OBEX_ObjectSetRsp( aObject, OBEX_RSP_CONTINUE, OBEX_RSP_CONTINUE ); } else { qCWarning(lcSyncML) << "Ignoring command related to unimplemented service"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_NOT_IMPLEMENTED, OBEX_RSP_NOT_IMPLEMENTED ); } break; } case OBEX_EV_REQ: { worker->requestReceived(aObject,aMode,aObexCmd); break; } case OBEX_EV_LINKERR: case OBEX_EV_PARSEERR: case OBEX_EV_ABORT: { worker->setLinkError( true ); break; } default: { break; } } } void OBEXServerWorker::linkError() { FUNCTION_CALL_TRACE(lcSyncMLTrace); iState = STATE_IDLE; iProcessing = false; if( isConnected() ) { setConnected( false ); closeOpenOBEX(); emit connectionError(); } qCCritical(lcSyncML) << "Link error occurred"; closeOpenOBEX(); setConnected( false ); } void OBEXServerWorker::requestReceived( obex_object_t *aObject, int aMode, int aObexCmd ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); Q_UNUSED(aMode); switch( aObexCmd ) { // Accept only supported commands case OBEX_CMD_CONNECT: { ConnectRequest( aObject ); break; } case OBEX_CMD_DISCONNECT: { DisconnectRequest( aObject ); break; } case OBEX_CMD_PUT: { if( iState == STATE_PUT ) { PutRequest( aObject ); } else { OBEX_ObjectSetRsp( aObject, OBEX_RSP_SERVICE_UNAVAILABLE, OBEX_RSP_SERVICE_UNAVAILABLE ); } break; } case OBEX_CMD_GET: { if( iState == STATE_GET ) { GetRequest( aObject ); } else { OBEX_ObjectSetRsp( aObject, OBEX_RSP_SERVICE_UNAVAILABLE, OBEX_RSP_SERVICE_UNAVAILABLE ); } break; } default: { qCWarning(lcSyncML) << "Ignoring command related to unimplemented service"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_NOT_IMPLEMENTED, OBEX_RSP_NOT_IMPLEMENTED ); break; } } } void OBEXServerWorker::ConnectRequest( obex_object_t *aObject ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( isConnected() ) { qCWarning(lcSyncML) << "Already connected, ignoring CONNECT"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_SERVICE_UNAVAILABLE, OBEX_RSP_SERVICE_UNAVAILABLE ); return; } OBEXDataHandler handler; OBEXDataHandler::ConnectCmdData cmdData; if( !handler.parseConnectCmd( getHandle(), aObject, cmdData ) ) { qCWarning(lcSyncML) << "Could not parse CONNECT request, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_BAD_REQUEST, OBEX_RSP_BAD_REQUEST ); return; } if( cmdData.iTarget != SYNCMLTARGET ) { qCWarning(lcSyncML) << "CONNECT request not directed to SyncML, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_NOT_FOUND, OBEX_RSP_NOT_FOUND ); return; } qCDebug(lcSyncML) << "Assigning connection id: " << iConnectionId; OBEXDataHandler::ConnectRspData rspData; rspData.iConnectionId = iConnectionId; rspData.iWho = cmdData.iTarget; if( !handler.createConnectRsp( getHandle(), aObject, rspData ) ) { qCCritical(lcSyncML) << "Internal error when creating CONNECT response"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_INTERNAL_SERVER_ERROR, OBEX_RSP_INTERNAL_SERVER_ERROR ); return; } OBEX_ObjectSetRsp( aObject, OBEX_RSP_CONTINUE, OBEX_RSP_SUCCESS ); qCDebug(lcSyncML) << "OBEX session established as server"; setConnected( true ); iProcessing = false; iState = STATE_IDLE; } void OBEXServerWorker::DisconnectRequest( obex_object_t *aObject ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !isConnected() ) { qCWarning(lcSyncML) << "Not connected, ignoring DISCONNECT"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_SERVICE_UNAVAILABLE, OBEX_RSP_SERVICE_UNAVAILABLE ); return; } OBEXDataHandler handler; OBEXDataHandler::DisconnectCmdData data; if( !handler.parseDisconnectCmd( getHandle(), aObject, data ) ) { qCWarning(lcSyncML) << "Could not parse DISCONNECT request, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_BAD_REQUEST, OBEX_RSP_BAD_REQUEST ); return; } if( data.iConnectionId != iConnectionId ) { qCWarning(lcSyncML) << "Received DISCONNECT request not matching the session, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_NOT_FOUND, OBEX_RSP_NOT_FOUND ); return; } OBEX_ObjectSetRsp( aObject, OBEX_RSP_CONTINUE, OBEX_RSP_SUCCESS ); if( iState != STATE_DISCONNECT ) { qCWarning(lcSyncML) << "Unexpected OBEX DISCONNECT received, presuming connection error"; emit connectionError(); } qCDebug(lcSyncML) << "OBEX session disconnected as server"; setConnected( false ); iProcessing = false; iState = STATE_IDLE; } void OBEXServerWorker::PutRequest( obex_object_t *aObject ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !isConnected() ) { qCWarning(lcSyncML) << "Not connected, ignoring PUT"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_SERVICE_UNAVAILABLE, OBEX_RSP_SERVICE_UNAVAILABLE ); return; } OBEXDataHandler handler; OBEXDataHandler::PutCmdData data; if( !handler.parsePutCmd( getHandle(), aObject, data ) ) { qCWarning(lcSyncML) << "Could not parse PUT request, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_BAD_REQUEST, OBEX_RSP_BAD_REQUEST ); return; } if( data.iUnsupportedHeaders ) { qCWarning(lcSyncML) << "PUT request included unsupported headers, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_CONTINUE, OBEX_RSP_SUCCESS ); return; } if( data.iConnectionId != iConnectionId ) { qCWarning(lcSyncML) << "Received PUT request not matching the session, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_NOT_FOUND, OBEX_RSP_NOT_FOUND ); return; } OBEX_ObjectSetRsp( aObject, OBEX_RSP_CONTINUE, OBEX_RSP_SUCCESS ); qCDebug(lcSyncML) << "Received PUT with body size of:" << data.iBody.size() <<", content type:" << data.iContentType; iProcessing = false; iState = STATE_IDLE; emit incomingData( data.iBody, data.iContentType ); } void OBEXServerWorker::GetRequest( obex_object_t *aObject ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !isConnected() ) { qCWarning(lcSyncML) << "Not connected, ignoring GET"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_SERVICE_UNAVAILABLE, OBEX_RSP_SERVICE_UNAVAILABLE ); return; } OBEXDataHandler handler; OBEXDataHandler::GetCmdData cmdData; if( !handler.parseGetCmd( getHandle(), aObject, cmdData ) ) { qCWarning(lcSyncML) << "Could not parse GET request, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_BAD_REQUEST, OBEX_RSP_BAD_REQUEST ); return; } if( cmdData.iConnectionId != iConnectionId ) { qCWarning(lcSyncML) << "Received GET request not matching the session, ignoring"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_NOT_FOUND, OBEX_RSP_NOT_FOUND ); return; } QByteArray data; if( iSource.getData( QString::fromLatin1( cmdData.iContentType ), data ) ) { OBEXDataHandler::GetRspData rspData; rspData.iBody = data; rspData.iLength = data.length(); if( handler.createGetRsp( getHandle(), aObject, rspData ) ) { OBEX_ObjectSetRsp( aObject, OBEX_RSP_CONTINUE, OBEX_RSP_SUCCESS ); qCDebug(lcSyncML) << "Responded to GET request for content type" << cmdData.iContentType << "with response of" << data.length() << "bytes"; } else { qCCritical(lcSyncML) << "Error when generating OBEX GET response"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_INTERNAL_SERVER_ERROR, OBEX_RSP_INTERNAL_SERVER_ERROR ); } } else { qCCritical(lcSyncML) << "Could not retrieve response data for GET!"; OBEX_ObjectSetRsp( aObject, OBEX_RSP_INTERNAL_SERVER_ERROR, OBEX_RSP_INTERNAL_SERVER_ERROR ); } iProcessing = false; iState = STATE_IDLE; } buteo-syncml-0.5.15/src/transport/OBEXServerWorker.h000066400000000000000000000111031433763642500223460ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OBEXSERVERWORKER_H #define OBEXSERVERWORKER_H #include "OBEXWorker.h" namespace DataSync { /*! \brief Data source for OBEX Server * */ class OBEXServerDataSource { public: /*! \brief Destructor * */ virtual ~OBEXServerDataSource() { } /*! \brief Retrieve data from source * * @param aContentType Content type for data to retrieve * @param aData Retrieved data buffer * @return True on success, otherwise false */ virtual bool getData( const QString& aContentType, QByteArray& aData ) = 0; }; /*! \brief Worker class for handling OBEX server functionality * */ class OBEXServerWorker : public OBEXWorker { Q_OBJECT; public: /*! \brief Constructor * * @param aSource Data source to use * @param aFd File descriptor to use * @param aMTU MTU to use * @param aTimeOut Timeout to use in OBEX operations */ OBEXServerWorker( OBEXServerDataSource& aSource, int aFd, qint32 aMTU, int aTimeOut ); /*! \brief Destructor * */ virtual ~OBEXServerWorker(); public slots: /*! \brief Slot for waiting to receive OBEX CONNECT * */ void waitForConnect(); /*! \brief Slot for waiting to receive OBEX DISCONNECT * */ void waitForDisconnect(); /*! \brief Slot for waiting to receive OBEX PUT * */ void waitForPut(); /*! \brief Slot for waiting to receive OBEX GET * */ void waitForGet(); signals: /*! \brief Emitted when data is available as a response to OBEX GET * * @param aData Data received * @param aContentType Content type of data */ void incomingData( QByteArray aData, QString aContentType ); /*! \brief Emitted when connection cannot be established * */ void connectionFailed(); /*! \brief Emitted when connection times out * */ void connectionTimeout(); /*! \brief Emitted when error occurs in connection * */ void connectionError(); private: enum State { STATE_IDLE, STATE_CONNECT, STATE_DISCONNECT, STATE_PUT, STATE_GET }; void process( State aNextState ); static void handleEvent( obex_t *aHandle, obex_object_t *aObject, int aMode, int aEvent, int aObexCmd, int aObexRsp ); void linkError(); void requestReceived( obex_object_t *aObject, int aMode, int aObexCmd ); void ConnectRequest( obex_object_t *aObject ); void DisconnectRequest( obex_object_t *aObject ); void PutRequest( obex_object_t *aObject ); void GetRequest( obex_object_t *aObject ); OBEXServerDataSource& iSource; int iFd; qint32 iMTU; int iTimeOut; unsigned int iConnectionId; bool iProcessing; State iState; }; } #endif // OBEXSERVERWORKER_H buteo-syncml-0.5.15/src/transport/OBEXTransport.cpp000066400000000000000000000251321433763642500222440ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "OBEXTransport.h" #include "datatypes.h" #include "SyncMLMessage.h" #include "SyncAgentConfigProperties.h" #include "OBEXConnection.h" #include "SyncMLLogging.h" // Default MTU, recommended by OpenOBEX #define DEFAULT_MTU 1024 // Default OBEX timeout #define DEFAULT_TIMEOUT 120 using namespace DataSync; OBEXTransport::OBEXTransport( OBEXConnection& aConnection, Mode aOpMode, ConnectionTypeHint aTypeHint, const ProtocolContext& aContext, QObject* aParent ) : BaseTransport( aContext, aParent ), iConnection( aConnection ), iMode( aOpMode ), iTimeOut( DEFAULT_TIMEOUT ), iTypeHint( aTypeHint ), iWorkerThread( 0 ), iWorker( 0 ), iMTU( DEFAULT_MTU ), iMessage( 0 ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); } OBEXTransport::~OBEXTransport() { FUNCTION_CALL_TRACE(lcSyncMLTrace); close(); } void OBEXTransport::setProperty( const QString& aProperty, const QString& aValue ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); //obex-mtu-bt: if( aProperty == OBEXMTUBTPROP && iTypeHint == TYPEHINT_BT ) { qCDebug(lcSyncML) << "Setting property" << aProperty <<":" << aValue; iMTU = aValue.toInt(); } //obex-mtu-usb: else if( aProperty == OBEXMTUUSBPROP&& iTypeHint == TYPEHINT_USB ) { qCDebug(lcSyncML) << "Setting property" << aProperty <<":" << aValue; iMTU = aValue.toInt(); } //obex-mtu-other: else if( aProperty == OBEXMTUOTHERPROP && iTypeHint == TYPEHINT_OTHER ) { qCDebug(lcSyncML) << "Setting property" << aProperty <<":" << aValue; iMTU = aValue.toInt(); } else if( aProperty == OBEXTIMEOUTPROP ) { qCDebug(lcSyncML) << "Setting property" << aProperty <<":" << aValue; iTimeOut = aValue.toInt(); } } bool OBEXTransport::init() { FUNCTION_CALL_TRACE(lcSyncMLTrace); int fd = iConnection.connect(); if( !iConnection.isConnected() ) { return false; } if( iMode == MODE_OBEX_CLIENT ) { setupClient( fd ); } else if( iMode == MODE_OBEX_SERVER ) { setupServer( fd ); } else { Q_ASSERT(0); } return true; } void OBEXTransport::close() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iWorkerThread && iWorkerThread->isRunning() ) { if( iWorker->isConnected() ) { if( iMode == MODE_OBEX_CLIENT ) { QMetaObject::invokeMethod( iWorker, "disconnect", Qt::BlockingQueuedConnection ); } else if( iMode == MODE_OBEX_SERVER ) { QMetaObject::invokeMethod( iWorker, "waitForDisconnect", Qt::BlockingQueuedConnection ); } else { Q_ASSERT(0); } } iWorkerThread->exit(); // Wait for the thread to finish. After it, force it to terminate to // make sure it doesn't stay running. if( !iWorkerThread->wait( iTimeOut * 1000 ) ) { iWorkerThread->terminate(); } } delete iWorkerThread; iWorkerThread = 0; delete iMessage; iMessage = 0; if( iConnection.isConnected() ) { iConnection.disconnect(); } } void OBEXTransport::setupClient( int aFd ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); OBEXClientWorker* worker = new OBEXClientWorker( aFd, iMTU, iTimeOut ); connect( worker, SIGNAL(incomingData(QByteArray,QString) ), this, SLOT(incomingData(QByteArray,QString) ) ); connect( worker, SIGNAL(connectionFailed()), this, SLOT(connectionFailed()), Qt::QueuedConnection ); connect( worker, SIGNAL(connectionTimeout()), this, SLOT(connectionTimeout()), Qt::QueuedConnection ); connect( worker, SIGNAL(connectionError()), this, SLOT(connectionError()), Qt::QueuedConnection ); connect( worker, SIGNAL(sessionRejected()), this, SLOT(sessionRejected()), Qt::QueuedConnection ); iWorkerThread = new OBEXWorkerThread( worker ); iWorker = worker; iWorkerThread->start(); } void OBEXTransport::setupServer( int aFd ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); OBEXServerWorker* worker = new OBEXServerWorker( *this, aFd, iMTU, iTimeOut ); connect( worker, SIGNAL(incomingData(QByteArray,QString) ), this, SLOT(incomingData(QByteArray,QString) ) ); connect( worker, SIGNAL(connectionFailed()), this, SLOT(connectionFailed()), Qt::QueuedConnection ); connect( worker, SIGNAL(connectionTimeout()), this, SLOT(connectionTimeout()), Qt::QueuedConnection ); connect( worker, SIGNAL(connectionError()), this, SLOT(connectionError()), Qt::QueuedConnection ); iWorkerThread = new OBEXWorkerThread( worker ); iWorker = worker; iWorkerThread->start(); } bool OBEXTransport::sendSyncML( SyncMLMessage* aMessage ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); // Normally when sending a SyncML message, the message is pushed // to the remote device. When in OBEX server mode, the message is // instead pulled by the remote device with OBEX GET. Also the // encoding (XML/WbXML) to be used is known only when the GET // command has been received, and not immediately when the message // can be pushed. For this reason, BaseTransport::sendSyncML() // implementation cannot be used in OBEX server mode. Instead we // must save the message, and supply it to the OBEX server worker // when the data is being pulled (with the encoding specified by // GET command ) if( iMode == MODE_OBEX_SERVER ) { delete iMessage; iMessage = aMessage; QMetaObject::invokeMethod( iWorker, "waitForGet", Qt::QueuedConnection ); return true; } else { return BaseTransport::sendSyncML( aMessage ); } } bool OBEXTransport::getData( const QString& aContentType, QByteArray& aData ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iMessage ) { return false; } bool success = false; if( aContentType == SYNCML_CONTTYPE_DS_WBXML || aContentType == SYNCML_CONTTYPE_DM_WBXML ) { setWbXml(true); encodeMessage(*iMessage, aData ); success = true; } else if( aContentType == SYNCML_CONTTYPE_DS_XML || aContentType == SYNCML_CONTTYPE_DM_XML ) { setWbXml(false); encodeMessage(*iMessage, aData ); success = true; } else { qCCritical(lcSyncML) << "Unsupported content type:" << aContentType; } delete iMessage; iMessage = 0; return success; } bool OBEXTransport::prepareSend() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iMode == MODE_OBEX_CLIENT ) { if( !iWorker->isConnected() ) { QMetaObject::invokeMethod( iWorker, "connect", Qt::BlockingQueuedConnection ); } } else if( iMode == MODE_OBEX_SERVER ) { // Don't need to do anything in server mode } else { Q_ASSERT(0); } return true; } bool OBEXTransport::doSend( const QByteArray& aData, const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iMode == MODE_OBEX_CLIENT ) { QMetaObject::invokeMethod( iWorker, "send", Qt::QueuedConnection, Q_ARG( QByteArray, aData ), Q_ARG( QString, aContentType ) ); } else if( iMode == MODE_OBEX_SERVER ) { Q_ASSERT(0); } else { Q_ASSERT(0); } return true; } bool OBEXTransport::doReceive( const QString& aContentType ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iMode == MODE_OBEX_CLIENT ) { QMetaObject::invokeMethod( iWorker, "receive", Qt::QueuedConnection, Q_ARG( QString, aContentType ) ); } else if( iMode == MODE_OBEX_SERVER ) { if( !iWorker->isConnected() ) { QMetaObject::invokeMethod( iWorker, "waitForConnect", Qt::BlockingQueuedConnection ); } QMetaObject::invokeMethod( iWorker, "waitForPut", Qt::QueuedConnection ); } else { Q_ASSERT(0); } return true; } void OBEXTransport::incomingData( QByteArray aData, QString aContentType ) { receive( aData, aContentType ); } void OBEXTransport::connectionFailed() { emit sendEvent( TRANSPORT_CONNECTION_FAILED, "" ); } void OBEXTransport::connectionTimeout() { emit sendEvent( TRANSPORT_CONNECTION_TIMEOUT, "" ); } void OBEXTransport::connectionError() { emit sendEvent( TRANSPORT_CONNECTION_ABORTED, "" ); } void OBEXTransport::sessionRejected() { emit sendEvent( TRANSPORT_SESSION_REJECTED, "" ); } OBEXWorkerThread::OBEXWorkerThread( OBEXWorker* worker) : iWorker( worker ) { iWorker->moveToThread( this ); } OBEXWorkerThread::~OBEXWorkerThread() { } void OBEXWorkerThread::run() { qCDebug(lcSyncML) << "Starting OBEX thread..."; exec(); delete iWorker; iWorker = 0; qCDebug(lcSyncML) << "Stopping OBEX thread..."; } buteo-syncml-0.5.15/src/transport/OBEXTransport.h000066400000000000000000000117471433763642500217200ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OBEXTRANSPORT_H #define OBEXTRANSPORT_H #include #include "BaseTransport.h" #include "OBEXClientWorker.h" #include "OBEXServerWorker.h" namespace DataSync { class OBEXWorker; class OBEXWorkerThread; class OBEXConnection; /*! \brief Transport that implements OBEX functionality * */ class OBEXTransport : public BaseTransport, public OBEXServerDataSource { Q_OBJECT; public: /*! \brief Operation mode for transport * */ enum Mode { MODE_OBEX_CLIENT, //!< Act as OBEX Client MODE_OBEX_SERVER //!< Act as OBEX Server }; /*! \brief Connection type hint for transport * * Transport can use this information about the type of connection * to optimize for example used Maximum Transfer Unit (MTU). * */ enum ConnectionTypeHint { TYPEHINT_USB, //!< Operating over USB transport TYPEHINT_BT, //!< Operating over BT transport TYPEHINT_OTHER //!< Operating over other transport }; /*! \brief Constructor * * @param aConnection OBEX connection to use * @param aOpMode Operation mode for transport * @param aTypeHint Connection type hint * @param aContext Protocol context * @param aParent Parent of this QObject */ OBEXTransport( OBEXConnection& aConnection, Mode aOpMode, ConnectionTypeHint aTypeHint = TYPEHINT_OTHER, const ProtocolContext& aContext = CONTEXT_DS, QObject* aParent = NULL ); /*! \brief Destructor * */ virtual ~OBEXTransport(); /*! \see Transport::setProperty() * */ virtual void setProperty( const QString& aProperty, const QString& aValue ); /*! \see Transport::init() * */ virtual bool init(); /*! \see Transport::close() * */ virtual void close(); /*! \see Transport::sendSyncML() * */ virtual bool sendSyncML( SyncMLMessage* aMessage ); virtual bool getData( const QString& aContentType, QByteArray& aData ); protected: /*! \see BaseTransport::prepareSend() * */ virtual bool prepareSend(); /*! \see BaseTransport::doSend() * */ virtual bool doSend( const QByteArray& aData, const QString& aContentType ); /*! \see BaseTransport::doReceive() * */ virtual bool doReceive( const QString& aContentType ); private slots: void incomingData( QByteArray aData, QString aContentType ); void connectionFailed(); void connectionTimeout(); void connectionError(); void sessionRejected(); private: void setupClient( int aFd ); void setupServer( int aFd ); OBEXConnection& iConnection; Mode iMode; int iTimeOut; ConnectionTypeHint iTypeHint; OBEXWorkerThread* iWorkerThread; OBEXWorker* iWorker; qint32 iMTU; SyncMLMessage* iMessage; }; /*! \brief Thread for OBEX worker * */ class OBEXWorkerThread : public QThread { Q_OBJECT; public: /*! \brief Constructor * * @param aWorker Worker to use */ OBEXWorkerThread( OBEXWorker* aWorker ); /*! \brief Destructor * */ virtual ~OBEXWorkerThread(); protected: /*! \brief Thread function * */ virtual void run(); private: OBEXWorker* iWorker; }; } #endif // OBEXTRANSPORT_H buteo-syncml-0.5.15/src/transport/OBEXWorker.cpp000066400000000000000000000067041433763642500215250ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "OBEXWorker.h" #include "SyncMLLogging.h" using namespace DataSync; OBEXWorker::OBEXWorker( QObject* aParent ) : QObject( aParent ), iTransportHandle( 0 ), iConnected( false ), iLinkError( false ) { } OBEXWorker::~OBEXWorker() { } bool OBEXWorker::setupOpenOBEX( int aFd, qint32 aMTU, obex_event_t aEventHandler ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( !iTransportHandle ) { qCDebug(lcSyncML) << "Initializing OpenOBEX..."; obex_t* handle = OBEX_Init( OBEX_TRANS_FD, aEventHandler, 0); if( handle ) { qCDebug(lcSyncML) << "Using MTU: " << aMTU; OBEX_SetTransportMTU( handle, aMTU, aMTU ); if( FdOBEX_TransportSetup(handle, aFd, aFd, aMTU ) >= 0 ) { qCDebug(lcSyncML) << "OpenOBEX initialized"; iTransportHandle = handle; return true; } else { qCDebug(lcSyncML) << "OpenOBEX transport setup failed"; return false; } } else { qCDebug(lcSyncML) << "OpenOBEX initialization failed"; return false; } } else { return true; } } void OBEXWorker::closeOpenOBEX() { FUNCTION_CALL_TRACE(lcSyncMLTrace); if( iTransportHandle ) { OBEX_TransportDisconnect( iTransportHandle ); OBEX_Cleanup( iTransportHandle ); iTransportHandle = NULL; } } obex_t* OBEXWorker::getHandle() const { return iTransportHandle; } bool OBEXWorker::isConnected() const { return iConnected; } void OBEXWorker::setConnected( bool aConnected ) { iConnected = aConnected; } bool OBEXWorker::isLinkError() const { return iLinkError; } void OBEXWorker::setLinkError( bool aLinkError ) { FUNCTION_CALL_TRACE(lcSyncMLTrace); iLinkError = aLinkError; } buteo-syncml-0.5.15/src/transport/OBEXWorker.h000066400000000000000000000061531433763642500211700ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OBEXWORKER_H #define OBEXWORKER_H #include #include namespace DataSync { /*! \brief Base class for OBEX workers * */ class OBEXWorker : public QObject { Q_OBJECT; public: /*! \brief Constructor * * @param aParent Parent of this object */ OBEXWorker( QObject* aParent = NULL); /*! \brief Destructor * */ virtual ~OBEXWorker(); public: /*! \brief Returns connection status * * @return True if connected, otherwise false */ bool isConnected() const; protected: /*! \brief Setup OpenOBEX * * @param aFd File descriptor to use * @param aMTU MTU to use * @param aEventHandler Event handler to use */ bool setupOpenOBEX( int aFd, qint32 aMTU, obex_event_t aEventHandler ); /*! \brief Close OpenOBEX * */ void closeOpenOBEX(); /*! \brief Retrieve current OBEX handle * * @return */ obex_t* getHandle() const; /*! \brief Sets connection status * * @param aConnected Connection status to set */ void setConnected( bool aConnected ); /*! \brief Returns link error status * * @return True if link error occurred, otherwise false */ bool isLinkError() const; /*! \brief Sets link error status * * @param aLinkError Link error status to set */ void setLinkError( bool aLinkError ); private: obex_t* iTransportHandle; bool iConnected; bool iLinkError; }; } #endif // OBEXWORKER_H buteo-syncml-0.5.15/src/transport/QtEncoder.cpp000066400000000000000000000065551433763642500214660ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "QtEncoder.h" #include #include "SyncMLMessage.h" #include "SyncMLLogging.h" using namespace DataSync; QtEncoder::QtEncoder() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } QtEncoder::~QtEncoder() { FUNCTION_CALL_TRACE(lcSyncMLTrace); } bool QtEncoder::encodeToXML( const SyncMLCmdObject& aRootObject, QByteArray& aXMLDocument, bool aPrettyPrint ) const { FUNCTION_CALL_TRACE(lcSyncMLTrace); QXmlStreamWriter writer( &aXMLDocument ); writer.setAutoFormatting( aPrettyPrint ); writer.writeStartDocument(); generateElement(aRootObject, writer ); writer.writeEndDocument(); return true; } void QtEncoder::generateElement( const SyncMLCmdObject& aObject, QXmlStreamWriter& aWriter ) const { const QList& children = aObject.getChildren(); if( aObject.getValue().isEmpty() && children.isEmpty() ) { aWriter.writeEmptyElement( aObject.getName() ); } else { aWriter.writeStartElement( aObject.getName() ); const QMap& attributes = aObject.getAttributes(); QXmlStreamAttributes attr; QMapIterator i( attributes ); while( i.hasNext() ) { i.next(); attr.append( i.key(), i.value() ); } aWriter.writeAttributes( attr ); if( aObject.getCDATA() ) { aWriter.writeCDATA( aObject.getValue() ); } else { aWriter.writeCharacters( aObject.getValue() ); } for( int i = 0; i < children.count(); ++i ) { generateElement( *children[i], aWriter ); } aWriter.writeEndElement(); } } buteo-syncml-0.5.15/src/transport/QtEncoder.h000066400000000000000000000050321433763642500211200ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef QTENCODER_H #define QTENCODER_H #include class QXmlStreamWriter; namespace DataSync { class SyncMLMessage; class SyncMLCmdObject; /*! \brief XML encoder that uses Qt * */ class QtEncoder { public: /*! \brief Constructor * */ QtEncoder(); /*! \brief Destructor * */ ~QtEncoder(); /*! \brief Encode a SyncML message to XML document * * @param aRootObject Root object of the document * @param aXMLDocument Output XML document * @param aPrettyPrint If true prefer human-readable output, otherwise prefer compact size * @return True on success, otherwise false */ bool encodeToXML( const SyncMLCmdObject& aRootObject, QByteArray& aXMLDocument, bool aPrettyPrint ) const; protected: private: void generateElement( const SyncMLCmdObject& aObject, QXmlStreamWriter& aWriter ) const; }; } #endif // QTENCODER_H buteo-syncml-0.5.15/src/transport/Transport.h000066400000000000000000000152011433763642500212270ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef TRANSPORT_H #define TRANSPORT_H #include #include class QIODevice; namespace DataSync { class SyncMLMessage; /*! \brief Transport layer events that are emitted by transports to * SyncML stack */ enum TransportStatusEvent { TRANSPORT_CONNECTION_FAILED, TRANSPORT_CONNECTION_OPENED, TRANSPORT_CONNECTION_TIMEOUT, TRANSPORT_CONNECTION_ABORTED, TRANSPORT_CONNECTION_CLOSED, TRANSPORT_CONNECTION_AUTHENTICATION_NEEDED, TRANSPORT_DATA_SENT, TRANSPORT_DATA_INVALID_CONTENT_TYPE, TRANSPORT_DATA_INVALID_CONTENT, TRANSPORT_SESSION_REJECTED }; } Q_DECLARE_METATYPE( DataSync::TransportStatusEvent ); namespace DataSync { /*! \brief Transport interface that is exposed to SyncML stack * */ class Transport: public QObject { Q_OBJECT public: /*! \brief Constructor * * @param aParent Parent of this QObject */ Transport( QObject* aParent ) : QObject( aParent ) { qRegisterMetaType("DataSync::TransportStatusEvent"); } /*! \brief Destructor * */ virtual ~Transport() { }; /*! \brief Sets the URI to use in next send operation * * @param aURI New URI to remote side */ virtual void setRemoteLocURI( const QString& aURI ) = 0; /*! \brief Returns true if this transport employes wbXML, and it should be taken * into account when the stack is estimating the size of the message to send. * @return True if transport employs wbXML, otherwise false */ virtual bool usesWbXML() = 0; /*! \brief Send SyncML message using transport * * When data is sent, sendEvent() signal with TRANSPORT_DATA_SENT is emitted. * In case of errors or timeouts, sendEvent() signal is emitted with error code. * * @param aMessage Message to send. Ownership is transferred * @return True if sending of data was started, false otherwise */ virtual bool sendSyncML( SyncMLMessage* aMessage ) = 0; /*! \brief Send SAN message using transport * * When data is sent, sendEvent() signal with TRANSPORT_DATA_SENT is emitted. * In case of errors or timeouts, sendEvent() signal is emitted with error code. * * @param aMessage Message to send. * @return True if sending of data was started, false otherwise */ virtual bool sendSAN( const QByteArray& aMessage ) = 0; /*! \brief Receive XML data using transport * * When data is available, readData() signal is emitted. In case of errors or * timeouts, sendEvent() signal is emitted * * @return True if listening for incoming data was started, false otherwise */ virtual bool receive() = 0; /*! \brief Sets a transport property * * This function is called by SyncAgent to enable properties set with * SyncAgentConfig::setTransportProperty(). Users generally should not * call this function directly. * * @param aProperty Property to set * @param aValue Value to set */ virtual void setProperty( const QString& aProperty, const QString& aValue ) = 0; /*! \brief Initiates the transport * * This function is called by SyncAgent when it is sure that transport * layer is required to proceed with the synchronization. Users generally * should not call this function directly. This function should take care * of any operations needed to be performed before data can be sent or * received, such as establishing a link layer connection and/or session. * * @return True if initiation was successful, otherwise false */ virtual bool init() = 0; /*! \brief Closes the transport * * This function is called by SyncAgent when it is sure that transport layer * is no longer required to proceed with the synchronization. Users generally * should not call this function directly. This function should take care of * any operations needed to close link layer connection and/or session. */ virtual void close() = 0; signals: /*! \brief Signal that is emitted when transport level event occurs * * @param aEvent Event that has occurred * @param aDescription Description of the event that has occurred * */ void sendEvent( DataSync::TransportStatusEvent aEvent, const QString& aDescription ); /*! \brief Signal that is emitted when new XML data is available * * @param aDevice QIODevice that can be used to read data * @param aIsNewPacket bool To indicate if this is a newly received packet * or a purged one. */ void readXMLData( QIODevice* aDevice, bool aIsNewPacket ); /*! \brief Signal that is emitted when new SAN data is available * * @param aDevice QIODevice that can be used to read data */ void readSANData( QIODevice* aDevice ); private slots: /*! \brief Remove any illegal XML characters from the previous message * * Removes illegal XML characters (NULLs and control characters) */ virtual void purgeAndResendBuffer() = 0; }; } #endif buteo-syncml-0.5.15/src/transport/transport.pro000066400000000000000000000007201433763642500216400ustar00rootroot00000000000000SOURCES += BaseTransport.cpp \ HTTPTransport.cpp \ OBEXDataHandler.cpp \ LibWbXML2Encoder.cpp \ QtEncoder.cpp \ OBEXTransport.cpp \ OBEXWorker.cpp \ OBEXClientWorker.cpp \ OBEXServerWorker.cpp \ HEADERS += Transport.h \ BaseTransport.h \ HTTPTransport.h \ OBEXConnection.h \ OBEXDataHandler.h \ LibWbXML2Encoder.h \ QtEncoder.h \ OBEXTransport.h \ OBEXWorker.h \ OBEXClientWorker.h \ OBEXServerWorker.h buteo-syncml-0.5.15/tests_meego/000077500000000000000000000000001433763642500165565ustar00rootroot00000000000000buteo-syncml-0.5.15/tests_meego/AlertPackageTest.cpp000066400000000000000000000102361433763642500224470ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "AlertPackageTest.h" #include "AlertPackage.h" #include "SyncMLMessage.h" #include "Mock.h" #include "QtEncoder.h" using namespace DataSync; void AlertPackageTest::testConstruction() { QString data = QString::number( TWO_WAY_SYNC ); QString source( "src" ); QString target( "dst" ); QString type( "type" ); // One test block for each constructor type. { AlertPackage pkg(data.toInt()); CommandParams result_params = pkg.iParams; QVERIFY( result_params.commandType == CommandParams::COMMAND_ALERT ); QCOMPARE(result_params.data, data); } { AlertPackage pkg(data.toInt(), source, target); CommandParams result_params = pkg.iParams; QVERIFY( result_params.commandType == CommandParams::COMMAND_ALERT ); QCOMPARE(result_params.data, data); QCOMPARE(result_params.items.count(), 1 ); QCOMPARE(result_params.items.first().source, source); QCOMPARE(result_params.items.first().target, target); } { AlertPackage pkg( data.toInt(), source, target, "", "" ); CommandParams result_params = pkg.iParams; QVERIFY( result_params.commandType == CommandParams::COMMAND_ALERT ); QCOMPARE(result_params.data, data); QCOMPARE(result_params.items.count(), 1 ); QCOMPARE(result_params.items.first().source, source); QCOMPARE(result_params.items.first().target, target); QVERIFY(result_params.items.first().meta.anchor.last == "0"); } { AlertPackage pkg( source, type, data.toInt() ); CommandParams result_params = pkg.iParams; QVERIFY( result_params.commandType == CommandParams::COMMAND_ALERT ); QCOMPARE(result_params.data, data); QCOMPARE(result_params.items.count(), 1 ); QCOMPARE(result_params.items.first().source, source); QCOMPARE(result_params.items.first().meta.type, type); } } void AlertPackageTest::testWrite() { AlertPackage pkg(SLOW_SYNC, "foo", "bar"); SyncMLMessage msg(HeaderParams(), SYNCML_1_2); QtEncoder encoder; QByteArray initial_xml; QVERIFY( encoder.encodeToXML( msg, initial_xml, true ) ); const int SIZE_TRESHOLD = 10000; int remaining = SIZE_TRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); QVERIFY(remaining < SIZE_TRESHOLD); QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QVERIFY(result_xml.size() > initial_xml.size()); QVERIFY(result_xml.indexOf(SYNCML_ELEMENT_ALERT) != -1); } QTEST_MAIN(AlertPackageTest) buteo-syncml-0.5.15/tests_meego/AlertPackageTest.h000066400000000000000000000035241433763642500221160ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef ALERTPACKAGETEST_H #define ALERTPACKAGETEST_H #include class AlertPackageTest : public QObject { Q_OBJECT private slots: void testConstruction(); void testWrite(); }; #endif // ALERTPACKAGETEST_H buteo-syncml-0.5.15/tests_meego/AlertPackageTest.pro000066400000000000000000000000351433763642500224610ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/AuthHelperTest.cpp000066400000000000000000000043671433763642500221750ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "AuthHelperTest.h" #include "AuthHelper.h" using namespace DataSync; void AuthHelperTest::testAuthEncodeBasic() { AuthHelper authHelper; QString username = "foo"; QString password = "bar"; // @todo: check results? QByteArray encodedData = authHelper.encodeBasicB64Auth(username, password); } void AuthHelperTest::testAuthEncodeMD5() { AuthHelper authHelper; QString username = "foo"; QString password = "bar"; QByteArray nonce; // @todo: check results? QByteArray encodedData = authHelper.encodeMD5Auth(username, password, nonce); } QTEST_MAIN(DataSync::AuthHelperTest) buteo-syncml-0.5.15/tests_meego/AuthHelperTest.h000066400000000000000000000035351433763642500216360ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef AUTHHELPERTEST_H #define AUTHHELPERTEST_H #include namespace DataSync { class AuthHelperTest : public QObject { Q_OBJECT; private slots: void testAuthEncodeBasic(); void testAuthEncodeMD5(); }; } #endif buteo-syncml-0.5.15/tests_meego/AuthHelperTest.pro000066400000000000000000000000351433763642500221770ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/AuthenticationPackageTest.cpp000066400000000000000000000070121433763642500243550ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "AuthenticationPackageTest.h" #include "AuthenticationPackage.h" #include "SyncMLMessage.h" #include "QtEncoder.h" #include "Fragments.h" #include "datatypes.h" // @todo: need better tests here using namespace DataSync; void AuthenticationPackageTest::testWrite() { QString user_name("user"); QString password("pw"); AuthenticationPackage pkg(AUTH_BASIC, user_name, password); QCOMPARE(pkg.iUsername, user_name); QCOMPARE(pkg.iPassword, password); SyncMLMessage msg(HeaderParams(), SYNCML_1_2); QtEncoder encoder; QByteArray initial_xml; QVERIFY( encoder.encodeToXML( msg, initial_xml, true ) ); const int SIZE_TRESHOLD = 10000; int remaining = SIZE_TRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); QVERIFY(remaining < SIZE_TRESHOLD); QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QVERIFY(result_xml.size() > initial_xml.size()); QVERIFY(result_xml.indexOf(SYNCML_ELEMENT_CRED) != -1); } void AuthenticationPackageTest::testWrite2() { QString user_name("user"); QString password("pw"); QtEncoder encoder; AuthenticationPackage pkg(AUTH_BASIC, user_name, password); QCOMPARE(pkg.iUsername, user_name); QCOMPARE(pkg.iPassword, password); pkg.iNonce = QString::number( QDateTime::currentDateTime().toTime_t() ).toLatin1(); SyncMLMessage msg(HeaderParams(), SYNCML_1_2); QByteArray initial_xml; QVERIFY( encoder.encodeToXML( msg, initial_xml, true ) ); const int SIZE_TRESHOLD = 10000; int remaining = SIZE_TRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); QVERIFY(remaining < SIZE_TRESHOLD); QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QVERIFY(result_xml.size() > initial_xml.size()); QVERIFY(result_xml.indexOf(SYNCML_ELEMENT_CRED) != -1); } QTEST_MAIN(AuthenticationPackageTest) buteo-syncml-0.5.15/tests_meego/AuthenticationPackageTest.h000066400000000000000000000035601433763642500240260ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef AUTHENTICATIONPACKAGETEST_H #define AUTHENTICATIONPACKAGETEST_H #include class AuthenticationPackageTest : public QObject { Q_OBJECT private slots: void testWrite(); void testWrite2(); }; #endif // AUTHENTICATIONPACKAGETEST_H buteo-syncml-0.5.15/tests_meego/AuthenticationPackageTest.pro000066400000000000000000000000351433763642500243710ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/ChangeLogHandlerTest.cpp000066400000000000000000000056661433763642500232640ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ChangeLogHandlerTest.h" #include "ChangeLog.h" #include "ChangeLogHandler.h" #include "DatabaseHandler.h" #include "datatypes.h" using namespace DataSync; #include #include void ChangeLogHandlerTest::initTestCase() { iDbHandler = new DatabaseHandler( "/tmp/changeloghandlertest.db" ); } void ChangeLogHandlerTest::cleanupTestCase() { if( iDbHandler ) { delete iDbHandler; iDbHandler = NULL; } } void ChangeLogHandlerTest::testCreateChangeLogTable() { ChangeLogHandler handler( iDbHandler->getDbHandle() ); QVERIFY(handler.createChangeLogTable()); ChangeLogInfo info("device1", "targetdb", "sourcedb", TWO_WAY_SYNC ); ChangeLog* log = handler.create(info); uint id = log->getChangeLogId(); //qDebug() << "log Number of Items " << log->getNrOfItems(); // Try to get it again, same changelog should be returned. ChangeLog* log2 = handler.create(info); //qDebug() << id << " and " << log2->getChangeLogId(); QVERIFY ( id == log2->getChangeLogId()); handler.remove(info); // New remote device, the changelog should be different info.iRemoteDevice = "device2"; ChangeLog* log3 = handler.create(info); QVERIFY( id != log3->getChangeLogId()); delete log; delete log2; delete log3; } QTEST_MAIN(ChangeLogHandlerTest) buteo-syncml-0.5.15/tests_meego/ChangeLogHandlerTest.h000066400000000000000000000037741433763642500227270ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CHANGELOGHANDLERTESTTEST_H #define CHANGELOGHANDLERTESTTEST_H #include #include "datatypes.h" namespace DataSync { class DatabaseHandler; } class ChangeLogHandlerTest: public QObject { Q_OBJECT private slots: void testCreateChangeLogTable(); void initTestCase(); void cleanupTestCase(); private: DataSync::DatabaseHandler* iDbHandler; }; #endif buteo-syncml-0.5.15/tests_meego/ChangeLogHandlerTest.pro000066400000000000000000000000351433763642500232630ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/ChangeLogTest.cpp000066400000000000000000000203211433763642500217470ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ChangeLogTest.h" #include "DatabaseHandler.h" #include "SyncMode.h" #include "SyncMLLogging.h" using namespace DataSync; const QString DB1( "/tmp/changelogtest1.db" ); const QString DB2( "/tmp/changelogtest2.db" ); void ChangeLogTest::initTestCase() { iDbHandler = new DatabaseHandler( DB1 ); } void ChangeLogTest::cleanupTestCase() { delete iDbHandler; iDbHandler = 0; } void ChangeLogTest::testBorrowedGetSetLastSyncTime() { ChangeLog changeLog( "testdevice1", "sourcedb1", DIRECTION_TWO_WAY ); // Test in-memory modifications QDateTime syncTime = QDateTime::currentDateTime(); changeLog.setLastSyncTime(syncTime); QCOMPARE(changeLog.getLastSyncTime(), syncTime ); // Test database commit & load QVERIFY( changeLog.save( iDbHandler->getDbHandle() ) ); QVERIFY( changeLog.load( iDbHandler->getDbHandle() ) ); // Compare only in accuracy of 1 second as sql database stores times // with the accuracy of 1 second only QCOMPARE( changeLog.getLastSyncTime().toTime_t(), syncTime.toTime_t() ); // Test database remove changeLog.remove( iDbHandler->getDbHandle() ); QVERIFY( !changeLog.load( iDbHandler->getDbHandle() ) ); } void ChangeLogTest::testBorrowedGetSetAnchor() { ChangeLog changeLog( "testdevice2", "sourcedb2", DIRECTION_TWO_WAY ); // Test in-memory modifications QString local("localanchor"); QString remote("remoteanchor"); changeLog.setLastLocalAnchor( local ); changeLog.setLastRemoteAnchor( remote ); QCOMPARE( changeLog.getLastLocalAnchor(), local ); QCOMPARE( changeLog.getLastRemoteAnchor(), remote ); // Test database commit & load QVERIFY( changeLog.save( iDbHandler->getDbHandle() ) ); QVERIFY( changeLog.load( iDbHandler->getDbHandle() ) ); QCOMPARE( changeLog.getLastLocalAnchor(), local ); QCOMPARE( changeLog.getLastRemoteAnchor(), remote ); // Test database remove changeLog.remove( iDbHandler->getDbHandle() ); QVERIFY( !changeLog.load( iDbHandler->getDbHandle() ) ); } void ChangeLogTest::testBorrowedGetSetMaps() { ChangeLog changeLog( "testdevice3", "sourcedb3", DIRECTION_TWO_WAY ); // Test in-memory modifications const QString localId1( "local1" ); const QString remoteId1( "remote1" ); const QString localId2( "local2"); const QString remoteId2( "remote2" ); UIDMapping map1; map1.iLocalUID = localId1; map1.iRemoteUID = remoteId1; UIDMapping map2; map2.iLocalUID = localId2; map2.iRemoteUID = remoteId2; QList maps; maps.append(map1); maps.append(map2); changeLog.setMaps( maps ); QCOMPARE( maps.count(), 2 ); QCOMPARE( changeLog.getMaps().count(), 2 ); QCOMPARE( changeLog.getMaps().at(0).iLocalUID, maps.at(0).iLocalUID ); QCOMPARE( changeLog.getMaps().at(0).iRemoteUID, maps.at(0).iRemoteUID ); QCOMPARE( changeLog.getMaps().at(1).iLocalUID, maps.at(1).iLocalUID ); QCOMPARE( changeLog.getMaps().at(1).iRemoteUID, maps.at(1).iRemoteUID ); // Test database commit & load QVERIFY( changeLog.save( iDbHandler->getDbHandle() ) ); QVERIFY( changeLog.load( iDbHandler->getDbHandle() ) ); QCOMPARE( changeLog.getMaps().count(), 2 ); QCOMPARE( changeLog.getMaps().at(0).iLocalUID, maps.at(0).iLocalUID ); QCOMPARE( changeLog.getMaps().at(0).iRemoteUID, maps.at(0).iRemoteUID ); QCOMPARE( changeLog.getMaps().at(1).iLocalUID, maps.at(1).iLocalUID ); QCOMPARE( changeLog.getMaps().at(1).iRemoteUID, maps.at(1).iRemoteUID ); // Test database remove changeLog.remove( iDbHandler->getDbHandle() ); QVERIFY( !changeLog.load( iDbHandler->getDbHandle() ) ); } void ChangeLogTest::testOwnedGetSetLastSyncTime() { ChangeLog changeLog( "testdevice4", "sourcedb4", DIRECTION_TWO_WAY ); // Test in-memory modifications QDateTime syncTime = QDateTime::currentDateTime(); changeLog.setLastSyncTime(syncTime); QCOMPARE(changeLog.getLastSyncTime(), syncTime ); // Test database commit & load QVERIFY( changeLog.save( DB2 ) ); QVERIFY( changeLog.load( DB2 ) ); // Compare only in accuracy of 1 second as sql database stores times // with the accuracy of 1 second only QCOMPARE( changeLog.getLastSyncTime().toTime_t(), syncTime.toTime_t() ); // Test database remove changeLog.remove( DB2 ); QVERIFY( !changeLog.load( DB2 ) ); } void ChangeLogTest::testOwnedGetSetLastAnchor() { ChangeLog changeLog( "testdevice5", "sourcedb5", DIRECTION_TWO_WAY ); // Test in-memory modifications QString local("localanchor"); QString remote("remoteanchor"); changeLog.setLastLocalAnchor( local ); changeLog.setLastRemoteAnchor( remote ); QCOMPARE( changeLog.getLastLocalAnchor(), local ); QCOMPARE( changeLog.getLastRemoteAnchor(), remote ); // Test database commit & load QVERIFY( changeLog.save( DB2 ) ); QVERIFY( changeLog.load( DB2 ) ); QCOMPARE( changeLog.getLastLocalAnchor(), local ); QCOMPARE( changeLog.getLastRemoteAnchor(), remote ); // Test database remove changeLog.remove( DB2 ); QVERIFY( !changeLog.load( DB2 ) ); } void ChangeLogTest::testOwnedGetSetMaps() { ChangeLog changeLog( "testdevice6", "sourcedb6", DIRECTION_TWO_WAY ); // Test in-memory modifications const QString localId1( "local1" ); const QString remoteId1( "remote1" ); const QString localId2( "local2"); const QString remoteId2( "remote2" ); UIDMapping map1; map1.iLocalUID = localId1; map1.iRemoteUID = remoteId1; UIDMapping map2; map2.iLocalUID = localId2; map2.iRemoteUID = remoteId2; QList maps; maps.append(map1); maps.append(map2); changeLog.setMaps( maps ); QCOMPARE( maps.count(), 2 ); QCOMPARE( changeLog.getMaps().count(), 2 ); QCOMPARE( changeLog.getMaps().at(0).iLocalUID, maps.at(0).iLocalUID ); QCOMPARE( changeLog.getMaps().at(0).iRemoteUID, maps.at(0).iRemoteUID ); QCOMPARE( changeLog.getMaps().at(1).iLocalUID, maps.at(1).iLocalUID ); QCOMPARE( changeLog.getMaps().at(1).iRemoteUID, maps.at(1).iRemoteUID ); // Test database commit & load QVERIFY( changeLog.save( DB2 ) ); QVERIFY( changeLog.load( DB2 ) ); QCOMPARE( changeLog.getMaps().count(), 2 ); QCOMPARE( changeLog.getMaps().at(0).iLocalUID, maps.at(0).iLocalUID ); QCOMPARE( changeLog.getMaps().at(0).iRemoteUID, maps.at(0).iRemoteUID ); QCOMPARE( changeLog.getMaps().at(1).iLocalUID, maps.at(1).iLocalUID ); QCOMPARE( changeLog.getMaps().at(1).iRemoteUID, maps.at(1).iRemoteUID ); // Test database remove changeLog.remove( DB2 ); QVERIFY( !changeLog.load( DB2 ) ); } QTEST_MAIN(ChangeLogTest) buteo-syncml-0.5.15/tests_meego/ChangeLogTest.h000066400000000000000000000042621433763642500214220ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CHANGELOGTEST_H #define CHANGELOGTEST_H #include #include "ChangeLog.h" namespace DataSync { class DatabaseHandler; } class ChangeLogTest: public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testBorrowedGetSetLastSyncTime(); void testBorrowedGetSetAnchor(); void testBorrowedGetSetMaps(); void testOwnedGetSetLastSyncTime(); void testOwnedGetSetLastAnchor(); void testOwnedGetSetMaps(); private: DataSync::DatabaseHandler* iDbHandler; }; #endif /* CHANGELOGTEST_H_ */ buteo-syncml-0.5.15/tests_meego/ChangeLogTest.pro000066400000000000000000000000351433763642500217650ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/CommandHandlerTest.cpp000066400000000000000000000552551433763642500230120ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "CommandHandlerTest.h" #include #include "CommandHandler.h" #include "ResponseGenerator.h" #include "ChangeLog.h" #include "ConflictResolver.h" #include "QtEncoder.h" #include "SyncMLMessage.h" #include "DeviceInfo.h" #include "Mock.h" #include "TestUtils.h" #include "SyncMLLogging.h" using namespace DataSync; CommandHandlerTest::CommandHandlerTest() { } CommandHandlerTest::~CommandHandlerTest() { } void CommandHandlerTest::testAdd_Client01() { // Test adding a new item from server without parent QString localDb( "localdb" ); QString remoteDb( "remotedb" ); QString mime( "mime/foo1" ); QString itemId( "id0" ); int cmdId = 1; // Setup sync target CommitTestStorage storage( localDb ); SyncMode mode; QString anchor; SyncTarget target( NULL, &storage, mode, anchor ); // Setup conflict resolver LocalChanges changes; ConflictResolver conflictResolver( changes, PREFER_LOCAL_CHANGES ); StorageHandler storageHandler; CommandHandler commandHandler( ROLE_CLIENT ); ResponseGenerator generator; generator.setRemoteMsgId( 1 ); // Create sync element SyncParams syncParams; syncParams.cmdId = cmdId++; syncParams.source = remoteDb; syncParams.target = localDb; CommandParams add( CommandParams::COMMAND_ADD ); add.cmdId = cmdId++; ItemParams addItem; addItem.source = itemId; addItem.data = "foodata"; addItem.meta.type = mime; add.items.append( addItem ); syncParams.commands.append( add ); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); QSignalSpy processed_spy( &storageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); commandHandler.handleSync( syncParams, target, storageHandler, generator, conflictResolver, false ); // Check that item was added to storage QCOMPARE( storage.iAddedItems.count(), 1 ); QCOMPARE( storage.iReplacedItems.count(), 0 ); QCOMPARE( storage.iDeletedItems.count(), 0 ); QCOMPARE( storage.iIdCounter, 1 ); // Check that item was added to mappings QCOMPARE( target.getUIDMappings().count(), 1 ); QCOMPARE( target.mapToLocalUID( itemId ), QString( "1" ) ); // Check that proper signals were emitted QCOMPARE( processed_spy.count(), 1 ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(0)), MOD_ITEM_ADDED ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(0).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(0).at(3).toString(), mime ); } void CommandHandlerTest::testAdd_Server01() { // Test adding a new item from client without parent QString localDb( "localdb" ); QString remoteDb( "remotedb" ); QString mime( "mime/foo1" ); QString itemId( "id0" ); int cmdId = 1; // Setup sync target CommitTestStorage storage( localDb ); SyncMode mode; QString anchor; SyncTarget target( NULL, &storage, mode, anchor ); // Setup conflict resolver LocalChanges changes; ConflictResolver conflictResolver( changes, PREFER_REMOTE_CHANGES ); StorageHandler storageHandler; CommandHandler commandHandler( ROLE_SERVER ); ResponseGenerator generator; generator.setRemoteMsgId( 1 ); // Create sync element SyncParams syncParams; syncParams.cmdId = cmdId++; syncParams.source = remoteDb; syncParams.target = localDb; CommandParams add( CommandParams::COMMAND_ADD ); add.cmdId = cmdId++; ItemParams addItem; addItem.source = itemId; addItem.data = "foodata"; addItem.meta.type = mime; add.items.append( addItem ); syncParams.commands.append( add ); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); QSignalSpy processed_spy( &storageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); commandHandler.handleSync( syncParams, target, storageHandler, generator, conflictResolver, false ); // Check that item was added to storage QCOMPARE( storage.iAddedItems.count(), 1 ); QCOMPARE( storage.iReplacedItems.count(), 0 ); QCOMPARE( storage.iDeletedItems.count(), 0 ); QCOMPARE( storage.iIdCounter, 1 ); // Check that item was added to mappings QCOMPARE( target.getUIDMappings().count(), 1 ); QCOMPARE( target.mapToLocalUID( itemId ), QString( "1" ) ); // Check that proper signals were emitted QCOMPARE( processed_spy.count(), 1 ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(0)), MOD_ITEM_ADDED ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(0).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(0).at(3).toString(), mime ); } void CommandHandlerTest::testSyncAdd() { QString localDb( "localdb" ); QString remoteDb( "remotedb" ); StorageHandler storageHandler; MockStorage storage( localDb ); SyncMode mode; QString anchor; SyncTarget target( NULL, &storage, mode, anchor ); LocalChanges changes; ConflictResolver conflictResolver( changes, PREFER_REMOTE_CHANGES ); CommandHandler handler( ROLE_SERVER ); ResponseGenerator generator; generator.setRemoteMsgId( 1 ); SyncParams syncParams; int cmdId = 1; syncParams.cmdId = cmdId++; syncParams.source = localDb; syncParams.target = remoteDb; CommandParams add( CommandParams::COMMAND_ADD ); add.cmdId = cmdId++; ItemParams addItem; addItem.source = "fooid"; addItem.data = "foodata"; addItem.meta.type = "mime/foo1"; add.items.append( addItem ); syncParams.commands.append( add ); CommandParams replace( CommandParams::COMMAND_REPLACE ); replace.cmdId = cmdId++; ItemParams replaceItem1; replaceItem1.source = "key1"; replaceItem1.data = "foodata"; replaceItem1.meta.type = "mime/foo2"; replace.items.append( replaceItem1 ); ItemParams replaceItem2; replaceItem2.source = "key2"; replaceItem2.data = "foodata"; replaceItem2.meta.type = "mime/foo3"; replace.items.append( replaceItem2 ); syncParams.commands.append( replace ); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); QSignalSpy processed_spy( &storageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); handler.handleSync( syncParams, target, storageHandler, generator, conflictResolver, false ); QCOMPARE( processed_spy.count(), 3 ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(0)), MOD_ITEM_ADDED ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(0).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(0).at(3).toString(), QString( "mime/foo1" ) ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(0)), MOD_ITEM_ADDED ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(1).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(1).at(3).toString(), QString( "mime/foo2" ) ); QCOMPARE( qvariant_cast(processed_spy.at(2).at(0)), MOD_ITEM_ADDED ); QCOMPARE( qvariant_cast(processed_spy.at(2).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(2).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(2).at(3).toString(), QString( "mime/foo3" ) ); QVERIFY( !target.mapToLocalUID( "fooid" ).isEmpty() ); QVERIFY( !target.mapToLocalUID( "key1" ).isEmpty() ); QVERIFY( !target.mapToLocalUID( "key2" ).isEmpty() ); } void CommandHandlerTest::testSyncReplace() { QString localDb( "localdb" ); QString remoteDb( "remotedb" ); StorageHandler storageHandler; MockStorage storage( localDb ); SyncMode mode; QString anchor; SyncTarget target( NULL, &storage, mode, anchor ); LocalChanges changes; ConflictResolver conflictResolver( changes, PREFER_REMOTE_CHANGES ); CommandHandler handler( ROLE_SERVER ); ResponseGenerator generator; generator.setRemoteMsgId( 1 ); SyncParams syncParams; int cmdId = 1; syncParams.cmdId = cmdId++; syncParams.source = localDb; syncParams.target = remoteDb; CommandParams replace( CommandParams::COMMAND_REPLACE ); replace.cmdId = cmdId++; ItemParams replaceItem1; replaceItem1.source = "key1"; replaceItem1.data = "foodata"; replaceItem1.meta.type = "mime/foo1"; replace.items.append( replaceItem1 ); ItemParams replaceItem2; replaceItem2.source = "key2"; replaceItem2.data = "foodata"; replaceItem2.meta.type = "mime/foo2"; replace.items.append( replaceItem2 ); ItemParams replaceItem3; replaceItem3.source = "secretkey"; replaceItem3.data = "foodata"; replaceItem3.meta.type = "mime/foo3"; replace.items.append( replaceItem3 ); syncParams.commands.append( replace ); UIDMapping mapping; mapping.iRemoteUID= "key1"; mapping.iLocalUID= "key1"; target.addUIDMapping( mapping ); mapping.iRemoteUID = "key2"; mapping.iLocalUID = "key2"; target.addUIDMapping( mapping ); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); QSignalSpy processed_spy( &storageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); handler.handleSync( syncParams, target, storageHandler, generator, conflictResolver, false ); QCOMPARE( processed_spy.count(), 3 ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(0)), MOD_ITEM_ADDED ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(0).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(0).at(3).toString(), QString( "mime/foo3" ) ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(0)), MOD_ITEM_MODIFIED ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(1).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(1).at(3).toString(), QString( "mime/foo1" ) ); QCOMPARE( qvariant_cast(processed_spy.at(2).at(0)), MOD_ITEM_MODIFIED ); QCOMPARE( qvariant_cast(processed_spy.at(2).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(2).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(2).at(3).toString(), QString( "mime/foo2" ) ); } void CommandHandlerTest::testSyncDelete() { QString localDb( "localdb" ); QString remoteDb( "remotedb" ); StorageHandler storageHandler; MockStorage storage( localDb ); SyncMode mode; QString anchor; SyncTarget target( NULL, &storage, mode, anchor ); LocalChanges changes; ConflictResolver conflictResolver( changes, PREFER_REMOTE_CHANGES ); CommandHandler handler( ROLE_SERVER ); ResponseGenerator generator; generator.setRemoteMsgId( 1 ); SyncParams syncParams; int cmdId = 1; syncParams.cmdId = cmdId++; syncParams.source = localDb; syncParams.target = remoteDb; CommandParams del( CommandParams::COMMAND_DELETE ); del.cmdId = cmdId++; ItemParams deleteItem1; deleteItem1.source = "key1"; del.items.append( deleteItem1 ); ItemParams deleteItem2; deleteItem2.source = "key2"; del.items.append( deleteItem2 ); syncParams.commands.append( del ); UIDMapping mapping; mapping.iRemoteUID = "key1"; mapping.iLocalUID = "key1"; target.addUIDMapping( mapping ); mapping.iRemoteUID = "key2"; mapping.iLocalUID = "key2"; target.addUIDMapping( mapping ); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); QSignalSpy processed_spy( &storageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); handler.handleSync( syncParams, target, storageHandler, generator, conflictResolver, false ); QCOMPARE( processed_spy.count(), 2 ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(0)), MOD_ITEM_DELETED ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(0).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(0).at(3).toString(), QString( "text/x-vcard" ) ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(0)), MOD_ITEM_DELETED ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(1).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(1).at(3).toString(), QString( "text/x-vcard" ) ); } void CommandHandlerTest::testSyncReplaceConflict() { QString localDb( "localdb" ); QString remoteDb( "remotedb" ); StorageHandler storageHandler; MockStorage storage( localDb ); SyncMode mode; QString anchor; SyncTarget target( NULL, &storage, mode, anchor ); LocalChanges changes; changes.modified.append(QString("key1")); changes.removed.append(QString("key2")); changes.removed.append(QString("secretkey")); ConflictResolver conflictResolver( changes, PREFER_REMOTE_CHANGES ); CommandHandler handler( ROLE_SERVER ); ResponseGenerator generator; generator.setRemoteMsgId( 1 ); SyncParams syncParams; int cmdId = 1; syncParams.cmdId = cmdId++; syncParams.source = localDb; syncParams.target = remoteDb; CommandParams replace( CommandParams::COMMAND_REPLACE ); replace.cmdId = cmdId++; ItemParams replaceItem1; replaceItem1.source = "key1"; replaceItem1.data = "foodata"; replaceItem1.meta.type = "mime/foo1"; replace.items.append( replaceItem1 ); ItemParams replaceItem2; replaceItem2.source = "key2"; replaceItem2.data = "foodata"; replaceItem2.meta.type = "mime/foo2"; replace.items.append( replaceItem2 ); ItemParams replaceItem3; replaceItem3.source = "secretkey"; replaceItem3.data = "foodata"; replaceItem3.meta.type = "mime/foo3"; replace.items.append( replaceItem3 ); syncParams.commands.append( replace ); UIDMapping mapping; mapping.iRemoteUID= "key1"; mapping.iLocalUID= "key1"; target.addUIDMapping( mapping ); mapping.iRemoteUID = "key2"; mapping.iLocalUID = "key2"; target.addUIDMapping( mapping ); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); QSignalSpy processed_spy( &storageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); handler.handleSync( syncParams, target, storageHandler, generator, conflictResolver, false ); QCOMPARE( processed_spy.count(), 3 ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(0)), MOD_ITEM_ADDED ); QCOMPARE( qvariant_cast(processed_spy.at(0).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(0).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(0).at(3).toString(), QString( "mime/foo3" ) ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(0)), MOD_ITEM_MODIFIED ); QCOMPARE( qvariant_cast(processed_spy.at(1).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(1).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(1).at(3).toString(), QString( "mime/foo1" ) ); QCOMPARE( qvariant_cast(processed_spy.at(2).at(0)), MOD_ITEM_MODIFIED ); QCOMPARE( qvariant_cast(processed_spy.at(2).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE( processed_spy.at(2).at(2).toString(), localDb ); QCOMPARE( processed_spy.at(2).at(3).toString(), QString( "mime/foo2" ) ); } void CommandHandlerTest::testSyncReplaceConflict_01() { QString localDb( "localdb" ); QString remoteDb( "remotedb" ); StorageHandler storageHandler; MockStorage storage( localDb ); SyncMode mode; QString anchor; SyncTarget target( NULL, &storage, mode, anchor ); LocalChanges changes; changes.modified.append(QString("key1")); changes.removed.append(QString("key2")); ConflictResolver conflictResolver( changes, PREFER_LOCAL_CHANGES ); CommandHandler handler( ROLE_SERVER ); ResponseGenerator generator; generator.setRemoteMsgId( 1 ); SyncParams syncParams; int cmdId = 1; syncParams.cmdId = cmdId++; syncParams.source = localDb; syncParams.target = remoteDb; CommandParams replace( CommandParams::COMMAND_REPLACE ); replace.cmdId = cmdId++; ItemParams replaceItem1; replaceItem1.source = "key1"; replaceItem1.data = "foodata"; replaceItem1.meta.type = "mime/foo1"; replace.items.append( replaceItem1 ); ItemParams replaceItem2; replaceItem2.source = "key2"; replaceItem2.data = "foodata"; replaceItem2.meta.type = "mime/foo2"; replace.items.append( replaceItem2 ); syncParams.commands.append( replace ); UIDMapping mapping; mapping.iRemoteUID= "key1"; mapping.iLocalUID= "key1"; target.addUIDMapping( mapping ); mapping.iRemoteUID = "key2"; mapping.iLocalUID = "key2"; target.addUIDMapping( mapping ); qRegisterMetaType("DataSync::ModificationType"); qRegisterMetaType("DataSync::ModifiedDatabase"); QSignalSpy processed_spy( &storageHandler, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); handler.handleSync( syncParams, target, storageHandler, generator, conflictResolver, false ); QCOMPARE( processed_spy.count(), 0 ); } void CommandHandlerTest::testGetStatusType() { CommandHandler handler(ROLE_SERVER); QCOMPARE(handler.getStatusType(static_cast(-50)), UNKNOWN); QCOMPARE(handler.getStatusType(static_cast(0)), UNKNOWN); QCOMPARE(handler.getStatusType(static_cast(50)), UNKNOWN); QCOMPARE(handler.getStatusType(IN_PROGRESS), INFORMATIONAL); QCOMPARE(handler.getStatusType(static_cast(199)), UNKNOWN); QCOMPARE(handler.getStatusType(SUCCESS), SUCCESSFUL); QCOMPARE(handler.getStatusType(ATOMIC_ROLLBACK_OK), SUCCESSFUL); QCOMPARE(handler.getStatusType(static_cast(299)), UNKNOWN); QCOMPARE(handler.getStatusType(MULTIPLE_CHOICES), REDIRECTION); QCOMPARE(handler.getStatusType(USE_PROXY), REDIRECTION); QCOMPARE(handler.getStatusType(static_cast(399)), UNKNOWN); QCOMPARE(handler.getStatusType(BAD_REQUEST), ORIGINATOR_EXCEPTION); QCOMPARE(handler.getStatusType(MOVE_FAILED), ORIGINATOR_EXCEPTION); QCOMPARE(handler.getStatusType(static_cast(499)), UNKNOWN); QCOMPARE(handler.getStatusType(COMMAND_FAILED), RECIPIENT_EXCEPTION); QCOMPARE(handler.getStatusType(ATOMIC_RESPONSE_TOO_LARGE), RECIPIENT_EXCEPTION); QCOMPARE(handler.getStatusType(static_cast(599)), UNKNOWN); QCOMPARE(handler.getStatusType(static_cast(1000)), UNKNOWN); } void CommandHandlerTest::testNotImplemented() { CommandHandler handler(ROLE_SERVER); QCOMPARE(handler.handleRedirection(MULTIPLE_CHOICES), NOT_IMPLEMENTED); } void CommandHandlerTest::testHandleMap() { CommandHandler handler(ROLE_SERVER); const QString src1("fooSource1"); const QString src2("fooSource2"); const QString trg1("barTarget1"); const QString trg2("barTarget2"); SyncTarget target(new ChangeLog("sourceDevice", "targetDevice", DIRECTION_TWO_WAY), new MockStorage("storage"), SyncMode(), QString()); MapParams map; MapItemParams param; param.source = src1; param.target = trg1; map.mapItems.append(param); param.source = src2; param.target = trg2; map.mapItems.append(param); QCOMPARE(handler.handleMap(map, target), SUCCESS); QCOMPARE(target.getUIDMappings().size(), 2); QCOMPARE(target.getUIDMappings().at(0).iRemoteUID, src1); QCOMPARE(target.getUIDMappings().at(0).iLocalUID, trg1); QCOMPARE(target.getUIDMappings().at(1).iRemoteUID, src2); QCOMPARE(target.getUIDMappings().at(1).iLocalUID, trg2); } QTEST_MAIN(DataSync::CommandHandlerTest) buteo-syncml-0.5.15/tests_meego/CommandHandlerTest.h000066400000000000000000000125551433763642500224530ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef COMMANDHANDLERTEST_H #define COMMANDHANDLERTEST_H #include #include "StoragePlugin.h" #include "Mock.h" namespace DataSync { class CommandHandlerTest; class CommitTestStorage : public StoragePlugin { public: CommitTestStorage( const QString& aSourceURI ) : iSourceURI( aSourceURI ), iIdCounter( 0 ) { ContentFormat format; format.iType = "foo"; format.iVersion = "0.0"; iFormats.setPreferredRx( format ); iFormats.setPreferredTx( format ); iFormats.rx().append( format ); iFormats.tx().append( format ); } virtual ~CommitTestStorage() { } virtual const QString& getSourceURI() const { return iSourceURI; } const StorageContentFormatInfo& getFormatInfo() const { return iFormats; } virtual qint64 getMaxObjSize() const { return 0; } virtual QByteArray getPluginCTCaps( ProtocolVersion /*aVersion*/ ) const { return ""; } QByteArray getPluginExts( ) const { return ""; } virtual bool getAll( QList& /*aKeys*/ ) { return true; } virtual bool getModifications( QList& /*aNewKeys*/, QList& /*aReplacedKeys*/, QList& /*aDeletedKeys*/, const QDateTime& /*aTimeStamp*/ ) { return true; } virtual SyncItem* newItem() { return new MockSyncItem( "" ); } virtual SyncItem* getSyncItem( const SyncItemKey& /*aKey*/ ) { Q_ASSERT( 0 ); return NULL; } virtual QList getSyncItems( const QList& aKeyList ) { Q_UNUSED( aKeyList ); QList items; Q_ASSERT( 0 ); return items; } virtual QList addItems( const QList& aItems ) { QList statuses; for( int i = 0; i < aItems.count(); ++i ) { aItems[i]->setKey( QString::number( ++iIdCounter ) ); iAddedItems.append( *aItems[i]->getKey() ); statuses.append( STATUS_OK ); } return statuses; } virtual QList replaceItems( const QList& aItems ) { QList statuses; for( int i = 0; i < aItems.count(); ++i ) { iReplacedItems.append( *aItems[i]->getKey() ); statuses.append( STATUS_OK ); } return statuses; } virtual QList deleteItems( const QList& aKeys ) { QList statuses; for( int i = 0; i < aKeys.count(); ++i ) { iDeletedItems.append( aKeys ); statuses.append( STATUS_OK ); } return statuses; } #if 0 virtual bool deleteAllItems() { return true; } #endif friend class CommandHandlerTest; private: QString iSourceURI; StorageContentFormatInfo iFormats; QList iAddedItems; QList iReplacedItems; QList iDeletedItems; int iIdCounter; }; class CommandHandlerTest : public QObject { Q_OBJECT; public: CommandHandlerTest(); virtual ~CommandHandlerTest(); private slots: void testAdd_Client01(); void testAdd_Server01(); void testSyncAdd(); void testSyncReplace(); void testSyncDelete(); void testSyncReplaceConflict(); void testSyncReplaceConflict_01(); void testGetStatusType(); void testNotImplemented(); void testHandleMap(); private: }; } #endif // COMMANDHANDLERTEST_H buteo-syncml-0.5.15/tests_meego/CommandHandlerTest.pro000066400000000000000000000000351433763642500230120ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/ConflictResolverTest.cpp000066400000000000000000000033321433763642500234060ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ConflictResolverTest.h" using namespace DataSync; QTEST_MAIN(DataSync::ConflictResolverTest) buteo-syncml-0.5.15/tests_meego/ConflictResolverTest.h000066400000000000000000000034711433763642500230570ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CONFLICTRESOLVERTEST_H #define CONFLICTRESOLVERTEST_H #include namespace DataSync { class ConflictResolverTest: public QObject { Q_OBJECT; private slots: private: }; } #endif buteo-syncml-0.5.15/tests_meego/ConflictResolverTest.pro000066400000000000000000000000351433763642500234210ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/DevInfHandlerTest.cpp000066400000000000000000000145641433763642500226050ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "DevInfHandlerTest.h" #include "DevInfHandler.h" #include "ResponseGenerator.h" #include "DevInfPackage.h" #include "SyncMLLogging.h" using namespace DataSync; void DevInfHandlerTest::testComposeLocalInitiatedDevInfExchange1() { DeviceInfo deviceInfo; DevInfHandler handler( deviceInfo ); QListstorages; ProtocolVersion version = SYNCML_1_2; Role role = ROLE_CLIENT; ResponseGenerator generator; handler.iLocalDevInfSent = false; handler.composeLocalInitiatedDevInfExchange( storages, version, role, generator ); QCOMPARE( handler.iLocalDevInfSent, true ); const QList& packages = generator.getPackages(); QCOMPARE( packages.count(), 1 ); QCOMPARE( packages[0]->metaObject()->className(), "DataSync::DevInfPackage" ); } void DevInfHandlerTest::testComposeLocalInitiatedDevInfExchange2() { DeviceInfo deviceInfo; DevInfHandler handler( deviceInfo ); QListstorages; ProtocolVersion version = SYNCML_1_2; Role role = ROLE_CLIENT; ResponseGenerator generator; handler.iLocalDevInfSent = true; handler.composeLocalInitiatedDevInfExchange( storages, version, role, generator ); QCOMPARE( handler.iLocalDevInfSent, true ); const QList& packages = generator.getPackages(); QCOMPARE( packages.count(), 0 ); } void DevInfHandlerTest::testHandleGet1() { DeviceInfo deviceInfo; DevInfHandler handler( deviceInfo ); QListstorages; ProtocolVersion version = SYNCML_1_2; Role role = ROLE_CLIENT; ResponseGenerator generator; CommandParams get; handler.iLocalDevInfSent = false; handler.iRemoteDevInfReceived = false; ResponseStatusCode response = handler.handleGet( get, version, storages, role, generator ); QCOMPARE( response, COMMAND_FAILED ); QCOMPARE( handler.iLocalDevInfSent, false ); QCOMPARE( handler.iRemoteDevInfReceived, false ); } void DevInfHandlerTest::testHandleGet2() { DeviceInfo deviceInfo; DevInfHandler handler( deviceInfo ); QListstorages; ProtocolVersion version = SYNCML_1_2; Role role = ROLE_CLIENT; ResponseGenerator generator; CommandParams get; ItemParams item; item.target = SYNCML_DEVINF_PATH_12; get.items.append(item); handler.iLocalDevInfSent = false; handler.iRemoteDevInfReceived = false; ResponseStatusCode response = handler.handleGet( get, version, storages, role, generator ); QCOMPARE( response, SUCCESS ); QCOMPARE( handler.iLocalDevInfSent, true ); QCOMPARE( handler.iRemoteDevInfReceived, false ); const QList& packages = generator.getPackages(); QCOMPARE( packages.count(), 1 ); QCOMPARE( packages[0]->metaObject()->className(), "DataSync::DevInfPackage" ); } void DevInfHandlerTest::testHandleGet3() { DeviceInfo deviceInfo; DevInfHandler handler( deviceInfo ); QListstorages; ProtocolVersion version = SYNCML_1_2; Role role = ROLE_CLIENT; ResponseGenerator generator; CommandParams get; ItemParams item; item.target = SYNCML_DEVINF_PATH_12; get.items.append(item); handler.iLocalDevInfSent = false; handler.iRemoteDevInfReceived = true; ResponseStatusCode response = handler.handleGet( get, version, storages, role, generator ); QCOMPARE( response, SUCCESS ); QCOMPARE( handler.iLocalDevInfSent, true ); QCOMPARE( handler.iRemoteDevInfReceived, true ); const QList& packages = generator.getPackages(); QCOMPARE( packages.count(), 1 ); QCOMPARE( packages[0]->metaObject()->className(), "DataSync::DevInfPackage" ); } void DevInfHandlerTest::testHandlePut() { DeviceInfo deviceInfo; DevInfHandler handler( deviceInfo ); ProtocolVersion version = SYNCML_1_2; PutParams put; ResponseStatusCode response = handler.handlePut( put, version ); QCOMPARE( response, COMMAND_FAILED ); put.devInf.source = SYNCML_DEVINF_PATH_12; response = handler.handlePut( put, version ); QCOMPARE( response, SUCCESS ); } void DevInfHandlerTest::testHandleResults() { DeviceInfo deviceInfo; DevInfHandler handler( deviceInfo ); ProtocolVersion version = SYNCML_1_2; ResultsParams results; ResponseStatusCode response = handler.handleResults( results, version ); QCOMPARE( response, COMMAND_FAILED ); results.devInf.source = SYNCML_DEVINF_PATH_12; response = handler.handleResults( results, version ); QCOMPARE( response, SUCCESS ); } QTEST_MAIN(DevInfHandlerTest) buteo-syncml-0.5.15/tests_meego/DevInfHandlerTest.h000066400000000000000000000040341433763642500222410ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DEVINFHANDLERTEST_H #define DEVINFHANDLERTEST_H #include class DevInfHandlerTest : public QObject { Q_OBJECT; private slots: void testComposeLocalInitiatedDevInfExchange1(); void testComposeLocalInitiatedDevInfExchange2(); void testHandleGet1(); void testHandleGet2(); void testHandleGet3(); void testHandlePut(); void testHandleResults(); }; #endif // DEVINFHANDLERTEST_H buteo-syncml-0.5.15/tests_meego/DevInfHandlerTest.pro000066400000000000000000000000351433763642500226070ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/DevInfPackageTest.cpp000066400000000000000000000144071433763642500225570ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "DevInfPackageTest.h" #include "DevInfPackage.h" #include "SyncMLMessage.h" #include "Mock.h" #include "QtEncoder.h" #include "DeviceInfo.h" #include "Fragments.h" void DevInfPackageTest::testPutGet() { QList storage_plugins; DeviceInfo devInfo; MockStorage storage("storage"); storage_plugins.append(&storage); const int SIZE_TRESHOLD = 10000; DevInfPackage pkg(storage_plugins, devInfo, SYNCML_1_2, ROLE_CLIENT ); SyncMLMessage msg(HeaderParams(), SYNCML_1_2); int remaining = SIZE_TRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); QVERIFY(remaining < SIZE_TRESHOLD); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QByteArray putData = extractElement( result_xml, "", "" ); QVERIFY( !putData.isEmpty() ); verifyDevInf(putData); QByteArray getData = extractElement( result_xml, "", "" ); QVERIFY( !getData.isEmpty() ); verifyGet(getData); } void DevInfPackageTest::testResults() { QList storage_plugins; DeviceInfo devInfo; MockStorage storage("storage"); storage_plugins.append(&storage); const int msgId = 99; const int cmdId = 109; const int SIZE_TRESHOLD = 10000; bool retrieveRemoteDevInf = false; DevInfPackage pkg(msgId, cmdId, storage_plugins, devInfo, SYNCML_1_2, ROLE_CLIENT, retrieveRemoteDevInf ); SyncMLMessage msg(HeaderParams(), SYNCML_1_2); int remaining = SIZE_TRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); QVERIFY(remaining < SIZE_TRESHOLD); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QByteArray resultsData = extractElement( result_xml, "", "" ); QVERIFY( !resultsData.isEmpty() ); QByteArray msgRef = extractElement( resultsData, "", "", "", "" ); QVERIFY( getData.isEmpty() ); } void DevInfPackageTest::testResultsGet() { QList storage_plugins; DeviceInfo devInfo; MockStorage storage("storage"); storage_plugins.append(&storage); const int msgId = 99; const int cmdId = 109; const int SIZE_TRESHOLD = 10000; bool retrieveRemoteDevInf = true; DevInfPackage pkg(msgId, cmdId, storage_plugins, devInfo, SYNCML_1_2, ROLE_CLIENT, retrieveRemoteDevInf ); SyncMLMessage msg(HeaderParams(), SYNCML_1_2); int remaining = SIZE_TRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); QVERIFY(remaining < SIZE_TRESHOLD); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QByteArray resultsData = extractElement( result_xml, "", "" ); QVERIFY( !resultsData.isEmpty() ); QByteArray msgRef = extractElement( resultsData, "", "", "", "" ); QVERIFY( !getData.isEmpty() ); verifyGet(getData); } QByteArray DevInfPackageTest::extractElement( const QByteArray& aData, const QByteArray& startElement, const QByteArray& endElement ) { QByteArray result; int start = aData.indexOf( startElement ); if( start == -1 ) { return result; } int end = aData.indexOf( endElement, start ); if( end == -1 ) { return result; } result = aData.mid( start + startElement.length(), end - start - startElement.length() ); return result; } void DevInfPackageTest::verifyDevInf( const QByteArray& aData ) { QVERIFY( aData.contains( "") ); QVERIFY( aData.contains( "application/vnd.syncml-devinf+xml") ); QVERIFY( aData.contains( "./devinf12") ); QVERIFY( aData.contains( "syncml:devinf") ); } void DevInfPackageTest::verifyGet( const QByteArray& aData ) { QVERIFY( aData.contains( "application/vnd.syncml-devinf+xml") ); QVERIFY( aData.contains( "./devinf12") ); } QTEST_MAIN(DevInfPackageTest) buteo-syncml-0.5.15/tests_meego/DevInfPackageTest.h000066400000000000000000000042221433763642500222160ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef DEVINFPACKAGETEST_H #define DEVINFPACKAGETEST_H #include class DevInfPackageTest : public QObject { Q_OBJECT private slots: void testPutGet(); void testResults(); void testResultsGet(); private: QByteArray extractElement( const QByteArray& aData, const QByteArray& startElement, const QByteArray& endElement ); void verifyDevInf( const QByteArray& aData ); void verifyGet( const QByteArray& aData ); }; #endif // DEVINFPACKAGETEST_H buteo-syncml-0.5.15/tests_meego/DevInfPackageTest.pro000066400000000000000000000000351433763642500225650ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/FinalPackageTest.cpp000066400000000000000000000043751433763642500224400ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "FinalPackageTest.h" #include "FinalPackage.h" #include "SyncMLMessage.h" #include "Fragments.h" #include "QtEncoder.h" using namespace DataSync; void FinalPackageTest::testPackage() { FinalPackage pkg; SyncMLMessage msg(HeaderParams(), SYNCML_1_2); const int SIZE_TRESHOLD = 10000; int remaining = SIZE_TRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); QVERIFY(remaining < SIZE_TRESHOLD); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QVERIFY(result_xml.indexOf(SYNCML_ELEMENT_FINAL) != -1); } QTEST_MAIN(FinalPackageTest) buteo-syncml-0.5.15/tests_meego/FinalPackageTest.h000066400000000000000000000034671433763642500221060ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef FINALPACKAGETEST_H #define FINALPACKAGETEST_H #include class FinalPackageTest : public QObject { Q_OBJECT private slots: void testPackage(); }; #endif // FINALPACKAGETEST_H buteo-syncml-0.5.15/tests_meego/FinalPackageTest.pro000066400000000000000000000000351433763642500224430ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/LocalChangesPackageTest.cpp000066400000000000000000000267371433763642500237400ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "LocalChangesPackageTest.h" #include "SyncItem.h" #include "SyncTarget.h" #include "LocalChangesPackage.h" #include "SyncMLMessage.h" #include "QtEncoder.h" #include "Mock.h" #include "Fragments.h" LocalChangesPackageStorage::LocalChangesPackageStorage( const QString& aSourceURI ) : iSourceURI( aSourceURI ) { ContentFormat format; format.iType = "text/foo"; format.iVersion = "1.0"; iFormats.setPreferredRx( format ); iFormats.setPreferredTx( format ); iFormats.rx().append( format ); iFormats.tx().append( format ); } LocalChangesPackageStorage::~LocalChangesPackageStorage() { qDeleteAll( iSyncItems ); iSyncItems.clear(); } void LocalChangesPackageStorage::setItems( const QList aSyncItems ) { iSyncItems = aSyncItems; } const QString& LocalChangesPackageStorage::getSourceURI() const { return iSourceURI; } const StorageContentFormatInfo& LocalChangesPackageStorage::getFormatInfo() const { return iFormats; } qint64 LocalChangesPackageStorage::getMaxObjSize() const { return 0; } QByteArray LocalChangesPackageStorage::getPluginCTCaps( ProtocolVersion aVersion ) const { Q_UNUSED( aVersion ); return QByteArray(); } QByteArray LocalChangesPackageStorage::getPluginExts() const { return QByteArray(); } bool LocalChangesPackageStorage::getAll( QList& aKeys ) { Q_UNUSED( aKeys ); return true; } bool LocalChangesPackageStorage::getModifications( QList& aNewKeys, QList& aReplacedKeys, QList& aDeletedKeys, const QDateTime& aTimeStamp ) { Q_UNUSED( aNewKeys ); Q_UNUSED( aReplacedKeys ); Q_UNUSED( aDeletedKeys ); Q_UNUSED( aTimeStamp ); return true; } SyncItem* LocalChangesPackageStorage::newItem() { return NULL; } SyncItem* LocalChangesPackageStorage::getSyncItem( const SyncItemKey& aKey ) { SyncItem* item = 0; for( int i = 0; i < iSyncItems.count(); ++i ) { if( iSyncItems[i] && iSyncItems[i]->getKey() == aKey ) { item = iSyncItems[i]; iSyncItems.removeAt(i); break; } } return item; } QList LocalChangesPackageStorage::getSyncItems( const QList& aKeyList ) { QList items; for( int i = 0; i < aKeyList.count(); ++i ) { SyncItem* item = 0; for( int a = 0; a < iSyncItems.count(); ++a ) { if( iSyncItems[a] && iSyncItems[a]->getKey() == aKeyList[i] ) { item = iSyncItems[a]; iSyncItems.removeAt(a); break; } } items.append( item ); } return items; } QList LocalChangesPackageStorage::addItems( const QList& aItems ) { Q_UNUSED( aItems ); QList status; return status; } QList LocalChangesPackageStorage::replaceItems( const QList& aItems ) { Q_UNUSED( aItems ); QList status; return status; } QList LocalChangesPackageStorage::deleteItems( const QList& aKeys ) { Q_UNUSED( aKeys ); QList status; return status; } LocalChangesPackageTest::LocalChangesPackageTest() { } LocalChangesPackageTest::~LocalChangesPackageTest() { } void LocalChangesPackageTest::testSimpleClient() { // Simple test for LocalChangesPackage for sending few // modifications in a single message in client mode const int msgSize = 65535; const int maxChanges = 50; LocalChangesPackageStorage storage( "./LocalContacts" ); LocalChanges changes; QList items; const QString itemTypes( "text/foo" ); const QString addedItemId( "addedItem" ); const QByteArray addedItemData ( "addedData" ); MockSyncItem* addedItem = new MockSyncItem( addedItemId ); addedItem->setType( itemTypes ); addedItem->write( 0, addedItemData ); items.append( addedItem ); changes.added.append( addedItemId ); const QString replacedItemId( "replacedItem" ); const QByteArray replacedItemData ( "replacedData" ); MockSyncItem* replacedItem = new MockSyncItem( replacedItemId ); replacedItem->setType( itemTypes ); replacedItem->write( 0, replacedItemData ); items.append( replacedItem ); changes.modified.append( replacedItemId ); const QString deletedItemId( "deletedItem" ); changes.removed.append( deletedItemId ); storage.setItems( items ); SyncMode syncMode; SyncTarget target( NULL, &storage, syncMode, "localAnchor" ); target.setTargetDatabase( "./RemoteContacts"); LocalChangesPackage package( target, changes, msgSize, ROLE_CLIENT, maxChanges ); SyncMLMessage msg( HeaderParams(), SYNCML_1_2 ); int remaining = msgSize; QVERIFY( package.write( msg, remaining , false, SYNCML_1_2) ); QVERIFY( remaining < msgSize ); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); // Check that the items were written QVERIFY( result_xml.contains( addedItemId.toLatin1() ) ); QVERIFY( result_xml.contains( addedItemData ) ); QVERIFY( result_xml.contains( replacedItemId.toLatin1() ) ); QVERIFY( result_xml.contains( replacedItemData ) ); QVERIFY( result_xml.contains( deletedItemId.toLatin1() ) ); } void LocalChangesPackageTest::testSimpleServer() { // Simple test for LocalChangesPackage for sending few // modifications in a single message in server mode const int msgSize = 65535; const int maxChanges = 50; LocalChangesPackageStorage storage( "./LocalContacts" ); LocalChanges changes; QList items; const QString itemTypes( "text/foo" ); const QString addedItemId( "addedItem" ); const QByteArray addedItemData ( "addedData" ); MockSyncItem* addedItem = new MockSyncItem( addedItemId ); addedItem->setType( itemTypes ); addedItem->write( 0, addedItemData ); items.append( addedItem ); changes.added.append( addedItemId ); const QString replacedItemId( "replacedItem" ); const QByteArray replacedItemData ( "replacedData" ); MockSyncItem* replacedItem = new MockSyncItem( replacedItemId ); replacedItem->setType( itemTypes ); replacedItem->write( 0, replacedItemData ); items.append( replacedItem ); changes.modified.append( replacedItemId ); const QString deletedItemId( "deletedItem" ); changes.removed.append( deletedItemId ); storage.setItems( items ); SyncMode syncMode; SyncTarget target( NULL, &storage, syncMode, "localAnchor" ); target.setTargetDatabase( "./RemoteContacts"); const QString mappedReplacedItemId( "replacedItemMapped" ); UIDMapping replacedMap; replacedMap.iLocalUID = replacedItemId; replacedMap.iRemoteUID = mappedReplacedItemId; target.addUIDMapping( replacedMap ); const QString mappedDeletedItemId( "deletedItemMapped" ); UIDMapping deletedMap; deletedMap.iLocalUID = deletedItemId; deletedMap.iRemoteUID = mappedDeletedItemId; target.addUIDMapping( deletedMap ); LocalChangesPackage package( target, changes, msgSize, ROLE_SERVER, maxChanges ); SyncMLMessage msg( HeaderParams(), SYNCML_1_2 ); int remaining = msgSize; QVERIFY( package.write( msg, remaining , false, SYNCML_1_2) ); QVERIFY( remaining < msgSize ); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); // Check that the items were written QVERIFY( result_xml.contains( addedItemId.toLatin1() ) ); QVERIFY( result_xml.contains( addedItemData ) ); QVERIFY( result_xml.contains( mappedReplacedItemId.toLatin1() ) ); QVERIFY( result_xml.contains( replacedItemData ) ); QVERIFY( result_xml.contains( mappedDeletedItemId.toLatin1() ) ); } void LocalChangesPackageTest::testLargeObjects() { // Test for LocalChangesPackage for checking if sending of large objects // functions properly const int msgSize = 1024; const int objSize = 1536; const int maxChanges = 50; LocalChangesPackageStorage storage( "./LocalContacts" ); LocalChanges changes; QList items; const QString itemTypes( "text/foo" ); const QString addedItemId( "addedItem" ); QByteArray addedItemData; addedItemData.fill( '0', objSize ); MockSyncItem* addedItem = new MockSyncItem( addedItemId ); addedItem->setType( itemTypes ); addedItem->write( 0, addedItemData ); items.append( addedItem ); changes.added.append( addedItemId ); storage.setItems( items ); SyncMode syncMode; SyncTarget target( NULL, &storage, syncMode, "localAnchor" ); target.setTargetDatabase( "./RemoteContacts"); LocalChangesPackage package( target, changes, msgSize, ROLE_CLIENT, maxChanges ); int remaining = msgSize; SyncMLMessage msg1( HeaderParams(), SYNCML_1_2 ); QVERIFY( !package.write( msg1, remaining, false, SYNCML_1_2 ) ); QVERIFY( remaining < msgSize ); QtEncoder encoder; QByteArray result_xml1; QVERIFY( encoder.encodeToXML( msg1, result_xml1, true ) ); // Check that the item was written with MoreData QVERIFY( result_xml1.contains( addedItemId.toLatin1() ) ); QVERIFY( result_xml1.contains( "MoreData" ) ); remaining = msgSize; SyncMLMessage msg2( HeaderParams(), SYNCML_1_2 ); QVERIFY( package.write( msg2, remaining, false, SYNCML_1_2 ) ); QVERIFY( remaining < msgSize ); QByteArray result_xml2; QVERIFY( encoder.encodeToXML( msg2, result_xml2, true ) ); // Check that the rest of the item was written QVERIFY( result_xml2.contains( addedItemId.toLatin1() ) ); QVERIFY( !result_xml2.contains( "MoreData" ) ); } QTEST_MAIN(LocalChangesPackageTest) buteo-syncml-0.5.15/tests_meego/LocalChangesPackageTest.h000066400000000000000000000066471433763642500234030ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LOCALCHANGESPACKAGETEST_H #define LOCALCHANGESPACKAGETEST_H #include #include "StoragePlugin.h" using namespace DataSync; class LocalChangesPackageStorage : public StoragePlugin { public: LocalChangesPackageStorage( const QString& aSourceURI ); virtual ~LocalChangesPackageStorage(); void setItems( const QList aSyncItems ); virtual const QString& getSourceURI() const; virtual qint64 getMaxObjSize() const; virtual const StorageContentFormatInfo& getFormatInfo() const; virtual QByteArray getPluginCTCaps( ProtocolVersion aVersion ) const; virtual QByteArray getPluginExts() const; virtual bool getAll( QList& aKeys ); virtual bool getModifications( QList& aNewKeys, QList& aReplacedKeys, QList& aDeletedKeys, const QDateTime& aTimeStamp ); virtual SyncItem* newItem(); virtual SyncItem* getSyncItem( const SyncItemKey& aKey ); virtual QList getSyncItems( const QList& aKeyList ); virtual QList addItems( const QList& aItems ); virtual QList replaceItems( const QList& aItems ); virtual QList deleteItems( const QList& aKeys ); private: QString iSourceURI; StorageContentFormatInfo iFormats; QList iSyncItems; }; class LocalChangesPackageTest : public QObject { Q_OBJECT; public: LocalChangesPackageTest(); virtual ~LocalChangesPackageTest(); private slots: void testSimpleClient(); void testSimpleServer(); void testLargeObjects(); }; #endif // LOCALCHANGESPACKAGETEST_H buteo-syncml-0.5.15/tests_meego/LocalChangesPackageTest.pro000066400000000000000000000000351433763642500237350ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/LocalMappingsPackageTest.cpp000066400000000000000000000065711433763642500241400ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "LocalMappingsPackageTest.h" #include "LocalMappingsPackage.h" #include "SyncMLMessage.h" #include "Mock.h" #include "QtEncoder.h" #include "Fragments.h" using namespace DataSync; void LocalMappingsPackageTest::testPackage() { // Create a mock SyncTarget and add two mappings to it. const QString source_db = "source"; const QString target_db = "target"; QList mappings; UIDMapping mapping1 = { "remoteUID1", "localUID1" }; UIDMapping mapping2 = { "remoteUID2", "localUID2" }; mappings.append( mapping1 ); mappings.append( mapping2 ); // Create a mappings package and verify that mapping is stored. LocalMappingsPackage pkg( source_db, target_db, mappings ); QCOMPARE(pkg.iSourceDatabase, source_db); QCOMPARE(pkg.iTargetDatabase, target_db); QCOMPARE(pkg.iMappings.size(), 2); QCOMPARE(pkg.iMappings.at(0).iLocalUID, mapping1.iLocalUID); QCOMPARE(pkg.iMappings.at(0).iRemoteUID, mapping1.iRemoteUID); QCOMPARE(pkg.iMappings.at(1).iLocalUID, mapping2.iLocalUID); QCOMPARE(pkg.iMappings.at(1).iRemoteUID, mapping2.iRemoteUID); // Write, only first mapping should fit. SyncMLMessage msg(HeaderParams(), SYNCML_1_2); const int SIZE_THRESHOLD = 160; int remaining = SIZE_THRESHOLD; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), false); QVERIFY(remaining < SIZE_THRESHOLD); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( msg, result_xml, true ) ); QVERIFY(result_xml.indexOf(SYNCML_ELEMENT_MAP) != -1); QVERIFY(result_xml.indexOf(SYNCML_ELEMENT_MAPITEM) != -1); // Write again, should complete. remaining += 200; QCOMPARE(pkg.write(msg, remaining, false, SYNCML_1_2), true); } QTEST_MAIN(LocalMappingsPackageTest) buteo-syncml-0.5.15/tests_meego/LocalMappingsPackageTest.h000066400000000000000000000035301433763642500235750ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LOCALMAPPINGSPACKAGETEST_H #define LOCALMAPPINGSPACKAGETEST_H #include class LocalMappingsPackageTest : public QObject { Q_OBJECT private slots: void testPackage(); }; #endif // LOCALMAPPINGSPACKAGETEST_H buteo-syncml-0.5.15/tests_meego/LocalMappingsPackageTest.pro000066400000000000000000000000351433763642500241430ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/Mock.h000066400000000000000000000246601433763642500176300ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef MOCK_HH #define MOCK_HH #include "SyncItem.h" #include "StoragePlugin.h" #include "Transport.h" #include "BaseTransport.h" #include "SyncAgentConfig.h" #include "SyncTarget.h" #include "OBEXConnection.h" #include "DatabaseHandler.h" #include "StorageHandler.h" #include #include #include "SyncMLMessage.h" // For test conveniance using namespace DataSync; /*! \brief Mock class for testing syncitem dependent code */ class MockSyncItem : public SyncItem { public: MockSyncItem ( const SyncItemKey& aKey ) { setKey( aKey ); } virtual ~MockSyncItem() { } virtual qint64 getSize() const { return iData.size(); } virtual bool read( qint64 aOffset, qint64 aLength, QByteArray& aData ) const { aData = iData.mid( aOffset, aLength ); return true; } virtual bool write( qint64 aOffset, const QByteArray& aData ) { iData.resize( aOffset + aData.size() ); iData.replace( aOffset, aData.size(), aData ); return true; } virtual bool resize( qint64 aLength ) { iData.resize( aLength ); return true; } protected: QByteArray iData; }; /*! \brief Mock class for testing storageplugin dependent code */ class MockStorage: public StoragePlugin { public: MockStorage( const QString& aURI, const QString& aContentFormat = "text/x-vcard", const QString& aContentVersion = "1.0" ) { iSourceURI = aURI; iMaxObjSize = 500000; ContentFormat format; format.iType = aContentFormat; format.iVersion = aContentVersion; iFormats.setPreferredRx(format); iFormats.setPreferredTx(format); iFormats.rx().append(format); iFormats.tx().append(format); iIdCounter = 0; } virtual ~MockStorage() {} virtual const QString& getSourceURI() const { return iSourceURI; } virtual const StorageContentFormatInfo& getFormatInfo() const { return iFormats; } virtual qint64 getMaxObjSize() const { return iMaxObjSize; } virtual QByteArray getPluginCTCaps( ProtocolVersion aVersion ) const { //TODO: check this needs to be removed for bookmark sync harmattan 1.0 QByteArray ctCaps( "" "text/x-vBookmark" "1.0" "" "read" "bool" "1" "Read" "" "" ); if ( aVersion == SYNCML_1_2 ) { ctCaps.prepend( "" ); ctCaps.append( QByteArray( "" "application/vnd.omads-folder+xml" "1.0" "" "read" "bool" "1" "Read" "" "" ) ); ctCaps.append( "" ); } return ctCaps; } QByteArray getPluginExts( ) const { QByteArray exts( "" "SynchronizeGroup" "X-CT" "" ); return exts; } virtual bool getAll( QList& aKeys ) { aKeys << SyncItemKey("1") << SyncItemKey("2") << SyncItemKey("3") << SyncItemKey("5"); return true; } virtual bool getModifications( QList& aNewKeys, QList& aReplacedKeys, QList& aDeletedKeys, const QDateTime& /*aTimeStamp*/ ) { aNewKeys << SyncItemKey("1") << SyncItemKey("5") << SyncItemKey("5"); aReplacedKeys << SyncItemKey("2") << SyncItemKey("3"); aDeletedKeys << SyncItemKey("1") << SyncItemKey("2") << SyncItemKey("3") << SyncItemKey("5"); return true; } virtual SyncItem* newItem() { return new MockSyncItem( "" ); } virtual SyncItem* getSyncItem( const SyncItemKey& aKey ) { if (aKey == "") { return NULL; } else { return new MockSyncItem( aKey ); } } virtual QList getSyncItems( const QList& aKeyList) { QList items; foreach( SyncItemKey key, aKeyList ) { items.append( getSyncItem( key ) ); } return items; } virtual QList addItems( const QList& aItems ) { QList results; for( int i = 0; i < aItems.count(); ++i ) { aItems[i]->setKey( QString("MockStorage-item-%1").arg( ++iIdCounter ) ); results.append( STATUS_OK ); } return results; } virtual QList replaceItems( const QList& aItems ) { QList results; for( int i = 0; i < aItems.count(); ++i ) { results.append( STATUS_OK ); } return results; } virtual QList deleteItems( const QList& aKeys ) { QList results; for( int i = 0; i < aKeys.count(); ++i ) { results.append( STATUS_OK ); } return results; } #if 0 virtual bool deleteAllItems() { return true; } #endif protected: QString iSourceURI; qint64 iMaxObjSize; StorageContentFormatInfo iFormats; int iIdCounter; }; class MockTransport : public DataSync::Transport { Q_OBJECT public: MockTransport(const QString& file, QObject* parent = 0) : Transport(parent), iFile(file) {} virtual ~MockTransport() { }; virtual void setProperty( const QString&, const QString& ) { } virtual bool init() { return true; } virtual void close() { } virtual void setRemoteLocURI( const QString& ) {}; virtual bool usesWbXML() { return false; } virtual bool sendSyncML( SyncMLMessage* aMessage) { delete aMessage; aMessage = NULL; return true; } virtual bool sendSAN( const QByteArray& /*aMessage*/ ) { return true; } virtual bool receive() { QFile syncmlFile(iFile); if (!syncmlFile.open(QFile::ReadOnly | QFile::Text)) { qDebug() << "File Cannot be opened"; } else { qDebug() << "Handling incoming data.. from " << iFile; emit readXMLData(&syncmlFile, true); } return true; } private slots: virtual void purgeAndResendBuffer() {}; private: QIODevice* data; QString iFile; }; class MockSyncTarget : public SyncTarget{ public: MockSyncTarget(ChangeLog* aChangeLog, StoragePlugin* aStoragePlugin, const SyncMode& aSyncMode, const QString aLocalNextAnchor) : SyncTarget(aChangeLog, aStoragePlugin, aSyncMode, aLocalNextAnchor) { } ~MockSyncTarget() { } bool reverted() {return true;} private: }; class TestTransport : public BaseTransport { Q_OBJECT; public: TestTransport( bool aDoReceive, QObject* aParent = NULL ) : BaseTransport( CONTEXT_DS, aParent ), iDoReceive( aDoReceive ) { } virtual ~TestTransport() { } virtual void setProperty( const QString& aProperty, const QString& aValue ) { Q_UNUSED( aProperty ); Q_UNUSED( aValue ); } virtual bool init() { return true; } virtual void close() { } QByteArray iData; QString iContentType; protected: virtual bool prepareSend() { return true; } virtual bool doSend( const QByteArray& aData, const QString& aContentType ) { iData = aData; iContentType = aContentType; if( iDoReceive ) { receive( aData, aContentType ); } return true; } virtual bool doReceive( const QString& aContentType ) { Q_UNUSED( aContentType ); if( iDoReceive ) { receive( iData, iContentType ); } return true; } private: bool iDoReceive; }; class OBEXConnectionTest : public DataSync::OBEXConnection { public: OBEXConnectionTest(bool connected) : OBEXConnection(), mIsConnected(connected) { } int connect() { return mIsConnected ? 123 : -1; } bool isConnected() const { return mIsConnected; } void disconnect() { } virtual ~OBEXConnectionTest() { } private: int mIsConnected; }; #endif buteo-syncml-0.5.15/tests_meego/NonceStorageTest.cpp000066400000000000000000000053041433763642500225130ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "NonceStorageTest.h" #include "DatabaseHandler.h" #include "NonceStorage.h" const QString DB( "/tmp/noncestoragetest.db" ); const QString LOCALDEVICE( "localDevice" ); const QString REMOTEDEVICE( "remoteDevice" ); using namespace DataSync; void NonceStorageTest::testGenerateNonce() { DatabaseHandler handler( DB ); NonceStorage nonces( handler.getDbHandle(), LOCALDEVICE, REMOTEDEVICE ); QByteArray nonce = nonces.generateNonce(); QVERIFY( !nonce.isEmpty() ); } void NonceStorageTest::testSetGetNonce() { DatabaseHandler handler( DB ); NonceStorage nonces( handler.getDbHandle(), LOCALDEVICE, REMOTEDEVICE ); QByteArray nonce = nonces.generateNonce(); nonces.setNonce( nonce ); QCOMPARE( nonces.nonce(), nonce ); } void NonceStorageTest::testClearNonce() { DatabaseHandler handler( DB ); NonceStorage nonces( handler.getDbHandle(), LOCALDEVICE, REMOTEDEVICE ); QByteArray nonce = nonces.generateNonce(); nonces.setNonce( nonce ); nonces.clearNonce(); QVERIFY( nonces.nonce().isEmpty() ); } QTEST_MAIN(DataSync::NonceStorageTest) buteo-syncml-0.5.15/tests_meego/NonceStorageTest.h000066400000000000000000000035661433763642500221700ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef NONCESTORAGETEST_H #define NONCESTORAGETEST_H #include namespace DataSync { class NonceStorageTest: public QObject { Q_OBJECT; private slots: void testGenerateNonce(); void testSetGetNonce(); void testClearNonce(); }; } #endif buteo-syncml-0.5.15/tests_meego/NonceStorageTest.pro000066400000000000000000000000351433763642500225250ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/ResponseGeneratorTest.cpp000066400000000000000000000526361433763642500236030ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include "ResponseGeneratorTest.h" #include "ResponseGenerator.h" #include "LocalMappingsPackage.h" #include "QtEncoder.h" #include "SyncMLMessage.h" using namespace DataSync; // @todo: need better unit tests here void ResponseGeneratorTest::testAddStatusStatus() { ResponseGenerator respGen; StatusParams* stParams1 = new StatusParams(); stParams1->cmdId = 1; respGen.addStatus(stParams1); StatusParams* stParams2 = new StatusParams(); stParams2->cmdId = 2; stParams2->cmd = SYNCML_ELEMENT_SYNCHDR; respGen.addStatus(stParams2); QCOMPARE(respGen.getStatuses().size(), 2); QCOMPARE(respGen.getStatuses().at(0)->cmdId, 2); QCOMPARE(respGen.getStatuses().at(1)->cmdId, 1); respGen.ignoreStatuses(true); respGen.addStatus(new StatusParams()); QCOMPARE(respGen.getStatuses().size(), 2); } void ResponseGeneratorTest::testAddStatusHeader() { ResponseGenerator respGen; HeaderParams header; ChalParams chal; int id = 123; QString type("fooType"); header.msgID = id; chal.meta.type = type; respGen.addStatus(header, SUCCESS); respGen.addStatus(header, chal, ITEM_ADDED); QCOMPARE(respGen.getStatuses().size(), 2); QCOMPARE(respGen.getStatuses().at(0)->msgRef, id); QCOMPARE(respGen.getStatuses().at(0)->data, SUCCESS); QCOMPARE(respGen.getStatuses().at(1)->msgRef, id); QCOMPARE(respGen.getStatuses().at(1)->data, ITEM_ADDED); QCOMPARE(respGen.getStatuses().at(1)->chal.meta.type, type); } void ResponseGeneratorTest::testAddStatusCommand1() { ResponseGenerator respGen; CommandParams params[10]; QString fooSrc1 = "fooSrc1"; QString fooSrc2 = "fooSrc2"; params[0].commandType = CommandParams::COMMAND_ALERT; params[1].commandType = CommandParams::COMMAND_ADD; params[2].commandType = CommandParams::COMMAND_REPLACE; params[3].commandType = CommandParams::COMMAND_DELETE; params[4].commandType = CommandParams::COMMAND_GET; params[5].commandType = CommandParams::COMMAND_COPY; params[6].commandType = CommandParams::COMMAND_MOVE; params[7].commandType = CommandParams::COMMAND_EXEC; params[8].commandType = CommandParams::COMMAND_ATOMIC; params[9].commandType = CommandParams::COMMAND_SEQUENCE; ItemParams item1; item1.source = fooSrc1; ItemParams item2; item2.source = fooSrc2; params[9].items.append(item1); params[9].items.append(item2); for (int i = 0; i < 10; i++) respGen.addStatus(params[i], SUCCESS, true); respGen.ignoreStatuses(true); respGen.addStatus(params[0], SUCCESS, true); QCOMPARE(respGen.getStatuses().size(), 10); QCOMPARE(respGen.getStatuses().at(0)->cmd, QString(SYNCML_ELEMENT_ALERT)); QCOMPARE(respGen.getStatuses().at(1)->cmd, QString(SYNCML_ELEMENT_ADD)); QCOMPARE(respGen.getStatuses().at(2)->cmd, QString(SYNCML_ELEMENT_REPLACE)); QCOMPARE(respGen.getStatuses().at(3)->cmd, QString(SYNCML_ELEMENT_DELETE)); QCOMPARE(respGen.getStatuses().at(4)->cmd, QString(SYNCML_ELEMENT_GET)); QCOMPARE(respGen.getStatuses().at(5)->cmd, QString(SYNCML_ELEMENT_COPY)); QCOMPARE(respGen.getStatuses().at(6)->cmd, QString(SYNCML_ELEMENT_MOVE)); QCOMPARE(respGen.getStatuses().at(7)->cmd, QString(SYNCML_ELEMENT_EXEC)); QCOMPARE(respGen.getStatuses().at(8)->cmd, QString(SYNCML_ELEMENT_ATOMIC)); QCOMPARE(respGen.getStatuses().at(9)->cmd, QString(SYNCML_ELEMENT_SEQUENCE)); QCOMPARE(respGen.getStatuses().at(9)->items.at(0).source, fooSrc1); QCOMPARE(respGen.getStatuses().at(9)->items.at(1).source, fooSrc2); } void ResponseGeneratorTest::testAddStatusCommand2() { ResponseGenerator respGen; CommandParams params[10]; QString fooSrc1 = "fooSrc1"; QString fooSrc2 = "fooSrc2"; params[0].commandType = CommandParams::COMMAND_ALERT; params[1].commandType = CommandParams::COMMAND_ADD; params[2].commandType = CommandParams::COMMAND_REPLACE; params[3].commandType = CommandParams::COMMAND_DELETE; params[4].commandType = CommandParams::COMMAND_GET; params[5].commandType = CommandParams::COMMAND_COPY; params[6].commandType = CommandParams::COMMAND_MOVE; params[7].commandType = CommandParams::COMMAND_EXEC; params[8].commandType = CommandParams::COMMAND_ATOMIC; params[9].commandType = CommandParams::COMMAND_SEQUENCE; ItemParams item1; item1.source = fooSrc1; ItemParams item2; item2.source = fooSrc2; params[9].items.append(item1); params[9].items.append(item2); for (int i = 0; i < 10; i++) respGen.addStatus(params[i], SUCCESS, QList()); respGen.ignoreStatuses(true); respGen.addStatus(params[0], SUCCESS, true); QCOMPARE(respGen.getStatuses().size(), 10); QCOMPARE(respGen.getStatuses().at(0)->cmd, QString(SYNCML_ELEMENT_ALERT)); QCOMPARE(respGen.getStatuses().at(1)->cmd, QString(SYNCML_ELEMENT_ADD)); QCOMPARE(respGen.getStatuses().at(2)->cmd, QString(SYNCML_ELEMENT_REPLACE)); QCOMPARE(respGen.getStatuses().at(3)->cmd, QString(SYNCML_ELEMENT_DELETE)); QCOMPARE(respGen.getStatuses().at(4)->cmd, QString(SYNCML_ELEMENT_GET)); QCOMPARE(respGen.getStatuses().at(5)->cmd, QString(SYNCML_ELEMENT_COPY)); QCOMPARE(respGen.getStatuses().at(6)->cmd, QString(SYNCML_ELEMENT_MOVE)); QCOMPARE(respGen.getStatuses().at(7)->cmd, QString(SYNCML_ELEMENT_EXEC)); QCOMPARE(respGen.getStatuses().at(8)->cmd, QString(SYNCML_ELEMENT_ATOMIC)); QCOMPARE(respGen.getStatuses().at(9)->cmd, QString(SYNCML_ELEMENT_SEQUENCE)); QCOMPARE(respGen.getStatuses().at(9)->items.count(), 0); } void ResponseGeneratorTest::testAddStatusSync() { ResponseGenerator respGen; SyncParams params; int id = 123; params.cmdId = id; respGen.ignoreStatuses(true); respGen.addStatus(params, SUCCESS); respGen.ignoreStatuses(false); respGen.addStatus(params, SUCCESS); QCOMPARE(respGen.getStatuses().size(), 1); QCOMPARE(respGen.getStatuses().at(0)->cmdRef, id); QCOMPARE(respGen.getStatuses().at(0)->cmd, QString(SYNCML_ELEMENT_SYNC)); } void ResponseGeneratorTest::testAddStatusMap() { ResponseGenerator respGen; MapParams params; int id = 123; params.cmdId = id; respGen.ignoreStatuses(true); respGen.addStatus(params, SUCCESS); respGen.ignoreStatuses(false); respGen.addStatus(params, SUCCESS); QCOMPARE(respGen.getStatuses().size(), 1); QCOMPARE(respGen.getStatuses().at(0)->cmdRef, id); QCOMPARE(respGen.getStatuses().at(0)->cmd, QString(SYNCML_ELEMENT_MAP)); } void ResponseGeneratorTest::testAddStatusResults() { ResponseGenerator respGen; ResultsParams params; int id = 123; params.cmdId = id; respGen.ignoreStatuses(true); respGen.addStatus(params, SUCCESS); respGen.ignoreStatuses(false); respGen.addStatus(params, SUCCESS); QCOMPARE(respGen.getStatuses().size(), 1); QCOMPARE(respGen.getStatuses().at(0)->cmdRef, id); QCOMPARE(respGen.getStatuses().at(0)->cmd, QString(SYNCML_ELEMENT_RESULTS)); } void ResponseGeneratorTest::testAddStatusPut() { ResponseGenerator respGen; PutParams params; int id = 123; params.cmdId = id; respGen.ignoreStatuses(true); respGen.addStatus(params, SUCCESS); respGen.ignoreStatuses(false); respGen.addStatus(params, SUCCESS); QCOMPARE(respGen.getStatuses().size(), 1); QCOMPARE(respGen.getStatuses().at(0)->cmdRef, id); QCOMPARE(respGen.getStatuses().at(0)->cmd, QString(SYNCML_ELEMENT_PUT)); } void ResponseGeneratorTest::testNB182304() { // Regression test for NB#182304: make sure message size threshold is obeyed // when composing a message to device with very low max message size const int maxMsgSize = 3584; ResponseGenerator respGen; HeaderParams hdr; hdr.sessionID = 1; hdr.msgID = 8; hdr.targetDevice = "IMEI:356407011863641"; hdr.sourceDevice = "IMEI:004402130345691"; hdr.meta.maxMsgSize = 65535; respGen.setHeaderParams( hdr ); respGen.setRemoteMsgId(8); StatusParams* status1 = new StatusParams; status1->msgRef = 8; status1->cmdRef = 0; status1->cmd = "SyncHdr"; status1->targetRef = "IMEI:004402130345691"; status1->sourceRef = "IMEI:356407011863641"; status1->data = SUCCESS; respGen.addStatus( status1 ); StatusParams* status2 = new StatusParams; status2->msgRef = 8; status2->cmdRef = 7; status2->cmd = "Sync"; status2->targetRef = "./contacts"; status2->sourceRef = "/telecom/pb.vcf"; status2->data = SUCCESS; respGen.addStatus( status2 ); StatusParams* status3 = new StatusParams; status3->msgRef = 8; status3->cmdRef = 8; status3->cmd = "Sync"; status3->targetRef = "./calendar"; status3->sourceRef = "/telecom/cal.vcs"; status3->data = SUCCESS; respGen.addStatus( status3 ); StatusParams* status4 = new StatusParams; status4->msgRef = 8; status4->cmdRef = 9; status4->cmd = "Replace"; status4->targetRef = "13"; status4->sourceRef = "1317"; status4->data = SUCCESS; respGen.addStatus( status4 ); StatusParams* status5 = new StatusParams; status5->msgRef = 8; status5->cmdRef = 10; status5->cmd = "Replace"; status5->targetRef = "12"; status5->sourceRef = "1316"; status5->data = SUCCESS; respGen.addStatus( status5 ); StatusParams* status6 = new StatusParams; status6->msgRef = 8; status6->cmdRef = 11; status6->cmd = "Replace"; status6->targetRef = "11"; status6->sourceRef = "1315"; status6->data = SUCCESS; respGen.addStatus( status6 ); StatusParams* status7 = new StatusParams; status7->msgRef = 8; status7->cmdRef = 12; status7->cmd = "Replace"; status7->targetRef = "10"; status7->sourceRef = "1314"; status7->data = SUCCESS; respGen.addStatus( status7 ); StatusParams* status8 = new StatusParams; status8->msgRef = 8; status8->cmdRef = 13; status8->cmd = "Replace"; status8->targetRef = "2"; status8->sourceRef = "1306"; status8->data = SUCCESS; respGen.addStatus( status8 ); StatusParams* status9 = new StatusParams; status9->msgRef = 8; status9->cmdRef = 14; status9->cmd = "Add"; status9->sourceRef = "1310"; status9->data = ITEM_ADDED; respGen.addStatus( status9 ); StatusParams* status10 = new StatusParams; status10->msgRef = 8; status10->cmdRef = 15; status10->cmd = "Add"; status10->sourceRef = "1312"; status10->data = ITEM_ADDED; respGen.addStatus( status10 ); StatusParams* status11 = new StatusParams; status11->msgRef = 8; status11->cmdRef = 16; status11->cmd = "Add"; status11->sourceRef = "1304"; status11->data = ITEM_ADDED; respGen.addStatus( status11 ); StatusParams* status12 = new StatusParams; status12->msgRef = 8; status12->cmdRef = 17; status12->cmd = "Add"; status12->sourceRef = "1322"; status12->data = ITEM_ADDED; respGen.addStatus( status12 ); StatusParams* status13 = new StatusParams; status13->msgRef = 8; status13->cmdRef = 18; status13->cmd = "Add"; status13->sourceRef = "1313"; status13->data = ITEM_ADDED; respGen.addStatus( status13 ); StatusParams* status14 = new StatusParams; status14->msgRef = 8; status14->cmdRef = 19; status14->cmd = "Add"; status14->sourceRef = "1302"; status14->data = ITEM_ADDED; respGen.addStatus( status14 ); StatusParams* status15 = new StatusParams; status15->msgRef = 8; status15->cmdRef = 20; status15->cmd = "Add"; status15->sourceRef = "1321"; status15->data = ITEM_ADDED; respGen.addStatus( status15 ); StatusParams* status16 = new StatusParams; status16->msgRef = 8; status16->cmdRef = 21; status16->cmd = "Sync"; status16->targetRef = "./Notepad"; status16->sourceRef = "/telecom/note.txt"; status16->data = SUCCESS; respGen.addStatus( status16 ); StatusParams* status17 = new StatusParams; status17->msgRef = 8; status17->cmdRef = 22; status17->cmd = "Add"; status17->sourceRef = "1323"; status17->data = ITEM_ADDED; respGen.addStatus( status17 ); QList mappings; UIDMapping m1; m1.iLocalUID = "16"; m1.iRemoteUID = "1310"; mappings.append( m1 ); UIDMapping m2; m2.iLocalUID = "17"; m2.iRemoteUID = "1312"; mappings.append( m2 ); UIDMapping m3; m3.iLocalUID = "18"; m3.iRemoteUID = "1304"; mappings.append( m3 ); LocalMappingsPackage* map = new LocalMappingsPackage( "/calendar", "/telecom/cal.vcs", mappings ); respGen.addPackage( map ); SyncMLMessage* msg = respGen.generateNextMessage( maxMsgSize, SYNCML_1_1 ); QVERIFY( msg ); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( *msg, result_xml, false ) ); delete msg; msg = 0; // Add 157 bytes to account for XML header and DOCTYPE QVERIFY( result_xml.size() + 157 < maxMsgSize ); } void ResponseGeneratorTest::test208762() { FUNCTION_CALL_TRACE(lcSyncMLTrace); const int maxMsgSize = 8000; ResponseGenerator respGen; HeaderParams hdr; hdr.sessionID = 1; hdr.msgID = 8; hdr.targetDevice = "IMEI:356407011863641"; hdr.sourceDevice = "IMEI:004402130345691"; hdr.meta.maxMsgSize = 56225; respGen.setHeaderParams( hdr ); respGen.setRemoteMsgId(8); StatusParams* status1 = new StatusParams; status1->msgRef = 8; status1->cmdRef = 0; status1->cmd = "SyncHdr"; status1->targetRef = "IMEI:004402130345691"; status1->sourceRef = "IMEI:356407011863641"; status1->data = SUCCESS; respGen.addStatus( status1 ); StatusParams* status2 = new StatusParams; status2->msgRef = 8; status2->cmdRef = 7; status2->cmd = "Sync"; status2->targetRef = "./contacts"; status2->sourceRef = "/telecom/pb.vcf"; status2->data = SUCCESS; respGen.addStatus( status2 ); StatusParams* status3 = new StatusParams; status3->msgRef = 8; status3->cmdRef = 8; status3->cmd = "Sync"; status3->targetRef = "./calendar"; status3->sourceRef = "/telecom/cal.vcs"; status3->data = SUCCESS; respGen.addStatus( status3 ); StatusParams* status4 = new StatusParams; status4->msgRef = 8; status4->cmdRef = 9; status4->cmd = "Replace"; status4->targetRef = "13"; status4->sourceRef = "1317"; status4->data = SUCCESS; respGen.addStatus( status4 ); StatusParams* status5 = new StatusParams; status5->msgRef = 8; status5->cmdRef = 10; status5->cmd = "Replace"; status5->targetRef = "12"; status5->sourceRef = "1316"; status5->data = SUCCESS; respGen.addStatus( status5 ); StatusParams* status6 = new StatusParams; status6->msgRef = 8; status6->cmdRef = 11; status6->cmd = "Replace"; status6->targetRef = "11"; status6->sourceRef = "1315"; status6->data = SUCCESS; respGen.addStatus( status6 ); StatusParams* status7 = new StatusParams; status7->msgRef = 8; status7->cmdRef = 12; status7->cmd = "Replace"; status7->targetRef = "10"; status7->sourceRef = "1314"; status7->data = SUCCESS; respGen.addStatus( status7 ); StatusParams* status8 = new StatusParams; status8->msgRef = 8; status8->cmdRef = 13; status8->cmd = "Replace"; status8->targetRef = "2"; status8->sourceRef = "1306"; status8->data = SUCCESS; respGen.addStatus( status8 ); StatusParams* status9 = new StatusParams; status9->msgRef = 8; status9->cmdRef = 14; status9->cmd = "Add"; status9->sourceRef = "1310"; status9->data = ITEM_ADDED; respGen.addStatus( status9 ); StatusParams* status10 = new StatusParams; status10->msgRef = 8; status10->cmdRef = 15; status10->cmd = "Add"; status10->sourceRef = "1312"; status10->data = ITEM_ADDED; respGen.addStatus( status10 ); StatusParams* status11 = new StatusParams; status11->msgRef = 8; status11->cmdRef = 16; status11->cmd = "Add"; status11->sourceRef = "1304"; status11->data = ITEM_ADDED; respGen.addStatus( status11 ); StatusParams* status12 = new StatusParams; status12->msgRef = 8; status12->cmdRef = 17; status12->cmd = "Add"; status12->sourceRef = "1322"; status12->data = ITEM_ADDED; respGen.addStatus( status12 ); StatusParams* status13 = new StatusParams; status13->msgRef = 8; status13->cmdRef = 18; status13->cmd = "Add"; status13->sourceRef = "1313"; status13->data = ITEM_ADDED; respGen.addStatus( status13 ); StatusParams* status14 = new StatusParams; status14->msgRef = 8; status14->cmdRef = 19; status14->cmd = "Add"; status14->sourceRef = "1302"; status14->data = ITEM_ADDED; respGen.addStatus( status14 ); StatusParams* status15 = new StatusParams; status15->msgRef = 8; status15->cmdRef = 20; status15->cmd = "Add"; status15->sourceRef = "1321"; status15->data = ITEM_ADDED; respGen.addStatus( status15 ); StatusParams* status16 = new StatusParams; status16->msgRef = 8; status16->cmdRef = 21; status16->cmd = "Sync"; status16->targetRef = "./Notepad"; status16->sourceRef = "/telecom/note.txt"; status16->data = SUCCESS; respGen.addStatus( status16 ); StatusParams* status17 = new StatusParams; status17->msgRef = 8; status17->cmdRef = 22; status17->cmd = "Add"; status17->sourceRef = "1323"; status17->data = ITEM_ADDED; respGen.addStatus( status17 ); StatusParams* status18 = new StatusParams; status18->msgRef = 8; status18->cmdRef = 23; status18->cmd = "Add"; status18->sourceRef = "1324"; status18->data = ITEM_ADDED; respGen.addStatus( status18 ); StatusParams* status19 = new StatusParams; status19->msgRef = 8; status19->cmdRef = 24; status19->cmd = "Add"; status19->sourceRef = "1325"; status19->data = ITEM_ADDED; respGen.addStatus( status19 ); StatusParams* status20 = new StatusParams; status20->msgRef = 8; status20->cmdRef = 25; status20->cmd = "Add"; status20->sourceRef = "1326"; status20->data = ITEM_ADDED; respGen.addStatus( status20 ); StatusParams* status21 = new StatusParams; status21->msgRef = 8; status21->cmdRef = 26; status21->cmd = "Add"; status21->sourceRef = "1327"; status21->data = ITEM_ADDED; respGen.addStatus( status21 ); StatusParams* status22 = new StatusParams; status22->msgRef = 8; status22->cmdRef = 27; status22->cmd = "Add"; status22->sourceRef = "1328"; status22->data = ITEM_ADDED; respGen.addStatus( status22 ); StatusParams* status23 = new StatusParams; status23->msgRef = 8; status23->cmdRef = 28; status23->cmd = "Add"; status23->sourceRef = "1329"; status23->data = ITEM_ADDED; respGen.addStatus( status23 ); QList mappings; UIDMapping m1; m1.iLocalUID = "16"; m1.iRemoteUID = "1310"; mappings.append( m1 ); UIDMapping m2; m2.iLocalUID = "17"; m2.iRemoteUID = "1312"; mappings.append( m2 ); UIDMapping m3; m3.iLocalUID = "18"; m3.iRemoteUID = "1304"; mappings.append( m3 ); LocalMappingsPackage* map = new LocalMappingsPackage( "/calendar", "/telecom/cal.vcs", mappings ); respGen.addPackage( map ); SyncMLMessage* msg = respGen.generateNextMessage( maxMsgSize, SYNCML_1_1 ); QVERIFY( msg ); QtEncoder encoder; QByteArray result_xml; QVERIFY( encoder.encodeToXML( *msg, result_xml, false ) ); delete msg; msg = 0; // Add 157 bytes to account for XML header and DOCTYPE QVERIFY( result_xml.size() + 157 < maxMsgSize ); } QTEST_MAIN(DataSync::ResponseGeneratorTest) buteo-syncml-0.5.15/tests_meego/ResponseGeneratorTest.h000066400000000000000000000041401433763642500232330ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef RESPONSEGENERATORTEST_HH #define RESPONSEGENERATORTEST_HH #include namespace DataSync { class ResponseGeneratorTest: public QObject { Q_OBJECT private slots: void testAddStatusStatus(); void testAddStatusHeader(); void testAddStatusCommand1(); void testAddStatusCommand2(); void testAddStatusSync(); void testAddStatusMap(); void testAddStatusResults(); void testAddStatusPut(); void testNB182304(); void test208762(); }; } #endif buteo-syncml-0.5.15/tests_meego/ResponseGeneratorTest.pro000066400000000000000000000000351433763642500236030ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SANTest.cpp000066400000000000000000000107601433763642500205470ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SANTest.h" #include #include "TestUtils.h" #include "ServerAlertedNotification.h" using namespace DataSync; void SANTest::testParser01() { const QString serverIdentifier( "PC Suite Data Sync" ); const QString password( "" ); const QString nonce( "" ); // testParser01: Test parsing of OVI Suite SAN for Contacts sync SANHandler parser; QByteArray message; SANDS data; QVERIFY( readFile( "data/SAN01.bin", message ) ); QVERIFY( parser.checkDigest( message, serverIdentifier, password, nonce ) ); QVERIFY( parser.parseSANMessageDS( message, data ) ); QVERIFY( data.iHeader.iVersion == SYNCML_1_2 ); QVERIFY( data.iHeader.iUIMode == SANUIMODE_BACKGROUND ); QVERIFY( data.iHeader.iInitiator == SANINITIATOR_SERVER ); QVERIFY( data.iHeader.iSessionId == 0 ); QVERIFY( data.iHeader.iServerIdentifier == serverIdentifier ); QVERIFY( data.iSyncInfo.count() == 1 ); QVERIFY( data.iSyncInfo[0].iSyncType == 206 ); QVERIFY( data.iSyncInfo[0].iContentType == "" ); QVERIFY( data.iSyncInfo[0].iServerURI == "Contacts" ); } void SANTest::testParser02() { const QString serverIdentifier( "PC Suite Data Sync" ); const QString password( "" ); const QString nonce( "" ); // testParser01: Test parsing of OVI Suite SAN for Contacts and // calendar sync SANHandler parser; QByteArray message; SANDS data; QVERIFY( readFile( "data/SAN02.bin", message ) ); QVERIFY( parser.checkDigest( message, serverIdentifier, password, nonce ) ); QVERIFY( parser.parseSANMessageDS( message, data ) ); QVERIFY( data.iHeader.iVersion == SYNCML_1_2 ); QVERIFY( data.iHeader.iUIMode == SANUIMODE_BACKGROUND ); QVERIFY( data.iHeader.iInitiator == SANINITIATOR_SERVER ); QVERIFY( data.iHeader.iSessionId == 0 ); QVERIFY( data.iHeader.iServerIdentifier == serverIdentifier ); QVERIFY( data.iSyncInfo.count() == 1 ); QVERIFY( data.iSyncInfo[0].iSyncType == 206 ); QVERIFY( data.iSyncInfo[0].iContentType == "" ); QVERIFY( data.iSyncInfo[0].iServerURI == "Calendar" ); } void SANTest::testGenerator01() { // testGenerator01: Test generation of SAN package for OVI Suite for // for Contacts sync SANHandler generator; QByteArray message; SANDS data; data.iHeader.iVersion = SYNCML_1_2; data.iHeader.iUIMode = SANUIMODE_BACKGROUND; data.iHeader.iInitiator = SANINITIATOR_SERVER; data.iHeader.iSessionId = 0; data.iHeader.iServerIdentifier = "PC Suite Data Sync"; SANSyncInfo syncInfo; syncInfo.iSyncType = 206; syncInfo.iContentType == ""; syncInfo.iServerURI = "Contacts"; data.iSyncInfo.append( syncInfo ); QVERIFY( generator.generateSANMessageDS( data, "", "", message ) ); QByteArray expected; QVERIFY( readFile( "data/SAN01.bin", expected ) ); QCOMPARE( message, expected ); } QTEST_MAIN(DataSync::SANTest) buteo-syncml-0.5.15/tests_meego/SANTest.h000066400000000000000000000035501433763642500202130ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SANTEST_H #define SANTEST_H #include namespace DataSync { class SANTest : public QObject { Q_OBJECT; private slots: void testParser01(); void testParser02(); void testGenerator01(); }; } #endif // SANTEST_H buteo-syncml-0.5.15/tests_meego/SANTest.pro000066400000000000000000000000351433763642500205570ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SessionHandlerTest.cpp000066400000000000000000001302711433763642500230470ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SessionHandlerTest.h" #include #include "SessionHandler.h" #include "ClientSessionHandler.h" #include "ServerSessionHandler.h" #include "Mock.h" #include "SyncAgent.h" #include "TestUtils.h" #include "ServerAlertedNotification.h" #include "SyncAgentConfigProperties.h" #include "SyncCommonDefs.h" using namespace DataSync; QString DBFILE( "/tmp/sessionhandlertest.db" ); QString NB153701UNKNOWNDEVICE( "/" ); QString NB153701SOURCEDEVICE( "IMEI:000000000000000" ); QString NB153701TARGETDEVICE( "IMEI:000000000000001" ); QString NB153701FORCEDEVICE( "IMEI:000000000000002" ); bool SessionHandlerTest::getStorageContentFormatInfo( const QString& aURI, StorageContentFormatInfo& aInfo ) { Q_UNUSED( aURI ); MockStorage storage( "storage" ); aInfo = storage.getFormatInfo(); return true; } StoragePlugin* SessionHandlerTest::acquireStorageByURI( const QString& /*aURI*/ ) { return new MockStorage( "storage" ); } StoragePlugin* SessionHandlerTest::acquireStorageByMIME( const QString& /*aMIME*/ ) { return new MockStorage( "storage" ); } void SessionHandlerTest::releaseStorage( StoragePlugin* aStorage ) { delete aStorage; } void SessionHandlerTest::init() { QFile::remove( DBFILE ); } void SessionHandlerTest::cleanup() { QFile::remove( DBFILE ); } void SessionHandlerTest::testClientWithClientInitiated() { TestTransport transport( false ); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_BASIC, "user", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); // First message has been sent to the server. QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "Source device"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->targetDevice = SYNCML_UNKNOWN_DEVICE; hp1->respURI = "redirect URI"; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = AUTH_ACCEPTED; session_handler.handleStatusElement( sp1 ); // Fake alert. CommandParams* ap1 = new CommandParams( CommandParams::COMMAND_ALERT ); ap1->cmdId = 2; ap1->data = QString::number( SLOW_SYNC ); ItemParams item; item.source = DB; item.target = DB; item.meta.anchor.next = "something"; ap1->items.append(item); session_handler.handleAlertElement(ap1); ap1 = NULL; session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), SENDING_ITEMS); // Step through different states. session_handler.handleEndOfMessage(); SyncParams* sync = new SyncParams(); sync->cmdId = 1; sync->source = DB; sync->target = DB; session_handler.handleSyncElement( sync ); QCOMPARE(session_handler.getSyncState(), RECEIVING_ITEMS); CommandParams* get = new CommandParams( CommandParams::COMMAND_GET ); get->cmdId = 1; session_handler.handleGetElement(get); get = NULL; session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), SENDING_MAPPINGS); session_handler.handleEndOfMessage(); session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), FINALIZING); session_handler.handleEndOfMessage(); QCOMPARE(session_handler.getSyncState(), SYNC_FINISHED); } void SessionHandlerTest::testNoRespSyncElement() { TestTransport transport( false ); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_BASIC, "user", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "Source device"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->targetDevice = SYNCML_UNKNOWN_DEVICE; hp1->respURI = "redirect URI"; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = AUTH_ACCEPTED; session_handler.handleStatusElement( sp1 ); // Fake alert. CommandParams* ap1 = new CommandParams( CommandParams::COMMAND_ALERT ); ap1->cmdId = 2; ap1->data = QString::number( SLOW_SYNC ); ItemParams item; item.source = DB; item.target = DB; item.meta.anchor.next = "something"; ap1->items.append(item); session_handler.handleAlertElement(ap1); ap1 = NULL; session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), SENDING_ITEMS); // Step through different states. session_handler.handleEndOfMessage(); SyncParams* sync = new SyncParams(); sync->cmdId = 1; sync->source = DB; sync->target = DB; sync->noResp = true; session_handler.handleSyncElement( sync ); QCOMPARE(session_handler.getSyncState(), RECEIVING_ITEMS); CommandParams* get = new CommandParams( CommandParams::COMMAND_GET ); get->cmdId = 1; session_handler.handleGetElement(get); get = NULL; session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), SENDING_MAPPINGS); session_handler.handleEndOfMessage(); session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), FINALIZING); session_handler.handleEndOfMessage(); QCOMPARE(session_handler.getSyncState(), SYNC_FINISHED); } void SessionHandlerTest::testClientWithServerInitiated() { MockTransport transport("transport"); const QString DB = "contacts"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.setSyncParams( "", SYNCML_1_2, SyncMode(DIRECTION_FROM_CLIENT, INIT_SERVER) ); config.addSyncTarget( "contacts", DB ); config.setDatabaseFilePath( DBFILE ); // Start. ClientSessionHandler session_handler(&config, NULL); QList fragments; // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "Source device"; hp1->sessionID = "1"; hp1->msgID = 1; fragments.append(hp1); // Fake alert. CommandParams* ap1 = new CommandParams( CommandParams::COMMAND_ALERT ); ap1->cmdId = 1; ap1->data = QString::number( ONE_WAY_FROM_CLIENT_BY_SERVER ); ItemParams item1; item1.meta.type = "text/x-vcard"; item1.source = DB; item1.target = DB; item1.meta.anchor.next = "kala"; ap1->items.append(item1); fragments.append(ap1); session_handler.handleNotificationXML( fragments ); QVERIFY( fragments.isEmpty() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); PutParams* put = new PutParams; put->cmdId = 1; fragments.append(put); // Fake alert. ap1 = new CommandParams( CommandParams::COMMAND_ALERT ); ap1->cmdId = 1; ap1->data = QString::number( SLOW_SYNC ); ItemParams item2; item2.source = DB; item2.target = DB; item2.meta.anchor.next = "something"; ap1->items.append(item2); fragments.append(ap1); session_handler.processMessage( fragments, true ); QVERIFY( fragments.isEmpty() ); QCOMPARE(session_handler.getSyncState(), SENDING_ITEMS); session_handler.processMessage( fragments, true ); // One way sync, no RECEIVING_ITEMS state. QCOMPARE(session_handler.getSyncState(), SYNC_FINISHED); } void SessionHandlerTest::testServerWithClientInitiated() { MockTransport transport( "transport" ); SyncAgentConfig config; config.setTransport( &transport ); config.setStorageProvider( this ); config.addSyncTarget( "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setLocalDeviceName( "Local device" ); // Prepare ServerSessionHandler sessionHandler( &config, NULL ); QVERIFY(sessionHandler.prepareSync()); QCOMPARE( sessionHandler.getSyncState(), PREPARED ); // Start. QVERIFY(sessionHandler.prepareSync()); QCOMPARE( sessionHandler.getSyncState(), PREPARED ); // Fake header HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "Source device"; hp1->targetDevice = "Target device"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = DEFAULT_MAX_MESSAGESIZE; sessionHandler.handleHeaderElement( hp1 ); hp1 = NULL; // Fake alert CommandParams* ap1 = new CommandParams( CommandParams::COMMAND_ALERT ); ap1->cmdId = 1; ap1->data = QString::number( SLOW_SYNC ); ItemParams item; item.source = "calendar"; item.target = "calendar"; item.meta.anchor.next = "nextAnchor"; ap1->items.append(item); sessionHandler.handleAlertElement( ap1 ); ap1 = NULL; QCOMPARE( sessionHandler.getSyncState(), REMOTE_INIT ); sessionHandler.handleFinal(); QCOMPARE( sessionHandler.getSyncState(), LOCAL_INIT ); sessionHandler.handleEndOfMessage(); SyncParams* sync = new SyncParams(); sync->cmdId = 1; sync->source = "calendar"; sync->target = "calendar"; sessionHandler.handleSyncElement( sync ); sync = NULL; QCOMPARE( sessionHandler.getSyncState(), RECEIVING_ITEMS ); sessionHandler.handleFinal(); QCOMPARE( sessionHandler.getSyncState(), SENDING_ITEMS ); sessionHandler.handleEndOfMessage(); sessionHandler.handleFinal(); QCOMPARE( sessionHandler.getSyncState(), FINALIZING ); sessionHandler.handleEndOfMessage(); QCOMPARE( sessionHandler.getSyncState(), SYNC_FINISHED ); } void SessionHandlerTest::testClientWithServerInitiatedSAN() { MockTransport transport("transport"); const QString DB = "contacts"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "Contacts", DB ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "", SYNCML_1_2, SyncMode(DIRECTION_FROM_CLIENT, INIT_SERVER) ); QStringList mappings; mappings << "Contacts" << "text/x-vcard"; config.setExtension( SANMAPPINGSEXTENSION, QVariant( mappings ) ); QByteArray message; QVERIFY( readFile( "data/SAN01.bin", message ) ); // Start. ClientSessionHandler session_handler(&config, NULL); // Fake SAN SANHandler parser; SANDS SANdata; QVERIFY( parser.parseSANMessageDS( message, SANdata ) ); session_handler.handleNotificationPackage( SANdata ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); // Fake alert. CommandParams* ap1 = new CommandParams( CommandParams::COMMAND_ALERT ); ap1->cmdId = 2; ap1->data = QString::number( SLOW_SYNC ); ItemParams item; item.source = DB; item.target = DB; item.meta.anchor.next = "something"; ap1->items.append( item ); session_handler.handleAlertElement(ap1); ap1 = NULL; session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), SENDING_ITEMS); // Step through different states. session_handler.handleEndOfMessage(); SyncParams* sync = new SyncParams(); sync->cmdId = 1; sync->source = DB; sync->target = DB; session_handler.handleSyncElement( sync ); QCOMPARE(session_handler.getSyncState(), RECEIVING_ITEMS); CommandParams* get = new CommandParams( CommandParams::COMMAND_GET ); get->cmdId = 1; session_handler.handleGetElement(get); get = NULL; session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), SENDING_MAPPINGS); session_handler.handleEndOfMessage(); session_handler.handleFinal(); QCOMPARE(session_handler.getSyncState(), FINALIZING); session_handler.handleEndOfMessage(); QCOMPARE(session_handler.getSyncState(), SYNC_FINISHED); } void SessionHandlerTest::testClientAuthNone() { // Test that no authentication info is sent if authentication type // is AUTH_NONE, even if credenticals would be supplied TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_NONE, "user", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray data = transport.iData; QVERIFY( !data.contains( SYNCML_ELEMENT_CRED ) ); } void SessionHandlerTest::testClientAuthNoneFailed() { // Test that session is aborted if authentication type is AUTH_NONE // and we receive 401 for authentication TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setLocalDeviceName( "client" ); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_NONE, "user", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray data = transport.iData; QVERIFY( !data.contains( SYNCML_ELEMENT_CRED ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "client"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = INVALID_CRED; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE( session_handler.getSyncState(), AUTHENTICATION_FAILURE ); } void SessionHandlerTest::testClientAuthNoneChal1() { // Test that session is aborted if authentication type is AUTH_NONE // and we receive 407 for authentication with a challenge for // basic auth TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setLocalDeviceName( "client" ); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_NONE, "user", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray data = transport.iData; QVERIFY( !data.contains( SYNCML_ELEMENT_CRED ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "client"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = INVALID_CRED; sp1->hasChal = true; sp1->chal.meta.type = SYNCML_FORMAT_AUTH_BASIC; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE( session_handler.getSyncState(), AUTHENTICATION_FAILURE ); } void SessionHandlerTest::testClientAuthNoneChal2() { // Test that session is aborted if authentication type is AUTH_NONE // and we receive 407 for authentication with a challenge without // unspecified type (should default to basic auth) TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setLocalDeviceName( "client" ); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_NONE, "user", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray data = transport.iData; QVERIFY( !data.contains( SYNCML_ELEMENT_CRED ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "client"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = INVALID_CRED; sp1->hasChal = true; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE( session_handler.getSyncState(), AUTHENTICATION_FAILURE ); } void SessionHandlerTest::testClientAuthBasicNoCreds() { // Test that basic authentication fails if no credentials are // supplied TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_BASIC, "", "" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), AUTHENTICATION_FAILURE); } void SessionHandlerTest::testClientAuthBasic() { // Test that basic authentication is processed properly when // server accepts the credentials TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_BASIC, "userid", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_BASIC ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); QVERIFY( message.contains( "dXNlcmlkOnBhc3N3b3Jk" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "client"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = AUTH_ACCEPTED; session_handler.handleStatusElement( sp1 ); QVERIFY( session_handler.authentication().authedToRemote() ); } void SessionHandlerTest::testClientAuthBasicChalToMD5WithoutNonce() { // Test that session is aborted if we try to use basic auth but // get challenged with MD5 without us having a nonce TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setLocalDeviceName( "testClientAuthBasicChalToMD5WithoutNonce" ); config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "server", SYNCML_1_2, SyncMode() ); config.setAuthParams( AUTH_BASIC, "userid", "password" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_BASIC ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); QVERIFY( message.contains( "dXNlcmlkOnBhc3N3b3Jk" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "client"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = MISSING_CRED; sp1->hasChal = true; sp1->chal.meta.type = SYNCML_FORMAT_AUTH_MD5; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), AUTHENTICATION_FAILURE); } void SessionHandlerTest::testClientAuthBasicChalToMD5WithNonce() { // Test that reauthentication is attempted if basic authentication // gets rejected, but MD5 auth challenge is issued with a nonce TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setLocalDeviceName( "testClientAuthBasicChalToMD5WithNonce" ); config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "server", SYNCML_1_2, SyncMode() ); config.setAuthParams( AUTH_BASIC, "Bruce2", "OhBehave" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_BASIC ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); QVERIFY( message.contains( "QnJ1Y2UyOk9oQmVoYXZl" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "testClientAuthBasicChalToMD5WithNonce"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = MISSING_CRED; sp1->hasChal = true; sp1->chal.meta.type = SYNCML_FORMAT_AUTH_MD5; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; sp1->chal.meta.nextNonce = "Tm9uY2U="; // "Nonce" in B64 session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); session_handler.handleFinal(); session_handler.handleEndOfMessage(); QCOMPARE( session_handler.getSyncState(), LOCAL_INIT ); message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_MD5 ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); // MD5 hash of username "Bruce2", password "OhBehave", with nonce "Nonce" QVERIFY( message.contains( "Zz6EivR3yeaaENcRN6lpAQ==" ) ); } void SessionHandlerTest::testClientAuthBasicContinuous() { // Test that basic authentication information is continued to be sent // if server responds with 200. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QSKIP( "Unimplemented!" ); #else QSKIP( "Unimplemented!", SkipAll ); #endif } void SessionHandlerTest::testClientAuthMD5NoCreds() { // Test that MD5 authentication fails if no credentials are // supplied TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setAuthParams( AUTH_MD5, "", "" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), AUTHENTICATION_FAILURE); } void SessionHandlerTest::testClientAuthMD5WithoutNonce1() { // Check that if we don't have a known nonce & MD5 is to be used, // that we first try to send message by using an empty nonce. If it is rejected // without sending NextNonce back to us in MD5 challenge, session should abort TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setLocalDeviceName( "testClientAuthMD5WithoutNonce1" ); config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "server", SYNCML_1_2, SyncMode() ); config.setAuthParams( AUTH_MD5, "Bruce2", "OhBehave" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_MD5 ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); // MD5 hash of username "Bruce2", password "OhBehave", with a null nonce QVERIFY( message.contains( "lEf25jyjHbCcTbj4p/1pUw==" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "testClientAuthMD5WithoutNonce1"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = INVALID_CRED; sp1->hasChal = true; sp1->chal.meta.type = SYNCML_FORMAT_AUTH_MD5; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), AUTHENTICATION_FAILURE); } void SessionHandlerTest::testClientAuthMD5WithoutNonce2() { // Check that if we don't have a known nonce & MD5 is to be used, // that we first try to send message by using an empty nonce. If basic challenge // comes, session should abort TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setLocalDeviceName( "testClientAuthMD5WithoutNonce2" ); config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "server", SYNCML_1_2, SyncMode() ); config.setAuthParams( AUTH_MD5, "Bruce2", "OhBehave" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_MD5 ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); // MD5 hash of username "Bruce2", password "OhBehave", with a null nonce QVERIFY( message.contains( "lEf25jyjHbCcTbj4p/1pUw==" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "testClientAuthMD5WithoutNonce2"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = INVALID_CRED; sp1->hasChal = true; sp1->chal.meta.type = SYNCML_FORMAT_AUTH_BASIC; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), AUTHENTICATION_FAILURE); } void SessionHandlerTest::testClientAuthMD5WithoutNonce3() { // Check that if we don't have a known nonce & MD5 is to be used, // that we first try to send message by using an empty nonce. If MD5 challenge // comes with a nonce, continue the session TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setLocalDeviceName( "testClientAuthMD5WithoutNonce3" ); config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "server", SYNCML_1_2, SyncMode() ); config.setAuthParams( AUTH_MD5, "Bruce2", "OhBehave" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_MD5 ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); // MD5 hash of username "Bruce2", password "OhBehave", with a null nonce QVERIFY( message.contains( "lEf25jyjHbCcTbj4p/1pUw==" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "testClientAuthMD5WithoutNonce3"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = INVALID_CRED; sp1->hasChal = true; sp1->chal.meta.type = SYNCML_FORMAT_AUTH_MD5; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; sp1->chal.meta.nextNonce = "Tm9uY2U="; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); session_handler.handleFinal(); session_handler.handleEndOfMessage(); QCOMPARE( session_handler.getSyncState(), LOCAL_INIT ); message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); QVERIFY( message.contains( SYNCML_FORMAT_AUTH_MD5 ) ); QVERIFY( message.contains( SYNCML_FORMAT_ENCODING_B64 ) ); // MD5 hash of username "Bruce2", password "OhBehave", with nonce "Nonce" QVERIFY( message.contains( "Zz6EivR3yeaaENcRN6lpAQ==" ) ); } void SessionHandlerTest::testClientAuthMD5WithNonce() { // Test that MD5 authentication is processed properly when // server accepts the credentials TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setLocalDeviceName( "testClientAuthMD5WithNonce" ); config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "server", SYNCML_1_2, SyncMode() ); config.setAuthParams( AUTH_MD5, "Bruce2", "OhBehave", "Nonce" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); // MD5 hash of username "Bruce2", password "OhBehave", with nonce "Nonce" QVERIFY( message.contains( "Zz6EivR3yeaaENcRN6lpAQ==" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "testClientAuthMD5WithNonce"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = SUCCESS; session_handler.handleStatusElement( sp1 ); QVERIFY( session_handler.authentication().authedToRemote() ); QCOMPARE( session_handler.getSyncState(), LOCAL_INIT ); } void SessionHandlerTest::testClientAuthMD5ChalToBasic() { // Test that session is aborted if we want to use MD5 authentication and // server responds with challenge for basic TestTransport transport(false); const QString DB = "calendar"; SyncAgentConfig config; config.setLocalDeviceName( "testClientAuthMD5ChalToBasic" ); config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "calendar", "calendar" ); config.setDatabaseFilePath( DBFILE ); config.setSyncParams( "server", SYNCML_1_2, SyncMode() ); config.setAuthParams( AUTH_MD5, "Bruce2", "OhBehave", "Nonce" ); // Start. ClientSessionHandler session_handler(&config, NULL); session_handler.initiateSync(); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE(session_handler.getSyncState(), LOCAL_INIT); QByteArray message = transport.iData; QVERIFY( message.contains( SYNCML_ELEMENT_CRED ) ); // MD5 hash of username "Bruce2", password "OhBehave", with nonce "Nonce" QVERIFY( message.contains( "Zz6EivR3yeaaENcRN6lpAQ==" ) ); // Fake header. HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = "server"; hp1->targetDevice = "testClientAuthMD5ChalToBasic"; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = 30000; session_handler.handleHeaderElement(hp1); hp1 = NULL; // Fake status StatusParams* sp1 = new StatusParams(); sp1->cmdId = 1; sp1->msgRef = 1; sp1->cmdRef = 0; sp1->cmd = SYNCML_ELEMENT_SYNCHDR; sp1->data = INVALID_CRED; sp1->hasChal = true; sp1->chal.meta.type = SYNCML_FORMAT_AUTH_BASIC; sp1->chal.meta.format = SYNCML_FORMAT_ENCODING_B64; session_handler.handleStatusElement( sp1 ); QVERIFY( !session_handler.authentication().authedToRemote() ); QCOMPARE( session_handler.getSyncState(), AUTHENTICATION_FAILURE ); } void SessionHandlerTest::testClientAuthMD5Continuous() { #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QSKIP( "Unimplemented!" ); #else QSKIP( "Unimplemented!", SkipAll ); #endif } void SessionHandlerTest::regression_NB153701_01() { // regression_NB153701_01: // Test handling of source device when receiving server initiated // sync message with unknown source device and local device name is not set MockTransport transport( "transport" ); SyncAgentConfig config; DeviceInfo deviceInfo; config.setTransport( &transport ); config.setStorageProvider( this ); config.setDatabaseFilePath( DBFILE ); deviceInfo.setDeviceID( NB153701SOURCEDEVICE ); config.setDeviceInfo(deviceInfo); // Prepare ClientSessionHandler sessionHandler( &config, NULL ); QList fragments; // Receive header HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = NB153701TARGETDEVICE; hp1->targetDevice = NB153701UNKNOWNDEVICE; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = DEFAULT_MAX_MESSAGESIZE; fragments.append(hp1); sessionHandler.handleNotificationXML(fragments); QVERIFY(fragments.isEmpty()); QCOMPARE( sessionHandler.getDevInfHandler().getLocalDeviceInfo().getDeviceID(), NB153701SOURCEDEVICE ); QCOMPARE( sessionHandler.params().localDeviceName(), NB153701SOURCEDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().sourceDevice, NB153701SOURCEDEVICE ); QCOMPARE( sessionHandler.params().remoteDeviceName(), NB153701TARGETDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().targetDevice, NB153701TARGETDEVICE ); } void SessionHandlerTest::regression_NB153701_02() { // regression_NB153701_02: // Test handling of source device when receiving server initiated // sync message with unknown source device and local device name is set MockTransport transport( "transport" ); SyncAgentConfig config; DeviceInfo deviceInfo; config.setTransport( &transport ); config.setStorageProvider( this ); config.setDatabaseFilePath( DBFILE ); deviceInfo.setDeviceID( NB153701SOURCEDEVICE ); config.setDeviceInfo(deviceInfo); config.setLocalDeviceName( NB153701FORCEDEVICE ); // Prepare ClientSessionHandler sessionHandler( &config, NULL ); QList fragments; // Receive header HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = NB153701TARGETDEVICE; hp1->targetDevice = NB153701UNKNOWNDEVICE; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = DEFAULT_MAX_MESSAGESIZE; fragments.append(hp1); sessionHandler.handleNotificationXML(fragments); QVERIFY(fragments.isEmpty()); QCOMPARE( sessionHandler.getDevInfHandler().getLocalDeviceInfo().getDeviceID(), NB153701SOURCEDEVICE ); QCOMPARE( sessionHandler.params().localDeviceName(), NB153701FORCEDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().sourceDevice, NB153701FORCEDEVICE ); QCOMPARE( sessionHandler.params().remoteDeviceName(), NB153701TARGETDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().targetDevice, NB153701TARGETDEVICE ); } void SessionHandlerTest::regression_NB153701_03() { // regression_NB153701_03: // Test handling of device id when receiving server initiated // sync message that includes a source device MockTransport transport( "transport" ); SyncAgentConfig config; config.setTransport( &transport ); config.setStorageProvider( this ); config.setDatabaseFilePath( DBFILE ); config.setLocalDeviceName( NB153701SOURCEDEVICE ); // Prepare ClientSessionHandler sessionHandler( &config, NULL ); QList fragments; // Receive header HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_2; hp1->sourceDevice = NB153701TARGETDEVICE; hp1->targetDevice = NB153701FORCEDEVICE; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = DEFAULT_MAX_MESSAGESIZE; fragments.append(hp1); sessionHandler.handleNotificationXML(fragments); QVERIFY(fragments.isEmpty()); QVERIFY( sessionHandler.getDevInfHandler().getLocalDeviceInfo().getDeviceID().isEmpty() ); QCOMPARE( sessionHandler.params().localDeviceName(), NB153701FORCEDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().sourceDevice, NB153701FORCEDEVICE ); QCOMPARE( sessionHandler.params().remoteDeviceName(), NB153701TARGETDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().targetDevice, NB153701TARGETDEVICE ); } void SessionHandlerTest::regression_NB153701_04() { // regression_NB153701_04: // Test handling of target device after sent server initiated // sync message MockTransport transport( "transport" ); SyncAgentConfig config; config.setTransport( &transport ); config.setStorageProvider( this ); config.setDatabaseFilePath( DBFILE ); config.setLocalDeviceName( NB153701SOURCEDEVICE ); config.setSyncParams( "", SYNCML_1_1, SyncMode(DIRECTION_TWO_WAY, INIT_SERVER, TYPE_FAST) ); config.addSyncTarget( "./calendar", "./calendar" ); ClientSessionHandler sessionHandler( &config, NULL ); sessionHandler.initiateSync(); QList fragments; // Receive header HeaderParams* hp1 = new HeaderParams(); hp1->verDTD = SYNCML_DTD_VERSION_1_1; hp1->sourceDevice = NB153701TARGETDEVICE; hp1->targetDevice = NB153701FORCEDEVICE; hp1->sessionID = "1"; hp1->msgID = 1; hp1->meta.maxMsgSize = DEFAULT_MAX_MESSAGESIZE; fragments.append(hp1); sessionHandler.handleNotificationXML(fragments); QVERIFY(fragments.isEmpty()); QVERIFY( sessionHandler.getDevInfHandler().getLocalDeviceInfo().getDeviceID().isEmpty() ); QCOMPARE( sessionHandler.params().localDeviceName(), NB153701FORCEDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().sourceDevice, NB153701FORCEDEVICE ); QCOMPARE( sessionHandler.params().remoteDeviceName(), NB153701TARGETDEVICE ); QCOMPARE( sessionHandler.getResponseGenerator().getHeaderParams().targetDevice, NB153701TARGETDEVICE ); } QTEST_MAIN(SessionHandlerTest) buteo-syncml-0.5.15/tests_meego/SessionHandlerTest.h000066400000000000000000000064041433763642500225140ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SESSIONHANDLERTEST_H #define SESSIONHANDLERTEST_H #include #include "StorageProvider.h" class SessionHandlerTest : public QObject, public DataSync::StorageProvider { Q_OBJECT public: virtual bool getStorageContentFormatInfo( const QString& aURI, DataSync::StorageContentFormatInfo& aInfo ); virtual DataSync::StoragePlugin* acquireStorageByURI( const QString& aURI ); virtual DataSync::StoragePlugin* acquireStorageByMIME( const QString& aMIME ); virtual void releaseStorage( DataSync::StoragePlugin* aStorage ); private slots: void init(); void cleanup(); void testClientWithClientInitiated(); void testClientWithServerInitiated(); void testServerWithClientInitiated(); void testClientWithServerInitiatedSAN(); void testClientAuthNone(); void testClientAuthNoneFailed(); void testClientAuthNoneChal1(); void testClientAuthNoneChal2(); void testClientAuthBasicNoCreds(); void testClientAuthBasic(); void testClientAuthBasicChalToMD5WithoutNonce(); void testClientAuthBasicChalToMD5WithNonce(); void testClientAuthBasicContinuous(); void testClientAuthMD5NoCreds(); void testClientAuthMD5WithoutNonce1(); void testClientAuthMD5WithoutNonce2(); void testClientAuthMD5WithoutNonce3(); void testClientAuthMD5WithNonce(); void testClientAuthMD5ChalToBasic(); void testClientAuthMD5Continuous(); void regression_NB153701_01(); void regression_NB153701_02(); void regression_NB153701_03(); void regression_NB153701_04(); void testNoRespSyncElement(); private: }; #endif // SESSIONHANDLERTEST_H buteo-syncml-0.5.15/tests_meego/SessionHandlerTest.pro000066400000000000000000000000351433763642500230570ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/StorageHandlerTest.cpp000066400000000000000000000261401433763642500230270ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "StorageHandlerTest.h" #include "Mock.h" #include "ConflictResolver.h" #include "SyncMLLogging.h" using namespace DataSync; void StorageHandlerTest::testAddItem() { MockStorage storage( "id" ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString parent(""); QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); LocalChanges changes; ConflictResolver resolver( changes, PREFER_LOCAL_CHANGES ); QVERIFY( iStorageHandler.addItem( id, storage, QString(), parent, type, format, version, data ) ); QMap commits = iStorageHandler.commitAddedItems( storage, &resolver ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iStatus == COMMIT_ADDED ); QVERIFY( results[0].iConflict == CONFLICT_NO_CONFLICT ); } void StorageHandlerTest::testReplaceItem() { MockStorage storage( "id" ); LocalChanges changes; ConflictResolver resolver( changes, PREFER_LOCAL_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key( "fookey" ); QString parent( "" ); QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); QVERIFY( iStorageHandler.replaceItem( id, storage, key, parent, type, format, version, data ) ); QMap commits = iStorageHandler.commitReplacedItems( storage, &resolver ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iItemKey == key ); QVERIFY( results[0].iStatus == COMMIT_REPLACED ); QVERIFY( results[0].iConflict == CONFLICT_NO_CONFLICT ); } void StorageHandlerTest::testDeleteItem() { MockStorage storage( "id" ); LocalChanges changes; ConflictResolver resolver( changes, PREFER_LOCAL_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key = "fookey"; QVERIFY( iStorageHandler.deleteItem( id, key ) ); QMap commits = iStorageHandler.commitDeletedItems( storage, &resolver ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iItemKey == key ); QVERIFY( results[0].iStatus == COMMIT_DELETED ); QVERIFY( results[0].iConflict == CONFLICT_NO_CONFLICT ); } void StorageHandlerTest::testLargeObjectReplace() { MockStorage storage( "id" ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString parent = ""; QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "ab" ); QString key = "fookey"; qint64 size = 4; QVERIFY( iStorageHandler.startLargeObjectReplace( storage, key, parent, type, format, version, size ) ); QVERIFY( iStorageHandler.buildingLargeObject() ); QVERIFY( iStorageHandler.matchesLargeObject( key ) ); QVERIFY( iStorageHandler.appendLargeObjectData( data ) ); QVERIFY( iStorageHandler.appendLargeObjectData( data ) ); QVERIFY( iStorageHandler.finishLargeObject( id ) ); QMap commits = iStorageHandler.commitReplacedItems( storage, NULL ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iItemKey == key ); QVERIFY( results[0].iStatus == COMMIT_REPLACED ); QVERIFY( results[0].iConflict == CONFLICT_NO_CONFLICT ); } void StorageHandlerTest::regression_NB153991_01() { // regression_NB153991_01: // Test that Replace with an empty local key is processed as an Add MockStorage storage( "id" ); LocalChanges changes; ConflictResolver resolver( changes, PREFER_LOCAL_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key = ""; QString parent = ""; QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); QVERIFY( iStorageHandler.replaceItem( id, storage, key, parent, type, format, version, data ) ); QMap commits = iStorageHandler.commitReplacedItems( storage, &resolver ); QVERIFY( commits.count() == 0 ); commits = iStorageHandler.commitAddedItems( storage, &resolver ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iStatus == COMMIT_ADDED ); QVERIFY( results[0].iConflict == CONFLICT_NO_CONFLICT ); } void StorageHandlerTest::regression_NB203771_01() { MockStorage storage( "id" ); LocalChanges changes; changes.modified.append("key1"); ConflictResolver resolver( changes, PREFER_LOCAL_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key = "key1"; QString parent = ""; QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); QVERIFY( iStorageHandler.replaceItem( id, storage, key, parent, type, format, version, data ) ); QMap commits = iStorageHandler.commitReplacedItems( storage, &resolver ); QVERIFY( commits.count() == 1 ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iStatus == COMMIT_INIT_REPLACE ); QVERIFY( results[0].iConflict == CONFLICT_LOCAL_WIN ); } void StorageHandlerTest::regression_NB203771_02() { MockStorage storage( "id" ); LocalChanges changes; changes.modified.append("key1"); ConflictResolver resolver( changes, PREFER_REMOTE_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key = "key1"; QString parent = ""; QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); QVERIFY( iStorageHandler.addItem( id, storage, key, parent, type, format, version, data ) ); QMap commits = iStorageHandler.commitAddedItems( storage, &resolver ); QVERIFY( commits.count() == 1 ); QList results = commits.values(); QVERIFY( results.count() == 1 ); qDebug() << results[0].iStatus; QVERIFY( results[0].iConflict == CONFLICT_REMOTE_WIN ); QVERIFY( results[0].iStatus == COMMIT_ADDED ); QVERIFY( changes.modified.size() == 0 ); //local change removed } void StorageHandlerTest::regression_NB203771_03() { MockStorage storage( "id" ); LocalChanges changes; changes.removed.append("key1"); ConflictResolver resolver( changes, PREFER_REMOTE_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key = ""; QString parent = ""; QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); QVERIFY( iStorageHandler.replaceItem( id, storage, key, parent, type, format, version, data ) ); // should be in add list SyncItem *item = iStorageHandler.iAddList.value(id); QVERIFY(item); item->setKey("key1"); QMap commits = iStorageHandler.commitAddedItems( storage, &resolver ); QVERIFY( commits.count() == 1 ); QList results = commits.values(); QVERIFY( results.count() == 1 ); qDebug() << results[0].iStatus; QVERIFY( results[0].iConflict == CONFLICT_REMOTE_WIN ); QVERIFY( results[0].iStatus == COMMIT_ADDED ); QVERIFY( changes.removed.size() == 0 ); //local change removed } void StorageHandlerTest::regression_NB203771_04() { MockStorage storage( "id" ); LocalChanges changes; changes.removed.append("key1"); ConflictResolver resolver( changes, PREFER_LOCAL_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key = ""; QString parent = ""; QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); QVERIFY( iStorageHandler.replaceItem( id, storage, key, parent, type, format, version, data ) ); // should be in add list SyncItem *item = iStorageHandler.iAddList.value(id); QVERIFY(item); item->setKey("key1"); QMap commits = iStorageHandler.commitAddedItems( storage, &resolver ); QVERIFY( commits.count() == 1 ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iConflict == CONFLICT_LOCAL_WIN ); QVERIFY( results[0].iStatus == COMMIT_INIT_ADD ); QVERIFY( changes.removed.size() == 1 ); } void StorageHandlerTest::regression_NB203771_05() { MockStorage storage( "id" ); LocalChanges changes; changes.removed.append("key11"); ConflictResolver resolver( changes, PREFER_LOCAL_CHANGES ); ItemId id; id.iCmdId = 1; id.iItemIndex = 0; QString key = ""; QString parent = ""; QString type( "text/x-vcard" ); QString format(""); QString version(""); QString data( "fasdaagadtadg" ); QVERIFY( iStorageHandler.replaceItem( id, storage, key, parent, type, format, version, data ) ); // should be in add list SyncItem *item = iStorageHandler.iAddList.value(id); QVERIFY(item); item->setKey("key1"); QMap commits = iStorageHandler.commitAddedItems( storage, &resolver ); QVERIFY( commits.count() == 1 ); QList results = commits.values(); QVERIFY( results.count() == 1 ); QVERIFY( results[0].iConflict == CONFLICT_NO_CONFLICT ); QVERIFY( results[0].iStatus == COMMIT_ADDED ); QVERIFY( changes.removed.size() == 1 ); } QTEST_MAIN(DataSync::StorageHandlerTest) buteo-syncml-0.5.15/tests_meego/StorageHandlerTest.h000066400000000000000000000042731433763642500224770ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef STORAGEHANDLERTEST_H #define STORAGEHANDLERTEST_H #include #include "StorageHandler.h" namespace DataSync { class StorageHandlerTest : public QObject { Q_OBJECT private slots: void testAddItem(); void testReplaceItem(); void testDeleteItem(); void testLargeObjectReplace(); void regression_NB153991_01(); void regression_NB203771_01(); void regression_NB203771_02(); void regression_NB203771_03(); void regression_NB203771_04(); void regression_NB203771_05(); private: StorageHandler iStorageHandler; }; } #endif buteo-syncml-0.5.15/tests_meego/StorageHandlerTest.pro000066400000000000000000000000351433763642500230400ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SyncAgentConfigTest.cpp000066400000000000000000000100051433763642500231370ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncAgentConfigTest.h" #include "SyncAgentConfig.h" #include "SyncAgentConfigProperties.h" using namespace DataSync; void SyncAgentConfigTest::testConfParsing() { const QString xsdFile( "data/testconf.xsd" ); const QString configFile( "data/testconf1.xml" ); const QString dbFile( "/fooland/syncml.db" ); const QString localDeviceName( "FoolandDevice" ); const QString proxyHost( "http://www.google.com" ); const QString inq( "InqMe" ); const QString ack( "AckMe" ); SyncAgentConfig config; QVERIFY( config.fromFile( configFile, xsdFile ) ); QCOMPARE( config.getDatabaseFilePath(), dbFile ); QCOMPARE( config.getLocalDeviceName(), localDeviceName ); QCOMPARE( config.getAgentProperty( MAXMESSAGESIZEPROP ).toInt(), 32768 ); QCOMPARE( config.getAgentProperty( MAXCHANGESPERMESSAGEPROP ).toInt(), 10 ); QCOMPARE( static_cast( config.getAgentProperty( CONFLICTRESOLUTIONPOLICYPROP ).toInt() ), PREFER_REMOTE_CHANGES ); QCOMPARE( config.getAgentProperty( FASTMAPSSENDPROP ).toInt(), 1 ); QCOMPARE( config.getTransportProperty( OBEXMTUBTPROP ).toInt(), 1024 ); QCOMPARE( config.getTransportProperty( OBEXMTUUSBPROP ).toInt(), 2048 ); QCOMPARE( config.getTransportProperty( OBEXMTUOTHERPROP ).toInt(), 4096 ); QCOMPARE( config.getTransportProperty( OBEXTIMEOUTPROP ).toInt(), 120 ); QCOMPARE( config.getTransportProperty( HTTPNUMBEROFRESENDATTEMPTSPROP ).toInt(), 3 ); QCOMPARE( config.getTransportProperty( HTTPPROXYHOSTPROP ), proxyHost ); QCOMPARE( config.getTransportProperty( HTTPPROXYPORTPROP ).toInt(), 666 ); QVERIFY( config.extensionEnabled( EMITAGSEXTENSION ) ); QVariant data = config.getExtensionData( EMITAGSEXTENSION ); QVERIFY( data.isValid() ); QStringList tags = data.toStringList(); QCOMPARE( tags.count(), 2 ); QCOMPARE( tags[0], inq ); QCOMPARE( tags[1], ack ); QVERIFY( config.extensionEnabled( SYNCWITHOUTINITPHASEEXTENSION ) ); data = config.getExtensionData( SANMAPPINGSEXTENSION ); QVERIFY( data.isValid() ); QStringList mappings = data.toStringList(); QCOMPARE( mappings.count(), 4 ); QCOMPARE( mappings[0], QString( "Map1" ) ); QCOMPARE( mappings[1], QString( "text/foo1" ) ); QCOMPARE( mappings[2], QString( "Map2" ) ); QCOMPARE( mappings[3], QString( "text/foo2" ) ); } QTEST_MAIN(DataSync::SyncAgentConfigTest) buteo-syncml-0.5.15/tests_meego/SyncAgentConfigTest.h000066400000000000000000000035061433763642500226140ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCAGENTCONFIGTEST_H #define SYNCAGENTCONFIGTEST_H #include namespace DataSync { class SyncAgentConfigTest : public QObject { Q_OBJECT private slots: void testConfParsing(); }; } #endif buteo-syncml-0.5.15/tests_meego/SyncAgentConfigTest.pro000066400000000000000000000000351433763642500231570ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SyncAgentTest.cpp000066400000000000000000000145411433763642500220220ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncAgent.h" #include "SyncAgentConfig.h" #include "SyncAgentTest.h" #include "Mock.h" #include "StoragePlugin.h" #include using namespace DataSync; bool SyncAgentTest::getStorageContentFormatInfo( const QString& aURI, StorageContentFormatInfo& aInfo ) { Q_UNUSED( aURI ); MockStorage temp( "storage" ); aInfo = temp.getFormatInfo(); return true; } StoragePlugin* SyncAgentTest::acquireStorageByURI( const QString& /*aURI*/ ) { return new MockStorage( "storage" ); } StoragePlugin* SyncAgentTest::acquireStorageByMIME( const QString& /*aMIME*/ ) { return new MockStorage( "storage" ); } void SyncAgentTest::releaseStorage( StoragePlugin* aStorage ) { delete aStorage; } void SyncAgentTest::testSync() { createSyncAgent_t createSyncAgent = (createSyncAgent_t) QLibrary::resolve( #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) "buteosyncml", "0", "createSyncAgent"); #else "buteosyncml5", "0", "createSyncAgent"); #endif QVERIFY(NULL != createSyncAgent); SyncAgent* agent = createSyncAgent(NULL); QVERIFY(NULL != agent); MockTransport transport("transport"); const QString DB = "target"; const QString ERROR = "no error"; const QString MIMETYPE = "text/x-vcard"; // Create signal spies. QSignalSpy status_spy(agent, SIGNAL(stateChanged(DataSync::SyncState))); QSignalSpy processed_spy(agent, SIGNAL( itemProcessed( DataSync::ModificationType, DataSync::ModifiedDatabase, QString ,QString, int ) )); // Initialize SyncAgent in client mode. SyncAgentConfig config; config.setTransport(&transport); config.setStorageProvider( this ); config.addSyncTarget( "storage", DB ); // Try operations when not prepared. QCOMPARE(agent->pauseSync(), false); QCOMPARE(agent->abort(), false); // Test changing status. status_spy.clear(); agent->receiveStateChanged( PREPARED ); QCOMPARE(status_spy.count(), 1); QCOMPARE(qvariant_cast(status_spy.at(0).at(0)), PREPARED); // Start. QCOMPARE(agent->startSync(config), true); QVERIFY(agent->isSyncing()); agent->receiveStateChanged( LOCAL_INIT ); QCOMPARE(agent->startSync(config), false); // Processed. agent->receiveItemProcessed( MOD_ITEM_ADDED, MOD_LOCAL_DATABASE, DB , MIMETYPE, 1 ); const SyncResults& results = agent->getResults(); const QMap* dbResults_p = results.getDatabaseResults(); const QMap& dbResults = *dbResults_p; QCOMPARE( dbResults.count(), 1 ); QCOMPARE( dbResults[DB].iLocalItemsAdded, 1 ); QCOMPARE( dbResults[DB].iLocalItemsModified, 0 ); QCOMPARE( dbResults[DB].iLocalItemsDeleted, 0 ); QCOMPARE( dbResults[DB].iRemoteItemsAdded, 0 ); QCOMPARE( dbResults[DB].iRemoteItemsModified, 0 ); QCOMPARE( dbResults[DB].iRemoteItemsDeleted, 0 ); QCOMPARE(processed_spy.count(), 1); QCOMPARE(qvariant_cast(processed_spy.at(0).at(0)), MOD_ITEM_ADDED ); QCOMPARE(qvariant_cast(processed_spy.at(0).at(1)), MOD_LOCAL_DATABASE ); QCOMPARE(processed_spy.at(0).at(2).toString(), DB); // Pause, abort, resume when finished. agent->receiveSyncFinished( QString("IMEI"),SYNC_FINISHED, ERROR ); QCOMPARE(agent->isSyncing(), false); QCOMPARE(agent->abort(), false); QCOMPARE(agent->pauseSync(), false); QCOMPARE(agent->resumeSync(), false); // Test in server mode. config.setSyncParams(config.getRemoteDeviceName(), config.getProtocolVersion(), SyncMode(DIRECTION_FROM_SERVER, INIT_SERVER)); QCOMPARE(agent->startSync(config), true); QCOMPARE(agent->pauseSync(), true); QCOMPARE(agent->abort(), true); // Listening agent->cleanSession(); QCOMPARE(agent->isListening(), false); QCOMPARE(agent->listen(config), true); QCOMPARE(agent->isListening(), true); agent->listenEvent(); QCOMPARE(agent->isListening(), false); agent->cleanSession(); QCOMPARE(agent->listen(config), true); agent->listenError(ABORTED, "Testing error"); QCOMPARE(agent->isListening(), false); agent->cleanSession(); QCOMPARE(agent->listen(config), true); QCOMPARE(agent->abort(), true); QCOMPARE(agent->isListening(), false); QCOMPARE(agent->cleanUp(&config), false); destroySyncAgent_t* destroySyncAgent = #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) (destroySyncAgent_t*) QLibrary::resolve("buteosyncml", #else (destroySyncAgent_t*) QLibrary::resolve("buteosyncml5", #endif "0", "destroySyncAgent"); QVERIFY(NULL != destroySyncAgent); destroySyncAgent(agent); agent = NULL; } QTEST_MAIN(SyncAgentTest) buteo-syncml-0.5.15/tests_meego/SyncAgentTest.h000066400000000000000000000043511433763642500214650ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCAGENTTEST_H #define SYNCAGENTTEST_H #include #include "StorageProvider.h" class SyncAgentTest: public QObject, public DataSync::StorageProvider { Q_OBJECT public: virtual bool getStorageContentFormatInfo( const QString& aURI, DataSync::StorageContentFormatInfo& aInfo ); virtual DataSync::StoragePlugin* acquireStorageByURI( const QString& aURI ); virtual DataSync::StoragePlugin* acquireStorageByMIME( const QString& aMIME ); virtual void releaseStorage( DataSync::StoragePlugin* aStorage ); private slots: void testSync(); }; #endif buteo-syncml-0.5.15/tests_meego/SyncAgentTest.pro000066400000000000000000000000351433763642500220310ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SyncItemPrefetcherTest.cpp000066400000000000000000000251561433763642500236760ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncItemPrefetcherTest.h" #include #include "SyncItemPrefetcher.h" #include "Mock.h" #include "SyncMLLogging.h" PrefetchStorage::PrefetchStorage( const QList& aItemIds ) : iItemIds( aItemIds ), iForceSyncItems( false ) { ContentFormat format; format.iType = "text/foo"; format.iVersion = "1.0"; iFormats.setPreferredRx( format ); iFormats.setPreferredTx( format ); iFormats.rx().append( format ); iFormats.tx().append( format ); } PrefetchStorage::~PrefetchStorage() { qDeleteAll( iSyncItems ); iSyncItems.clear(); } void PrefetchStorage::forceSyncItems( const QList aSyncItems ) { qDeleteAll( iSyncItems ); iSyncItems.clear(); iForceSyncItems = true; iSyncItems = aSyncItems; } const QString& PrefetchStorage::getSourceURI() const { return iSourceURI; } const StorageContentFormatInfo& PrefetchStorage::getFormatInfo() const { return iFormats; } qint64 PrefetchStorage::getMaxObjSize() const { return 0; } QByteArray PrefetchStorage::getPluginCTCaps( ProtocolVersion aVersion ) const { Q_UNUSED( aVersion ); return QByteArray(); } QByteArray PrefetchStorage::getPluginExts() const { return QByteArray(); } bool PrefetchStorage::getAll( QList& aKeys ) { Q_UNUSED( aKeys ); return true; } bool PrefetchStorage::getModifications( QList& aNewKeys, QList& aReplacedKeys, QList& aDeletedKeys, const QDateTime& aTimeStamp ) { Q_UNUSED( aNewKeys ); Q_UNUSED( aReplacedKeys ); Q_UNUSED( aDeletedKeys ); Q_UNUSED( aTimeStamp ); return true; } SyncItem* PrefetchStorage::newItem() { return NULL; } SyncItem* PrefetchStorage::getSyncItem( const SyncItemKey& aKey ) { Q_UNUSED( aKey ); return NULL; } QList PrefetchStorage::getSyncItems( const QList& aKeyList ) { if( iForceSyncItems ) { QList items = iSyncItems; iSyncItems.clear(); return items; } else { QList items; for( int i = 0; i < aKeyList.count(); ++i ) { MockSyncItem* item = NULL; if( iItemIds.contains( aKeyList[i] ) ) { item = new MockSyncItem( aKeyList[i] ); } items.append( item ); } return items; } } QList PrefetchStorage::addItems( const QList& aItems ) { Q_UNUSED( aItems ); QList status; return status; } QList PrefetchStorage::replaceItems( const QList& aItems ) { Q_UNUSED( aItems ); QList status; return status; } QList PrefetchStorage::deleteItems( const QList& aKeys ) { Q_UNUSED( aKeys ); QList status; return status; } void SyncItemPrefetcherTest::testNormalNoIdle() { // Test item prefetcher using normal sequence without idle prefetching QList items; items.append( "1" ); items.append( "2" ); items.append( "3" ); items.append( "4" ); items.append( "5" ); const int batchSizeHint = 2; PrefetchStorage storage( items ); SyncItemPrefetcher prefetcher( items, storage, batchSizeHint ); QCOMPARE( prefetcher.iBatchSizeHint, batchSizeHint ); QCOMPARE( &prefetcher.iStoragePlugin, &storage ); QCOMPARE( prefetcher.iItemIdList, items ); QVERIFY( prefetcher.iFetchedItems.isEmpty() ); SyncItem* item = prefetcher.getItem( items.at(0) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), batchSizeHint - 1 ); delete item; item = prefetcher.getItem( items.at(1) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), 0 ); delete item; item = prefetcher.getItem( items.at(2) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - 2 - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), batchSizeHint - 1 ); delete item; item = prefetcher.getItem( items.at(3) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - 2 - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), 0 ); delete item; item = prefetcher.getItem( items.at(4) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), 0 ); QCOMPARE( prefetcher.iFetchedItems.count(), 0 ); delete item; } void SyncItemPrefetcherTest::testNormalIdle() { // Test item prefetcher using normal sequence with idle prefetching QList items; items.append( "1" ); items.append( "2" ); items.append( "3" ); items.append( "4" ); items.append( "5" ); const int batchSizeHint = 2; PrefetchStorage storage( items ); SyncItemPrefetcher prefetcher( items, storage, batchSizeHint ); QCOMPARE( prefetcher.iBatchSizeHint, batchSizeHint ); QCOMPARE( &prefetcher.iStoragePlugin, &storage ); QCOMPARE( prefetcher.iItemIdList, items ); QVERIFY( prefetcher.iFetchedItems.isEmpty() ); // Items going to "first message" SyncItem* item = prefetcher.getItem( items.at(0) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), batchSizeHint - 1 ); delete item; item = prefetcher.getItem( items.at(1) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), 0 ); delete item; prefetcher.prefetch(); // Item going to "second message" item = prefetcher.getItem( items.at(2) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - 2 - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), batchSizeHint - 1 ); delete item; prefetcher.prefetch(); // Item going to "third message" item = prefetcher.getItem( items.at(3) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), items.count() - 3 - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), 1 ); delete item; prefetcher.prefetch(); // Item going to "fourth message" item = prefetcher.getItem( items.at(4) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), 0 ); QCOMPARE( prefetcher.iFetchedItems.count(), 0 ); delete item; // Unnecessary prefetch call at the end of session prefetcher.prefetch(); } void SyncItemPrefetcherTest::testAbnormalBadItems() { // Test item prefetcher when some or all items returned by plugin are NULL QList itemsIds; itemsIds.append( "1" ); itemsIds.append( "2" ); itemsIds.append( "3" ); const int batchSizeHint = 2; PrefetchStorage storage( itemsIds ); SyncItemPrefetcher prefetcher( itemsIds, storage, batchSizeHint ); QCOMPARE( prefetcher.iBatchSizeHint, batchSizeHint ); QCOMPARE( &prefetcher.iStoragePlugin, &storage ); QCOMPARE( prefetcher.iItemIdList, itemsIds ); QVERIFY( prefetcher.iFetchedItems.isEmpty() ); QList items; items.append( new MockSyncItem( "1" ) ); items.append( NULL ); storage.forceSyncItems(items); SyncItem* item = prefetcher.getItem( itemsIds.at(0) ); QVERIFY( item ); QCOMPARE( prefetcher.iItemIdList.count(), itemsIds.count() - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), batchSizeHint - 1 ); // Items will be deleted by storage //delete item; item = prefetcher.getItem( itemsIds.at(1) ); QVERIFY( !item ); QCOMPARE( prefetcher.iItemIdList.count(), itemsIds.count() - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), batchSizeHint - 2 ); // Items will be deleted by storage //delete item; } void SyncItemPrefetcherTest::testAbnormalBadItemCount() { // Test item prefetcher when plugin returns invalid amount of items QList itemsIds; itemsIds.append( "1" ); itemsIds.append( "2" ); itemsIds.append( "3" ); const int batchSizeHint = 2; PrefetchStorage storage( itemsIds ); SyncItemPrefetcher prefetcher( itemsIds, storage, batchSizeHint ); QCOMPARE( prefetcher.iBatchSizeHint, batchSizeHint ); QCOMPARE( &prefetcher.iStoragePlugin, &storage ); QCOMPARE( prefetcher.iItemIdList, itemsIds ); QVERIFY( prefetcher.iFetchedItems.isEmpty() ); QList items; items.append( NULL ); items.append( NULL ); storage.forceSyncItems(items); SyncItem* item = prefetcher.getItem( itemsIds.at(0) ); QVERIFY( !item ); QCOMPARE( prefetcher.iItemIdList.count(), itemsIds.count() - batchSizeHint ); QCOMPARE( prefetcher.iFetchedItems.count(), batchSizeHint - 1 ); delete item; } QTEST_MAIN(SyncItemPrefetcherTest) buteo-syncml-0.5.15/tests_meego/SyncItemPrefetcherTest.h000066400000000000000000000066771433763642500233520ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCITEMPREFETCHERTEST_H #define SYNCITEMPREFETCHERTEST_H #include #include "StoragePlugin.h" using namespace DataSync; class PrefetchStorage : public StoragePlugin { public: PrefetchStorage( const QList& aItemIds ); virtual ~PrefetchStorage(); void forceSyncItems( const QList aSyncItems ); virtual const QString& getSourceURI() const; virtual qint64 getMaxObjSize() const; virtual const StorageContentFormatInfo& getFormatInfo() const; virtual QByteArray getPluginCTCaps( ProtocolVersion aVersion ) const; virtual QByteArray getPluginExts() const; virtual bool getAll( QList& aKeys ); virtual bool getModifications( QList& aNewKeys, QList& aReplacedKeys, QList& aDeletedKeys, const QDateTime& aTimeStamp ); virtual SyncItem* newItem(); virtual SyncItem* getSyncItem( const SyncItemKey& aKey ); virtual QList getSyncItems( const QList& aKeyList ); virtual QList addItems( const QList& aItems ); virtual QList replaceItems( const QList& aItems ); virtual QList deleteItems( const QList& aKeys ); private: QString iSourceURI; StorageContentFormatInfo iFormats; QList iItemIds; bool iForceSyncItems; QList iSyncItems; }; class SyncItemPrefetcherTest : public QObject { Q_OBJECT; public: private slots: void testNormalNoIdle(); void testNormalIdle(); void testAbnormalBadItems(); void testAbnormalBadItemCount(); }; #endif // SYNCITEMPREFETCHERTEST_H buteo-syncml-0.5.15/tests_meego/SyncItemPrefetcherTest.pro000066400000000000000000000000351433763642500237010ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SyncModeTest.cpp000066400000000000000000000153671433763642500216570ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncModeTest.h" #include "SyncMode.h" #include "datatypes.h" using namespace DataSync; void SyncModeTest::initTestCase() { } void SyncModeTest::cleanupTestCase() { } void SyncModeTest::testIsValid() { SyncMode validMode1(DIRECTION_TWO_WAY, INIT_CLIENT); QVERIFY(validMode1.isValid()); SyncMode validMode2(SLOW_SYNC); QVERIFY(validMode2.isValid()); SyncMode invalidMode(-1); QVERIFY(!invalidMode.isValid()); } void SyncModeTest::testSyncDirection() { SyncDirection direction = DIRECTION_TWO_WAY; SyncMode mode( direction ); QCOMPARE( mode.syncDirection(), direction ); } void SyncModeTest::testSyncInitiator() { SyncInitiator initiator = INIT_CLIENT; SyncMode mode(DIRECTION_TWO_WAY, initiator ); QCOMPARE( mode.syncInitiator(), initiator ); } void SyncModeTest::testSyncType() { SyncType type = TYPE_SLOW; SyncMode mode(DIRECTION_TWO_WAY, INIT_CLIENT, type ); QCOMPARE( mode.syncType(), type ); mode.setRefresh(); QCOMPARE( mode.syncType(), TYPE_REFRESH ); } void SyncModeTest::testSyncAlertCode() { SyncMode mode(INVALID_ALERT); QVERIFY(mode.isValid() == false); mode = SyncMode(RESULT_ALERT); QVERIFY(mode.isValid() == false); mode = SyncMode(TWO_WAY_SYNC); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_TWO_WAY); QCOMPARE(mode.syncInitiator(), INIT_CLIENT); QCOMPARE(mode.syncType(), TYPE_FAST); mode = SyncMode(SLOW_SYNC); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_TWO_WAY); QCOMPARE(mode.syncInitiator(), INIT_CLIENT); QCOMPARE(mode.syncType(), TYPE_SLOW); mode = SyncMode(ONE_WAY_FROM_CLIENT_SYNC); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_CLIENT); QCOMPARE(mode.syncInitiator(), INIT_CLIENT); QCOMPARE(mode.syncType(), TYPE_FAST); mode = SyncMode(REFRESH_FROM_CLIENT_SYNC); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_CLIENT); QCOMPARE(mode.syncInitiator(), INIT_CLIENT); QCOMPARE(mode.syncType(), TYPE_REFRESH); mode = SyncMode(ONE_WAY_FROM_SERVER_SYNC); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_SERVER); QCOMPARE(mode.syncInitiator(), INIT_CLIENT); QCOMPARE(mode.syncType(), TYPE_FAST); mode = SyncMode(REFRESH_FROM_SERVER_SYNC); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_SERVER); QCOMPARE(mode.syncInitiator(), INIT_CLIENT); QCOMPARE(mode.syncType(), TYPE_REFRESH); mode = SyncMode(TWO_WAY_BY_SERVER); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_TWO_WAY); QCOMPARE(mode.syncInitiator(), INIT_SERVER); QCOMPARE(mode.syncType(), TYPE_FAST); mode = SyncMode(ONE_WAY_FROM_CLIENT_BY_SERVER); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_CLIENT); QCOMPARE(mode.syncInitiator(), INIT_SERVER); QCOMPARE(mode.syncType(), TYPE_FAST); mode = SyncMode(REFRESH_FROM_CLIENT_BY_SERVER); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_CLIENT); QCOMPARE(mode.syncInitiator(), INIT_SERVER); QCOMPARE(mode.syncType(), TYPE_REFRESH); mode = SyncMode(ONE_WAY_FROM_SERVER_BY_SERVER); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_SERVER); QCOMPARE(mode.syncInitiator(), INIT_SERVER); QCOMPARE(mode.syncType(), TYPE_FAST); mode = SyncMode(REFRESH_FROM_SERVER_BY_SERVER); QVERIFY(mode.isValid()); QCOMPARE(mode.syncDirection(), DIRECTION_FROM_SERVER); QCOMPARE(mode.syncInitiator(), INIT_SERVER); QCOMPARE(mode.syncType(), TYPE_REFRESH); } void SyncModeTest::testToSyncML() { qint32 syncMLCode = TWO_WAY_SYNC; SyncMode mode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = SLOW_SYNC; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = ONE_WAY_FROM_CLIENT_SYNC; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = REFRESH_FROM_CLIENT_SYNC; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = ONE_WAY_FROM_SERVER_SYNC; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = REFRESH_FROM_SERVER_SYNC; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = TWO_WAY_BY_SERVER; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = ONE_WAY_FROM_CLIENT_BY_SERVER; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = REFRESH_FROM_CLIENT_BY_SERVER; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = ONE_WAY_FROM_SERVER_BY_SERVER; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); syncMLCode = REFRESH_FROM_SERVER_BY_SERVER; mode = SyncMode(syncMLCode); QCOMPARE(mode.toSyncMLCode(), syncMLCode); mode = SyncMode(DIRECTION_TWO_WAY, INIT_CLIENT, TYPE_REFRESH); QCOMPARE(mode.toSyncMLCode(), -1); } QTEST_MAIN(DataSync::SyncModeTest) buteo-syncml-0.5.15/tests_meego/SyncModeTest.h000066400000000000000000000040321433763642500213070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNC_MODE_TEST_H #define SYNC_MODE_TEST_H #include namespace DataSync { class SyncModeTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testIsValid(); void testSyncDirection(); void testSyncInitiator(); void testSyncType(); void testSyncAlertCode(); void testToSyncML(); }; } #endif buteo-syncml-0.5.15/tests_meego/SyncModeTest.pro000066400000000000000000000000351433763642500216570ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SyncResultTest.cpp000066400000000000000000000061371433763642500222440ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncResultTest.h" #include "SyncResults.h" using namespace DataSync; void SyncResultsTest::initTestCase() { iSyncResults = new SyncResults(); } void SyncResultsTest::cleanupTestCase() { delete iSyncResults; iSyncResults = NULL; } void SyncResultsTest::testGetLastState() { iSyncResults->setState( SYNC_FINISHED ); SyncState state = iSyncResults->getState(); QVERIFY( state == SYNC_FINISHED ); } void SyncResultsTest::testGetLastErrorString() { QString errorString( "Guru meditation" ); iSyncResults->setErrorString( errorString ); QString error = iSyncResults->getErrorString(); QVERIFY( error == errorString ); } void SyncResultsTest::testAddProcessedItem() { DataSync::ModifiedDatabase modBase = MOD_LOCAL_DATABASE; DataSync::ModificationType modType = MOD_ITEM_ADDED; QString database = "foo"; iSyncResults->addProcessedItem(modType, modBase, database); modType = MOD_ITEM_MODIFIED; iSyncResults->addProcessedItem(modType, modBase, database); modType = MOD_ITEM_DELETED; iSyncResults->addProcessedItem(modType, modBase, database); modBase = MOD_REMOTE_DATABASE; modType = MOD_ITEM_ADDED; iSyncResults->addProcessedItem(modType, modBase, database); modType = MOD_ITEM_MODIFIED; iSyncResults->addProcessedItem(modType, modBase, database); modType = MOD_ITEM_DELETED; iSyncResults->addProcessedItem(modType, modBase, database); } QTEST_MAIN(DataSync::SyncResultsTest) buteo-syncml-0.5.15/tests_meego/SyncResultTest.h000066400000000000000000000041501433763642500217020ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCRESULTTEST_HH #define SYNCRESULTTEST_HH #include namespace DataSync { class SyncResults; class SyncResultsTest: public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testGetLastState(); void testGetLastErrorString(); void testAddProcessedItem(); private: SyncResults* iSyncResults; }; } #endif buteo-syncml-0.5.15/tests_meego/SyncResultTest.pro000066400000000000000000000000351433763642500222510ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/SyncTargetTest.cpp000066400000000000000000000061551433763642500222140ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncTargetTest.h" #include "SyncTarget.h" #include "DatabaseHandler.h" #include "Mock.h" #include "ChangeLog.h" using namespace DataSync; void SyncTargetTest::initTestCase() { iDbHandler = new DatabaseHandler( "/tmp/synctargettest.db"); QString remoteDevice = "remotedevice"; QString localDb = "localcontacts"; const SyncMode syncMode; iChangeLog = new ChangeLog( remoteDevice, localDb, syncMode.syncDirection() ); iStorage = new MockStorage( localDb ); QVERIFY( iStorage != 0 ); iSyncTarget = new SyncTarget( iChangeLog, iStorage, syncMode, "fooanchor" ); QVERIFY( iSyncTarget != 0 ); } void SyncTargetTest::cleanupTestCase() { delete iSyncTarget; iSyncTarget = 0; delete iDbHandler; iDbHandler = 0; delete iStorage; iStorage = 0; } void SyncTargetTest::testSetGetRemoteNextAnchor() { const QString next = "foo"; iSyncTarget->setRemoteNextAnchor(next); QString next_received = iSyncTarget->getRemoteNextAnchor(); QVERIFY(next == next_received); } void SyncTargetTest::testRevertSyncMode() { iSyncTarget->revertSyncMode(); } void SyncTargetTest::testReverted() { iSyncTarget->iReverted = true; bool reverted = iSyncTarget->reverted(); QVERIFY(reverted); } void SyncTargetTest::testClearUIDMappings() { iSyncTarget->clearUIDMappings(); } void SyncTargetTest::testSetRefreshFromClient() { QCOMPARE( iSyncTarget->setRefreshFromClient(), false ); } QTEST_MAIN(DataSync::SyncTargetTest) buteo-syncml-0.5.15/tests_meego/SyncTargetTest.h000066400000000000000000000044111433763642500216520ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCTARGETTEST_HH #define SYNCTARGETTEST_HH #include namespace DataSync { class SyncTarget; class DatabaseHandler; class ChangeLog; class StoragePlugin; class SyncTargetTest: public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testSetGetRemoteNextAnchor(); void testRevertSyncMode(); void testReverted(); void testClearUIDMappings(); void testSetRefreshFromClient(); private: StoragePlugin* iStorage; SyncTarget* iSyncTarget; ChangeLog* iChangeLog; DataSync::DatabaseHandler* iDbHandler; }; } #endif buteo-syncml-0.5.15/tests_meego/SyncTargetTest.pro000066400000000000000000000000351433763642500222210ustar00rootroot00000000000000include(testapplication.pri) buteo-syncml-0.5.15/tests_meego/TestUtils.cpp000066400000000000000000000040201433763642500212160ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "TestUtils.h" #include #include #include #include bool readFile( const QString& aFileName, QByteArray& aData ) { QFile file( aFileName ); if( file.open( QIODevice::ReadOnly ) ) { aData = file.readAll(); file.close(); return true; } else { qDebug() << "Could not read file" << aFileName; return false; } } buteo-syncml-0.5.15/tests_meego/TestUtils.h000066400000000000000000000036521433763642500206750ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef TESTUTILS_H #define TESTUTILS_H class QByteArray; class QString; /*! \brief Reads a file * * @param aFileName Name of the file * @param aData Read file data on success * @return True on success, otherwise false */ bool readFile( const QString& aFileName, QByteArray& aData ); #endif // TESTUTILS_H buteo-syncml-0.5.15/tests_meego/TestUtils.pro000066400000000000000000000002351433763642500212400ustar00rootroot00000000000000include(tests_common.pri) TEMPLATE = lib CONFIG += staticlib TARGET = TestUtils HEADERS = \ Mock.h \ TestUtils.h \ SOURCES = \ TestUtils.cpp \ buteo-syncml-0.5.15/tests_meego/clienttests/000077500000000000000000000000001433763642500211175ustar00rootroot00000000000000buteo-syncml-0.5.15/tests_meego/clienttests/ClientSessionHandlerTest.cpp000066400000000000000000000174071433763642500265540ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ClientSessionHandlerTest.h" #include #include "ClientSessionHandler.h" #include "SyncAgentConfig.h" #include "datatypes.h" #include "Mock.h" #include "ChangeLog.h" #include "SyncMLLogging.h" using namespace DataSync; void ClientSessionHandlerTest::initTestCase() { iDbHandler = new DatabaseHandler( "/tmp/clientsessionhandler.db"); iClientId = QString("clientId"); iConfig = new SyncAgentConfig(); iTransport = new MockTransport(QString("data/transport_initrequest_nohdr.txt")); iConfig->setTransport(iTransport); const SyncAgentConfig *tempConstConfig = iConfig; iHandler = new ClientSessionHandler(tempConstConfig); } void ClientSessionHandlerTest::cleanupTestCase() { delete iTransport; delete iHandler; delete iDbHandler; delete iConfig; } void ClientSessionHandlerTest::testMapReceived() { bool result = iHandler->mapReceived(); QVERIFY(result == false); } void ClientSessionHandlerTest::testResendPackage() { iHandler->setSyncState(PREPARED); iHandler->resendPackage(); iHandler->setSyncState(LOCAL_INIT); iHandler->resendPackage(); iHandler->setSyncState(SENDING_ITEMS); iHandler->resendPackage(); iHandler->setSyncState(FINALIZING); iHandler->resendPackage(); } void ClientSessionHandlerTest::testSyncReceived() { bool result; iHandler->setSyncState(PREPARED); result = iHandler->syncReceived(); QVERIFY(result == false); iHandler->setSyncState(REMOTE_INIT); result = iHandler->syncReceived(); QVERIFY(result == false); iHandler->setSyncWithoutInitPhase( true ); iHandler->setSyncState(REMOTE_INIT); result = iHandler->syncReceived(); QVERIFY(result == true); iHandler->setSyncState(LOCAL_INIT); result = iHandler->syncReceived(); QVERIFY(result == false); iHandler->setSyncState(SENDING_ITEMS); result = iHandler->syncReceived(); QVERIFY(result == true); iHandler->setSyncState(RECEIVING_ITEMS); result = iHandler->syncReceived(); QVERIFY(result == true); } void ClientSessionHandlerTest::testFinalReceived() { iHandler->setSyncState(PREPARED); iHandler->finalReceived(); iHandler->setSyncState(SENDING_ITEMS); iHandler->finalReceived(); iHandler->setSyncState(RECEIVING_ITEMS); iHandler->finalReceived(); iHandler->setSyncWithoutInitPhase( true ); iHandler->finalReceived(); iHandler->setSyncState(RECEIVING_MAPPINGS); iHandler->finalReceived(); iHandler->setSyncState(REMOTE_INIT); iHandler->finalReceived(); iHandler->setSyncState(FINALIZING); iHandler->finalReceived(); } void ClientSessionHandlerTest::testBusyStatusReceived() { StatusParams *busyStatusParams = new StatusParams; busyStatusParams->data = IN_PROGRESS; busyStatusParams->cmdRef = 0; iHandler->setSyncState(PREPARED); iHandler->finalReceived(); iHandler->setSyncState(SENDING_ITEMS); iHandler->handleStatusElement(busyStatusParams); QVERIFY(iHandler->isRemoteBusyStatusSet() == true); iHandler->messageParsed(); QVERIFY(iHandler->isRemoteBusyStatusSet() == false); } void ClientSessionHandlerTest::regression_NB166841_01() { // regression_NB166841_01: Test that target acknowledgement succeeds if // target db uri and next anchor are present const QString sourceURI( "./storage" ); const QString nextAnchor( "0" ); const SyncDirection direction( DIRECTION_TWO_WAY ); SyncAgentConfig config; ClientSessionHandler sessionHandler(&config); MockStorage* storage = new MockStorage( sourceURI ); ChangeLog* changeLog = new ChangeLog( "", sourceURI, direction ); MockSyncTarget* target = new MockSyncTarget( changeLog, storage, direction, nextAnchor ); sessionHandler.iStorages.append( storage ); sessionHandler.iSyncTargets.append( target ); SyncMode syncMode; CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.target = sourceURI; item.meta.anchor.next = nextAnchor; alert.items.append(item); ResponseStatusCode status = sessionHandler.acknowledgeTarget( syncMode, alert ); QCOMPARE( status, SUCCESS ); } void ClientSessionHandlerTest::regression_NB166841_02() { // regression_NB166841_02: Test that target acknowledgement fails when // target db is not present in the alert sent by remote device const QString sourceURI( "./storage" ); const QString nextAnchor( "0" ); const SyncDirection direction( DIRECTION_TWO_WAY ); SyncAgentConfig config; ClientSessionHandler sessionHandler(&config); MockStorage* storage = new MockStorage( sourceURI ); ChangeLog* changeLog = new ChangeLog( "", sourceURI, direction ); MockSyncTarget* target = new MockSyncTarget( changeLog, storage, direction, nextAnchor ); sessionHandler.iStorages.append( storage ); sessionHandler.iSyncTargets.append( target ); SyncMode syncMode; CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.meta.anchor.next = nextAnchor; alert.items.append(item); ResponseStatusCode status = sessionHandler.acknowledgeTarget( syncMode, alert ); QCOMPARE( status, INCOMPLETE_COMMAND ); } void ClientSessionHandlerTest::regression_NB166841_03() { // regression_NB166841_03: Test that target acknowledgement fails when // next anchor is not present in the alert sent by remote device const QString sourceURI( "./storage" ); const QString nextAnchor( "0" ); const SyncDirection direction( DIRECTION_TWO_WAY ); SyncAgentConfig config; ClientSessionHandler sessionHandler(&config); MockStorage* storage = new MockStorage( sourceURI ); ChangeLog* changeLog = new ChangeLog( "", sourceURI, direction ); MockSyncTarget* target = new MockSyncTarget( changeLog, storage, direction, nextAnchor ); sessionHandler.iStorages.append( storage ); sessionHandler.iSyncTargets.append( target ); SyncMode syncMode; CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.target = sourceURI; alert.items.append(item); ResponseStatusCode status = sessionHandler.acknowledgeTarget( syncMode, alert ); QCOMPARE( status, INCOMPLETE_COMMAND ); } QTEST_MAIN(ClientSessionHandlerTest) buteo-syncml-0.5.15/tests_meego/clienttests/ClientSessionHandlerTest.h000066400000000000000000000050721433763642500262140ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CLIENTSESSIONHNDLAERTEST_H #define CLIENTSESSIONHNDLAERTEST_H #include #include #include "SyncTarget.h" #include "Mock.h" namespace DataSync { class ClientSessionHandler; class Transport; class SyncAgentConfig; class DatabaseHandler; } class ClientSessionHandlerTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testMapReceived(); void testResendPackage(); void testSyncReceived(); void testFinalReceived(); void testBusyStatusReceived(); void regression_NB166841_01(); void regression_NB166841_02(); void regression_NB166841_03(); private: MockTransport* iTransport; DataSync::SyncAgentConfig* iConfig; DataSync::ClientSessionHandler* iHandler; QString iClientId; DatabaseHandler* iDbHandler; }; #endif /* CLIENTSESSIONHNDLAERTEST_H */ buteo-syncml-0.5.15/tests_meego/clienttests/ClientSessionHandlerTest.pro000066400000000000000000000000401433763642500265530ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/clienttests/clienttests.pro000077500000000000000000000001371433763642500242060ustar00rootroot00000000000000include(../tests_common.pri) TEMPLATE = subdirs SUBDIRS = \ ClientSessionHandlerTest.pro \ buteo-syncml-0.5.15/tests_meego/data/000077500000000000000000000000001433763642500174675ustar00rootroot00000000000000buteo-syncml-0.5.15/tests_meego/data/SAN01.bin000066400000000000000000000000701433763642500207400ustar00rootroot00000000000000y«ghòf˜&›L§‚"­PC Suite Data Sync`Contactsbuteo-syncml-0.5.15/tests_meego/data/SAN02.bin000066400000000000000000000000701433763642500207410ustar00rootroot00000000000000e­ñkîØ@†ƒÏÈ"k‹PC Suite Data Sync`Calendarbuteo-syncml-0.5.15/tests_meego/data/SyncMLHdrTest.txt000066400000000000000000000006251433763642500226760ustar00rootroot00000000000000 1.2 SyncML/1.2 12345 100 card addressbook 20 40 buteo-syncml-0.5.15/tests_meego/data/SyncMLHdrTest_11.txt000066400000000000000000000006251433763642500231770ustar00rootroot00000000000000 1.1 SyncML/1.1 12345 100 card addressbook 20 40 buteo-syncml-0.5.15/tests_meego/data/basicbasetransport.bin000066400000000000000000000001111433763642500240430ustar00rootroot00000000000000¤jmlq1.2rSyncML/1.2%[1nWtargetDevicegWsourceDevice+buteo-syncml-0.5.15/tests_meego/data/basicbasetransport.txt000066400000000000000000000004321433763642500241200ustar00rootroot000000000000001.2SyncML/1.21targetDevicesourceDevice buteo-syncml-0.5.15/tests_meego/data/basicbasetransport2.txt000066400000000000000000000007531433763642500242100ustar00rootroot00000000000000 1.2 SyncML/1.2 1 targetDevice sourceDevice buteo-syncml-0.5.15/tests_meego/data/cmdhandler_get.txt000066400000000000000000000025671433763642500232020ustar00rootroot000000000000001.2SyncML/1.21111Get./devinf11211Get./devinf12311Get./devinf12411Getfoo511Get./devinf12611./devinf12application/vnd.syncml-devinf+xml./devinf121.2Nokiaphone buteo-syncml-0.5.15/tests_meego/data/cmdhandler_put.txt000066400000000000000000000025561433763642500232310ustar00rootroot000000000000001.2SyncML/1.21111Put./devinf11211Put./devinf11311Put./devinf12411Put./devinf12511Put./devinf12611Put./devinf12711Putfoo811Putfoo buteo-syncml-0.5.15/tests_meego/data/devinf01.txt000066400000000000000000000127311433763642500216500ustar00rootroot00000000000000 1.1 FooManufacturer FooModel FooOEM FwVersion v 21.0.045 HwVersion IMEI:356064034969473 phone_Switch4 ./Contacts 8 text/x-vcard 2.1 text/vcard 3.0 text/x-vcard 2.1 1 2 3 5 7 ./Calendar 8 text/x-vcalendar 1.0 text/x-vcalendar 1.0 1 2 3 5 7 ./Notepad 8 text/plain 1.0 text/plain 1.0 text/plain 1.0 1 2 3 5 7 text/x-vcard BEGIN VCARD END VCARD VERSION 2.1 REV N ADR HOME WORK PREF TEL HOME WORK CELL PAGER FAX VOICE CAR VIDEO FN EMAIL URL HOME WORK NOTE TITLE ORG PHOTO BDAY X-SIP LABEL X-ASSISTANT X-SPOUSE X-CHILDREN X-ASSISTANT-TEL X-ANNIVERSARY X-CLASS SOUND X-EPOCSECONDNAME X-WV-ID UID X-CNTGROUP text/x-vcalendar BEGIN VCALENDAR VEVENT VTODO END VCALENDAR VEVENT VTODO VERSION 1.0 UID SUMMARY DESCRIPTION DTEND DTSTART AALARM X-EPOCSOUND CLASS PUBLIC PRIVATE CONFIDENTIAL LOCATION DCREATED LAST-MODIFIED PRIORITY STATUS RRULE DUE ATTACH EXDATE TZ DAYLIGHT RDATE RNUM TRANSP ATTENDEE STATUS X-METHOD X-RECURRENCE-ID X-SYMBIAN-LUID X-SYMBIAN-DTSTAMP X-ANNIVERSARY X-CLASS X-SENT-BY X-EPOCAGENDAENTRYTYPE APPOINTMENT EVENT ANNIVERSARY TODO X-ADAPTERVERSION v 21.0.045 14-01-10 RM-505 (c) Nokia text/plain chr 0 buteo-syncml-0.5.15/tests_meego/data/devinf02.txt000066400000000000000000000265331433763642500216560ustar00rootroot00000000000000 1.2 FooManufacturer FooModel FooOEM FwVersion v 21.0.045 HwVersion IMEI:356064034969473 phone_Switch4 ./Contacts 8 text/x-vcard 2.1 text/vcard 3.0 text/x-vcard 2.1 1 2 3 5 7 text/x-vcard 2.1 BEGIN 256 VCARD END 256 VCARD VERSION 256 2.1 REV 256 N 256 ADR 256 TYPE HOME WORK TEL 256 TYPE HOME WORK CELL PAGER FAX VIDEO PREF CAR FN 256 EMAIL 256 TYPE HOME WORK URL 256 TYPE HOME WORK NOTE 256 TITLE 256 ORG 256 PHOTO 256 BDAY 256 SOUND 256 X-ASSISTANT 256 X-ASSISTANT-TEL 256 X-SPOUSE 256 X-CHILDREN 256 X-ANNIVERSARY 256 X-GENDER 256 X-JABBER 256 X-SIP 256 TYPE SWIS VOIP ./Calendar 8 text/x-vcalendar 1.0 text/x-vcalendar 1.0 1 2 3 5 7 text/x-vcalendar 1.0 BEGIN 256 VCALENDAR VEVENT VTODO Begin END 256 VCALENDAR VEVENT VTODO End VERSION 256 1.0 Version UID 256 Uid SUMMARY 256 Summary DESCRIPTION 256 Description DTSTART 256 Dstart DTEND 256 Dtend AALARM 256 Aalarm TYPE Alarm type CLASS 256 PUBLIC PRIVATE CONFIDENTIAL Class LOCATION 256 Location LAST-MODIFIED 256 Last Modified PRIORITY 256 Priority STATUS 256 Status RRULE 256 Rrule COMPLETED 256 Completed DCREATED 256 Dcreated DUE 256 Due EXDATE 256 ExDate CATEGORIES 256 Categories SEQUENCE 256 Sequence TZ 256 TZ DAYLIGHT 256 Daylight RDATE 256 RDate ATTENDEE 256 Attendee TYPE ROLE STATUS X-CN X-ROLE X-SENTBY X-STATUS Type ./Notepad 8 text/plain 1.0 text/plain 1.0 text/plain 1.0 1 2 3 5 7 text/plain 1.0 Note chr 5 0 Note buteo-syncml-0.5.15/tests_meego/data/obexresp01.bin000066400000000000000000000000321433763642500221440ustar00rootroot00000000000000 ÿÿËJSYNCML-SYNCbuteo-syncml-0.5.15/tests_meego/data/obexresp02.bin000066400000000000000000000000031433763642500221430ustar00rootroot00000000000000Óbuteo-syncml-0.5.15/tests_meego/data/obexresp03.bin000066400000000000000000000000031433763642500221440ustar00rootroot00000000000000 buteo-syncml-0.5.15/tests_meego/data/resp.txt000066400000000000000000000076661433763642500212200ustar00rootroot00000000000000 1.2 SyncML/1.2 1230022352 5 sc-pim-75af2bff-3a5e-4cba-affb-4c555b9ee740 http://82.77.123.71:8080/services/syncml http://82.77.123.71:8080/services/syncml?s=RYHmRQAA&srv_id=002 1 5 0 SyncHdr http://localhost:8080/funambol/ds/card sc-pim-75af2bff-3a5e-4cba-affb-4c555b9ee740 syncml:auth-md5 b64 ZG9iZWhhdmUNCg== 200 note memo 2 201 addressbook card 1232366487448 1232981790235 500000 3 addressbook card 4 text/x-vcard 0 1 BEGIN:VCARD VERSION:2.1 N:Lahtela;Tatu;;; FN:Lahtela, Tatu TEL;TYPE=PREF:+35840 7532165 EMAIL;INTERNET:tatu.lahtela TITLE: ORG:; END:VCARD 5 x-type/x-subtype 244 245 ReplaceData 6 x-type/x-subtype2 128 7 http://www.datasync.org/servlet/syncit IMEI:001004FF1234567 ./0123456789ABCDEF ./01 ./0123456789ABCDF0 ./02 ./0123456789ABCDF1 ./03 buteo-syncml-0.5.15/tests_meego/data/resp2.txt000066400000000000000000000006111433763642500212610ustar00rootroot00000000000000 1 1 1 Alert ./contacts/james_bond ./dev-contacts 200 276 buteo-syncml-0.5.15/tests_meego/data/respinvalid1.txt000066400000000000000000000000461433763642500226310ustar00rootroot00000000000000buteo-syncml-0.5.15/tests_meego/data/respinvalid2.txt000066400000000000000000000000721433763642500226310ustar00rootroot00000000000000 buteo-syncml-0.5.15/tests_meego/data/respinvalid3.txt000066400000000000000000000001211433763642500226250ustar00rootroot00000000000000 buteo-syncml-0.5.15/tests_meego/data/respinvalid4.txt000066400000000000000000000001231433763642500226300ustar00rootroot00000000000000 buteo-syncml-0.5.15/tests_meego/data/respinvalid5.txt000066400000000000000000000002011433763642500226260ustar00rootroot00000000000000 buteo-syncml-0.5.15/tests_meego/data/respinvalid6.txt000066400000000000000000000002031433763642500226310ustar00rootroot00000000000000 buteo-syncml-0.5.15/tests_meego/data/subcommands01.txt000066400000000000000000000105771433763642500227160ustar00rootroot00000000000000 1.2 SyncML/1.2 1 1 http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 65535 1 ./calendar text/x-vcalendar 2 application/vnd.syncml-devinf+xml ./devinf12 3 4 ./calendar text/x-vcalendar 5 text/x-vcalendar 1133 6 7 ./calendar text/x-vcalendar 8 text/x-vcalendar 1133 9 ./calendar ./Calendar 0 1018 10 text/x-vcalendar 1133 11 text/x-vcalendar 1134 12 13 text/x-vcalendar 1133 14 text/x-vcalendar 1134 buteo-syncml-0.5.15/tests_meego/data/syncml_init.txt000066400000000000000000000023111433763642500225550ustar00rootroot000000000000001.1SyncML/1.112307174951http://localhost:8080/funambol/dssc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0guestb64syncml:auth-md5pi7qlvm20/3ssN2yQm2xAg==81925000001200cardaddressbook123071740312307174955000002200notememo12307174031230717495500000 buteo-syncml-0.5.15/tests_meego/data/syncml_resp.txt000066400000000000000000000027001433763642500225650ustar00rootroot00000000000000 1.1 SyncML/1.1 1230717495 2 http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 b64 syncml:auth-basic Z3Vlc3Q6Z3Vlc3Q= 8192 500000 1 1 0 SyncHdr http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 200 2 200 card addressbook 1230717403 1230717495 500000 3 200 note memo 1230717403 1230717495 500000 buteo-syncml-0.5.15/tests_meego/data/syncml_resp2.txt000066400000000000000000000023731433763642500226550ustar00rootroot00000000000000 1.1 SyncML/1.1 1230717403 3 http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 1 2 0 SyncHdr http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 200 2 2 4 Alert card addressbook 200 1230717403643 3 2 5 Alert note memo 200 1230717403643 4 card addressbook buteo-syncml-0.5.15/tests_meego/data/syncml_resp3.txt000066400000000000000000000013311433763642500226470ustar00rootroot00000000000000 1.1 SyncML/1.1 1230717403 4 http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 1 3 0 SyncHdr http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 200 2 note memo buteo-syncml-0.5.15/tests_meego/data/syncml_resp4.txt000066400000000000000000000016231433763642500226540ustar00rootroot00000000000000 1.1 SyncML/1.1 1230717403 5 http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 1 4 0 SyncHdr http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 200 2 222 card addressbook 3 222 note memo buteo-syncml-0.5.15/tests_meego/data/syncml_resp5.txt000066400000000000000000000025271433763642500226610ustar00rootroot00000000000000 1.1 SyncML/1.1 1230717403 6 http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 1 5 0 SyncHdr http://localhost:8080/funambol/ds sc-pim-166b90db-53a4-4877-a5bd-285e533c4cb0 200 2 5 4 Sync card addressbook 200 3 5 5 Add 200 3 4 5 6 Sync note memo 200 5 card addressbook 3 pas-id-495B41DB00000004 buteo-syncml-0.5.15/tests_meego/data/testAdd.txt000066400000000000000000000001051433763642500216140ustar00rootroot00000000000000 10 buteo-syncml-0.5.15/tests_meego/data/testAlert.txt000066400000000000000000000007351433763642500222040ustar00rootroot00000000000000 -1 card addressbook 12345678 12345679 text buteo-syncml-0.5.15/tests_meego/data/testDevInf.txt000066400000000000000000000006451433763642500223100ustar00rootroot00000000000000 ./devinf12 1.2 buteo-syncml-0.5.15/tests_meego/data/testItem.txt000066400000000000000000000004001433763642500220200ustar00rootroot00000000000000contactscalendarcontactsparentcalendarparent buteo-syncml-0.5.15/tests_meego/data/testURI.txt000066400000000000000000000017471433763642500216000ustar00rootroot000000000000001.2SyncML/1.212338217793sc-pim-7c7cc17f-3d01-413d-baeb-435ffcbe375fhttp://82.77.123.71:8080/services/syncmlhttp://82.77.123.71:8080/services/syncml?s=RYHmRQAA&srv_id=002120SyncHdrhttp://82.77.123.71:8080/services/syncmlsc-pim-7c7cc17f-3d01-413d-baeb-435ffcbe375fb64syncml:auth-basic407222Sync407323Add1407 buteo-syncml-0.5.15/tests_meego/data/testconf.xsd000066400000000000000000000113361433763642500220400ustar00rootroot00000000000000 buteo-syncml-0.5.15/tests_meego/data/testconf1.xml000066400000000000000000000025051433763642500221210ustar00rootroot00000000000000 /fooland/syncml.db FoolandDevice 32768 10 1 1 1024 2048 4096 120 3 http://www.google.com 666 InqMe AckMe Map1 text/foo1 Map2 text/foo2 buteo-syncml-0.5.15/tests_meego/data/toXMLtest.txt000066400000000000000000000002251433763642500221320ustar00rootroot00000000000000 12Srikanth Kavoori buteo-syncml-0.5.15/tests_meego/data/transport_initrequest.txt000066400000000000000000000063251433763642500247260ustar00rootroot00000000000000POST /services/syncml HTTP/1.1 POST: /services/syncml User-Agent: libdatasync Content-Type: application/vnd.syncml+xml Accept: */* auth-type: global Content-Length: 3037 Connection: Keep-Alive Accept-Encoding: gzip Host: localhost:8081 1.2 SyncML/1.2 1241693158 1 http://localhost:8081/services/syncml sc-pim-7c7cc17f-3d01-413d-baeb-435ffcbe375f 8192 500000 b64 syncml:auth-basic dGF0dTp0YXR1 1 application/vnd.syncml-devinf+xml ./devinf12 1.2 Nokia Model 1.0 1.0 1.0 DeviceID phone contact text/x-vcard 2.1 text/x-vcard 2.1 text/vcard 3.0 text/vcard 3.0 1 2 3 4 5 6 7 2 200 contact contact 1241693158 buteo-syncml-0.5.15/tests_meego/data/transport_initrequest_nohdr.txt000066400000000000000000000060451433763642500261170ustar00rootroot00000000000000 1.2 SyncML/1.2 1241693158 1 http://localhost:8081/services/syncml sc-pim-7c7cc17f-3d01-413d-baeb-435ffcbe375f 8192 500000 b64 syncml:auth-basic dGF0dTp0YXR1 1 application/vnd.syncml-devinf+xml ./devinf12 1.2 Nokia Model 1.0 1.0 1.0 DeviceID phone contact text/x-vcard 2.1 text/x-vcard 2.1 text/vcard 3.0 text/vcard 3.0 1 2 3 4 5 6 7 2 200 contact contact 1241693158 buteo-syncml-0.5.15/tests_meego/generaltests.pro000066400000000000000000000013241433763642500220000ustar00rootroot00000000000000include(tests_common.pri) TEMPLATE = subdirs SUBDIRS = \ AlertPackageTest.pro \ AuthenticationPackageTest.pro \ AuthHelperTest.pro \ CommandHandlerTest.pro \ ConflictResolverTest.pro \ DevInfHandlerTest.pro \ DevInfPackageTest.pro \ FinalPackageTest.pro \ ChangeLogTest.pro \ LocalChangesPackageTest.pro \ LocalMappingsPackageTest.pro \ NonceStorageTest.pro \ ResponseGeneratorTest.pro \ SANTest.pro \ SessionHandlerTest.pro \ StorageHandlerTest.pro \ SyncAgentConfigTest.pro \ SyncAgentTest.pro \ SyncItemPrefetcherTest.pro \ SyncModeTest.pro \ SyncResultTest.pro \ SyncTargetTest.pro \ # Dead code? #ChangeLogHandlerTest.pro buteo-syncml-0.5.15/tests_meego/libmaemosyncml-tests.ref000066400000000000000000000030771433763642500234360ustar00rootroot00000000000000Totals: 6 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 6 passed, 0 failed, 0 skipped Totals: 13 passed, 0 failed, 0 skipped Totals: 5 passed, 0 failed, 0 skipped Totals: 6 passed, 0 failed, 0 skipped Totals: 2 passed, 0 failed, 0 skipped Totals: 8 passed, 0 failed, 0 skipped Totals: 6 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 6 passed, 0 failed, 0 skipped Totals: 7 passed, 0 failed, 0 skipped Totals: 5 passed, 0 failed, 0 skipped Totals: 23 passed, 0 failed, 0 skipped Totals: 10 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 4 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 6 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 3 passed, 0 failed, 0 skipped Totals: 6 passed, 0 failed, 0 skipped buteo-syncml-0.5.15/tests_meego/runstarget.sh000077500000000000000000000002601433763642500213110ustar00rootroot00000000000000#!/bin/sh if [ $# -lt 1 ]; then echo "You need to pass test executable as an argument!" exit 1 fi cd "$(dirname "${0}")" PATH=".:${PATH}" exec "${@}" -maxwarnings 0 buteo-syncml-0.5.15/tests_meego/sample.db000066400000000000000000000060001433763642500203420ustar00rootroot00000000000000SQLite format 3@  [ [CWtabletimechecktimecheckCREATE TABLE timecheck (tt timestamp)^tablecontactscontactsCREATE TABLE contacts (id integer primary key, vcard varchar(64))  buteo-syncml-0.5.15/tests_meego/servertests/000077500000000000000000000000001433763642500211475ustar00rootroot00000000000000buteo-syncml-0.5.15/tests_meego/servertests/ServerCommandHandlerTest.cpp000066400000000000000000000224151433763642500265620ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ServerCommandHandlerTest.h" #include "CommandHandler.h" #include "ChangeLog.h" #include "SyncAgentConfig.h" #include "datatypes.h" #include "Mock.h" #include "SyncTarget.h" #include "StorageHandler.h" #include "ConflictResolver.h" #include "DeviceInfo.h" #include #include "SyncMLLogging.h" using namespace DataSync; /*! \fn ServerCommandHandlerTest::initTestCase() */ void ServerCommandHandlerTest::initTestCase() { iDbHandler = new DatabaseHandler( "/tmp/servercommandhandlertest.db"); iStorageHandler = new StorageHandler(); iCommandHandler = new CommandHandler( MODE_SERVER ); iRemoteDevice = "remotedevice"; iLocalDb = "localcontacts"; iRemoteDb = "remotecontacts"; iStorage = new MockStorage( iLocalDb ); SyncMode syncMode; ChangeLog* changeLog = new ChangeLog( iDbHandler->getDbHandle(), iRemoteDevice, iLocalDb, DIRECTION_TWO_WAY ); SyncTarget* target = new SyncTarget( changeLog, *iStorage, syncMode, "fooanchor" ); iTargets.append(target); } /*! \fn ServerCommandHandlerTest::cleanupTestCase() */ void ServerCommandHandlerTest::cleanupTestCase() { qDeleteAll(iTargets); iTargets.clear(); delete iStorage; iStorage = 0; delete iCommandHandler; iCommandHandler = 0; delete iStorageHandler; iStorageHandler = 0; delete iDbHandler; iDbHandler = 0; } /*! \fn ServerCommandHandlerTest::testHandlerPut() */ void ServerCommandHandlerTest::testHandlerPut() { MetaParams metaParams; metaParams.type = SYNCML_CONTTYPE_DEVINF_XML; ItemParams item; item.source = SYNCML_DEVINF_PATH_11; SyncActionData actionData; actionData.action = SYNCML_PUT; actionData.meta = metaParams; actionData.items.append(item); ProtocolVersion version = DS_1_1; iCommandHandler->handlePut(actionData, version, iResponseGenerator); version = DS_1_2; iCommandHandler->handlePut(actionData, version, iResponseGenerator); actionData.items[0].source = SYNCML_DEVINF_PATH_12; iCommandHandler->handlePut(actionData, version, iResponseGenerator); version = DS_1_1; iCommandHandler->handlePut(actionData, version, iResponseGenerator); } /*! \fn ServerCommandHandlerTest::testHandleGet() */ void ServerCommandHandlerTest::testHandleGet() { MetaParams metaParams; metaParams.type = SYNCML_CONTTYPE_DEVINF_XML; ItemParams item; item.target = SYNCML_DEVINF_PATH_11; QList itemList; itemList.append(item); SyncActionData actionData; actionData.action = SYNCML_GET; actionData.meta = metaParams; actionData.items = itemList; ProtocolVersion version = DS_1_1; OperationMode opMode = MODE_CLIENT; QList dataStores; DeviceInfo devInfo; iCommandHandler->handleGet( actionData, version, opMode, dataStores, devInfo, iResponseGenerator ); } /*! \fn ServerCommandHandlerTest::testHandleStatus() */ void ServerCommandHandlerTest::testHandleStatus() { StatusParams status; status.data = IN_PROGRESS; iCommandHandler->handleStatus(&status); status.data = SUCCESS; iCommandHandler->handleStatus(&status); status.data = MULTIPLE_CHOICES; iCommandHandler->handleStatus(&status); status.data = BAD_REQUEST; iCommandHandler->handleStatus(&status); /// @todo slot for catching abort-signal status.data = COMMAND_FAILED; iCommandHandler->handleStatus(&status); status.data = (ResponseStatusCode)600; iCommandHandler->handleStatus(&status); } /*! \fn DataSync::ServerCommandHandlerTest::testResolveConflicts() */ void DataSync::ServerCommandHandlerTest::testResolveConflicts() { bool actual = iCommandHandler->resolveConflicts(); bool expexted = true; QCOMPARE(actual, expexted); } /*! \fn DataSync::ServerCommandHandlerTest::testAddUIDMapping() */ void DataSync::ServerCommandHandlerTest::testAddUIDMapping() { QString uid = "Foo"; MockStorage storagePlugin(0); SyncMode syncMode; ChangeLog* changeLog = new ChangeLog( iDbHandler->getDbHandle(), "device1", "sourcedb", DIRECTION_TWO_WAY ); MockSyncTarget syncTarget(changeLog, storagePlugin, syncMode, ""); MapParams mapParams; MapItem mapItem; mapItem.source = "foo"; mapItem.target = "bar"; QList mapItemList; mapItemList.append(mapItem); mapParams.mapItemList = mapItemList; /*ResponseStatusCode result = */iCommandHandler->handleMap(mapParams, syncTarget); // delete changeLog; // changeLog = NULL; // QVERIFY(syncTarget.iMappingCount == mapItemList.size()); iCommandHandler->removeUIDMapping(syncTarget, "foo"); } void DataSync::ServerCommandHandlerTest::testMapUID() { SyncTarget* target; if (!iTargets.isEmpty()) { target = iTargets.first(); } iCommandHandler->mapUID(*target, "foo"); } void DataSync::ServerCommandHandlerTest::testHandleSync() { SyncParams syncParams; int cmdId = 1; syncParams.cmdID = cmdId++; syncParams.targetDatabase = iLocalDb; syncParams.sourceDatabase = iRemoteDb; SyncActionData add; add.action = SYNCML_ADD; add.cmdID = cmdId++; ItemParams addItem; addItem.source = "fooid"; addItem.Data = "foodata"; add.items.append( addItem ); syncParams.actionList.append( add ); SyncActionData replace; replace.action = SYNCML_REPLACE; replace.cmdID = cmdId++; ItemParams replaceItem; replaceItem.source = "fooid2"; replaceItem.Data = "foodata2"; replace.items.append( replaceItem ); syncParams.actionList.append( replace ); SyncActionData del; del.action = SYNCML_DELETE; del.cmdID = cmdId++; ItemParams deleteItem; deleteItem.source = "fooid3"; del.items.append( deleteItem ); syncParams.actionList.append( del ); SyncTarget& target = *iTargets.first(); StorageHandler& storageHandler = *iStorageHandler; ResponseGenerator& responseGenerator = iResponseGenerator; LocalChanges changes; ConflictResolver ConflictResolver( changes, PREFER_CLIENT, MODE_SERVER ); iCommandHandler->handleSync( syncParams, target, storageHandler, responseGenerator, ConflictResolver, MODE_SERVER ); } void DataSync::ServerCommandHandlerTest::testHandleSyncLargeObject() { SyncTarget& target = *iTargets.first(); StorageHandler& storageHandler = *iStorageHandler; ResponseGenerator& responseGenerator = iResponseGenerator; LocalChanges changes; ConflictResolver ConflictResolver( changes, PREFER_CLIENT, MODE_SERVER ); SyncParams syncParams1; syncParams1.cmdID = 1; syncParams1.targetDatabase = iLocalDb; syncParams1.sourceDatabase = iRemoteDb; SyncActionData add1; add1.action = SYNCML_ADD; add1.cmdID = 2; add1.meta.size = 2; ItemParams addItem1; addItem1.source = "fooid"; addItem1.Data = QByteArray( "1" ); addItem1.moreData = true; add1.items.append( addItem1 ); syncParams1.actionList.append( add1 ); iCommandHandler->handleSync( syncParams1, target, storageHandler, responseGenerator, ConflictResolver, MODE_SERVER ); SyncParams syncParams2; syncParams2.cmdID = 1; syncParams2.targetDatabase = iLocalDb; syncParams2.sourceDatabase = iRemoteDb; SyncActionData add2; add2.action = SYNCML_ADD; add2.cmdID = 2; ItemParams addItem2; addItem2.source = "fooid"; addItem2.Data = QByteArray( "2" ); add2.items.append( addItem2 ); syncParams2.actionList.append( add2 ); iCommandHandler->handleSync( syncParams2, target, storageHandler, responseGenerator, ConflictResolver, MODE_SERVER ); } QTEST_MAIN(DataSync::ServerCommandHandlerTest) buteo-syncml-0.5.15/tests_meego/servertests/ServerCommandHandlerTest.h000066400000000000000000000052261433763642500262300ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SERVERCOMMANDHANDLERTEST_H #define SERVERCOMMANDHANDLERTEST_H #include #include "SyncAgentConfig.h" #include "ResponseGenerator.h" #include "Mock.h" namespace DataSync { class CommandHandler; class Transport; class StorageHandler; class DatabaseHandler; /** */ class ServerCommandHandlerTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testHandlerPut(); void testHandleGet(); void testHandleStatus(); void testResolveConflicts(); void testAddUIDMapping(); void testMapUID(); void testHandleSync(); void testHandleSyncLargeObject(); private: StoragePlugin* iStorage; Transport* iTransport; StorageHandler* iStorageHandler; CommandHandler* iCommandHandler; QString iRemoteDevice; QString iLocalDb; QString iRemoteDb; QList iTargets; ResponseGenerator iResponseGenerator; DatabaseHandler* iDbHandler; }; } #endif buteo-syncml-0.5.15/tests_meego/servertests/ServerCommandHandlerTest.pro000066400000000000000000000000401433763642500265660ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/servertests/ServerSessionHandlerTest.cpp000066400000000000000000000315231433763642500266270ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ServerSessionHandlerTest.h" #include #include "ServerSessionHandler.h" #include "SyncAgentConfig.h" #include "datatypes.h" #include "Mock.h" #include "ChangeLog.h" #include "SyncMLLogging.h" using namespace DataSync; static QString DBFILE( "/tmp/serversessionhandler.db" ); void ServerSessionHandlerTest::initTestCase() { iDbHandler = new DatabaseHandler( DBFILE ); iClientId = QString("clientId"); iConfig = new SyncAgentConfig(); QString localDb = "localcontacts"; iStorage = new MockStorage( localDb ); iTransport = new MockTransport(QString("data/transport_initrequest_nohdr.txt")); iConfig->setTransport(iTransport); iConfig->setDatabaseFilePath( DBFILE ); const SyncAgentConfig *tempConstConfig = iConfig; iHandler = new ServerSessionHandler(tempConstConfig); } void ServerSessionHandlerTest::cleanupTestCase() { delete iHandler; iHandler = 0; delete iConfig; iConfig = 0; delete iStorage; iStorage = NULL; delete iTransport; iTransport = 0; delete iDbHandler; iDbHandler = 0; } void ServerSessionHandlerTest::testHandleResponseHeader() { HeaderParams* params = new HeaderParams; params->sessionID = QString("sessionId"); params->targetDevice = QString("targetDevice"); params->sourceDevice= QString("sourceDevice"); params->msgID = 1; iHandler->handleHeaderElement( params ); } void ServerSessionHandlerTest::testSetGetSyncStatus() { SyncState setSyncState = SENDING_ITEMS; iHandler->setSyncState(setSyncState); SyncState receivedSyncState = iHandler->getSyncState(); QVERIFY(setSyncState == receivedSyncState); } void ServerSessionHandlerTest::testAddGetSyncTargets() { // DatabaseHandler* dbHandler = new DatabaseHandler( "/tmp/serversessionhandlertest2.db"); // iConfig = new SyncAgentConfig(); // iStorageHandler = new StorageHandler(); // iCommandHandler = new ServerCommandHandler( ); QString remoteDevice = "remotedevice"; QString localDb = "localcontacts"; SyncMode syncMode; ChangeLog* changeLog = new ChangeLog( remoteDevice, localDb, DIRECTION_TWO_WAY ); SyncTarget* target = new SyncTarget( changeLog, iStorage, syncMode, "fooanchor" ); iHandler->addSyncTarget(target); QList returnedTargets = iHandler->getSyncTargets(); QVERIFY(!returnedTargets.isEmpty()); } void ServerSessionHandlerTest::testSyncReceived() { bool result; iHandler->setSyncState(PREPARED); result = iHandler->syncReceived(); QVERIFY(result == false); iHandler->setSyncState(REMOTE_INIT); result = iHandler->syncReceived(); QVERIFY(result == true); iHandler->setSyncState(LOCAL_INIT); result = iHandler->syncReceived(); QVERIFY(result == true); iHandler->setSyncState(RECEIVING_ITEMS); result = iHandler->syncReceived(); QVERIFY(result == true); } void ServerSessionHandlerTest::testMapReceived() { bool result; iHandler->setSyncState(PREPARED); result = iHandler->mapReceived(); QVERIFY(result == false); iHandler->setSyncState(SENDING_ITEMS); result = iHandler->mapReceived(); QVERIFY(result == true); iHandler->setSyncState(RECEIVING_MAPPINGS); result = iHandler->mapReceived(); QVERIFY(result == true); } void ServerSessionHandlerTest::testFinalReceived() { iHandler->setSyncState(PREPARED); iHandler->finalReceived(); iHandler->setSyncState(SENDING_ITEMS); iHandler->finalReceived(); iHandler->setSyncState(RECEIVING_ITEMS); iHandler->finalReceived(); iHandler->setSyncState(RECEIVING_MAPPINGS); iHandler->finalReceived(); iHandler->setSyncState(REMOTE_INIT); iHandler->finalReceived(); iHandler->setSyncState(FINALIZING); iHandler->finalReceived(); } void ServerSessionHandlerTest::testMessageParsed() { iHandler->setSyncState(PREPARED); iHandler->messageParsed(); iHandler->setSyncState(SUSPENDING); iHandler->messageParsed(); iHandler->setSyncState(FINALIZING); iHandler->messageParsed(); } void ServerSessionHandlerTest::testResendPackage() { iHandler->setSyncState(PREPARED); iHandler->resendPackage(); iHandler->setSyncState(LOCAL_INIT); iHandler->resendPackage(); iHandler->setSyncState(SENDING_ITEMS); iHandler->resendPackage(); iHandler->setSyncState(FINALIZING); iHandler->resendPackage(); } void ServerSessionHandlerTest::testComposeServerModificationsPackage() { iHandler->composeServerModificationsPackage(); } void ServerSessionHandlerTest::testSyncFinished() { bool expected = iHandler->iSyncFinished; bool actual = iHandler->syncFinished(); QCOMPARE(expected, actual); } void ServerSessionHandlerTest::testHandleInformativeAlert() { CommandParams alertParams( CommandParams::COMMAND_ALERT ); alertParams.data = QString::number( DISPLAY ); ResponseStatusCode response = iHandler->handleInformativeAlert(alertParams); QVERIFY(response == NOT_IMPLEMENTED); alertParams.data = QString::number( NEXT_MESSAGE ); response = iHandler->handleInformativeAlert(alertParams); QVERIFY(response == SUCCESS); alertParams.data = QString::number( SLOW_SYNC ); response = iHandler->handleInformativeAlert(alertParams); QVERIFY(response == NOT_IMPLEMENTED); } void ServerSessionHandlerTest::testSyncInitiate() { ServerSessionHandler sessionHandler(iConfig); sessionHandler.initiateSync(); QCOMPARE(sessionHandler.getSyncState(), PREPARED); } void ServerSessionHandlerTest::testUnsupportedCalls() { iHandler->initiateSync(); SyncState prevState = iHandler->getSyncState(); // After unsupported calls the state should be the same as it was previously iHandler->suspendSync(); QCOMPARE(iHandler->getSyncState(), prevState); iHandler->resumeSync(); QCOMPARE(iHandler->getSyncState(), prevState); } void ServerSessionHandlerTest::testSyncAlert() { CommandParams params; SyncMode syncMode(TWO_WAY_SYNC); iHandler->setSyncState(PREPARED); QCOMPARE(iHandler->syncAlertReceived(syncMode, params), INCOMPLETE_COMMAND); QCOMPARE(iHandler->getSyncState(), REMOTE_INIT); iHandler->setSyncState(LOCAL_INIT); QCOMPARE(iHandler->syncAlertReceived(syncMode, params), INCOMPLETE_COMMAND); QCOMPARE(iHandler->getSyncState(), LOCAL_INIT); iHandler->setSyncState(NOT_PREPARED); QCOMPARE(iHandler->syncAlertReceived(syncMode, params), COMMAND_NOT_ALLOWED); QCOMPARE(iHandler->getSyncState(), NOT_PREPARED); } void ServerSessionHandlerTest::regression_NB166841_01() { // regression_NB166841_01: Test that target setup succeeds if source db uri, // target db uri and next anchor are present const QString sourceURI( "./target" ); const QString targetURI( "./source" ); const QString nextAnchor( "0" ); SyncAgentConfig config; config.setDatabaseFilePath( DBFILE ); ServerSessionHandler sessionHandler(&config); MockStorage* storage = new MockStorage( sourceURI ); sessionHandler.iStorages.append( storage ); SyncMode syncMode(DIRECTION_TWO_WAY, INIT_CLIENT, TYPE_SLOW); CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.target = sourceURI; item.source = targetURI; item.meta.anchor.next = nextAnchor; alert.items.append(item); ResponseStatusCode status = sessionHandler.setupTargetByClient(syncMode,alert); // Intentionally expecting REFRESH_REQUIRED inst. of SUCCESS. Would need // TYPE_FAST and valid last anchor otherwise. QCOMPARE( status, REFRESH_REQUIRED ); } void ServerSessionHandlerTest::regression_NB166841_02() { // regression_NB166841_02: Test that target setup succeeds if source db uri, // mime type and next anchor are present const QString sourceURI( "./target" ); const QString mimeURI( "text/x-vcalendar" ); const QString nextAnchor( "0" ); SyncAgentConfig config; config.setDatabaseFilePath( DBFILE ); ServerSessionHandler sessionHandler(&config); MockStorage* storage = new MockStorage( sourceURI, mimeURI ); sessionHandler.iStorages.append( storage ); SyncMode syncMode(DIRECTION_TWO_WAY, INIT_CLIENT, TYPE_SLOW); CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.source = sourceURI; item.meta.type = mimeURI; item.meta.anchor.next = nextAnchor; alert.items.append(item); ResponseStatusCode status = sessionHandler.setupTargetByClient(syncMode,alert); // Intentionally expecting REFRESH_REQUIRED inst. of SUCCESS. Would need // TYPE_FAST and valid last anchor otherwise. QCOMPARE( status, REFRESH_REQUIRED ); } void ServerSessionHandlerTest::regression_NB166841_03() { // regression_NB166841_03: Test that target setup fails if source db uri and // mime type are absent const QString mimeURI( "text/x-vcalendar" ); const QString nextAnchor( "0" ); SyncAgentConfig config; config.setDatabaseFilePath( DBFILE ); ServerSessionHandler sessionHandler(&config); SyncMode syncMode(DIRECTION_TWO_WAY, INIT_CLIENT, TYPE_SLOW); CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.meta.anchor.next = nextAnchor; alert.items.append(item); ResponseStatusCode status = sessionHandler.setupTargetByClient(syncMode,alert); QCOMPARE( status, INCOMPLETE_COMMAND ); } void ServerSessionHandlerTest::regression_NB166841_04() { // regression_NB166841_01: Test that target setup fails if next anchor is absent const QString sourceURI( "./target" ); const QString targetURI( "./source" ); SyncAgentConfig config; config.setDatabaseFilePath( DBFILE ); ServerSessionHandler sessionHandler(&config); MockStorage* storage = new MockStorage( sourceURI ); sessionHandler.iStorages.append( storage ); SyncMode syncMode(DIRECTION_TWO_WAY, INIT_CLIENT, TYPE_SLOW); CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.target = sourceURI; item.source = targetURI; alert.items.append(item); ResponseStatusCode status = sessionHandler.setupTargetByClient(syncMode,alert); QCOMPARE( status, INCOMPLETE_COMMAND ); } void ServerSessionHandlerTest::testSetClientRefresh() { QString remoteDevice = "aremotedevice"; QString localDb = "localdb"; const QString sourceURI( "./targetURI" ); const QString targetURI( "./sourceURI" ); const QString nextAnchor( "0" ); SyncMode syncMode(DIRECTION_FROM_CLIENT,INIT_CLIENT,TYPE_SLOW); SyncMode nextSyncMode(DIRECTION_FROM_CLIENT,INIT_CLIENT,TYPE_FAST); SyncAgentConfig config; config.setDatabaseFilePath( DBFILE ); ServerSessionHandler sessionHandler(&config); MockStorage* storage = new MockStorage( sourceURI ); sessionHandler.iStorages.append( storage ); ChangeLog* changeLog = new ChangeLog( remoteDevice, localDb, DIRECTION_FROM_CLIENT ); SyncTarget* target = new SyncTarget( changeLog, storage, syncMode, "lastanchor" ); sessionHandler.addSyncTarget(target); CommandParams alert( CommandParams::COMMAND_ALERT ); ItemParams item; item.target = sourceURI; item.source = targetURI; item.meta.anchor.next = nextAnchor; alert.items.append(item); ResponseStatusCode status = sessionHandler.setupTargetByClient(nextSyncMode,alert); QCOMPARE( status, REFRESH_REQUIRED ); } QTEST_MAIN(ServerSessionHandlerTest) buteo-syncml-0.5.15/tests_meego/servertests/ServerSessionHandlerTest.h000066400000000000000000000056771433763642500263070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SERVERSESSIONHNDLAERTEST_H #define SERVERSESSIONHNDLAERTEST_H #include #include #include "SyncTarget.h" #include "Mock.h" namespace DataSync { class ServerSessionHandler; class Transport; class SyncAgentConfig; class DatabaseHandler; } class ServerSessionHandlerTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testHandleResponseHeader(); void testSetGetSyncStatus(); void testAddGetSyncTargets(); void testSyncReceived(); void testMapReceived(); void testFinalReceived(); void testMessageParsed(); void testResendPackage(); void testComposeServerModificationsPackage(); void testSyncFinished(); void testHandleInformativeAlert(); void testSyncInitiate(); void testSyncAlert(); void testUnsupportedCalls(); void regression_NB166841_01(); void regression_NB166841_02(); void regression_NB166841_03(); void regression_NB166841_04(); void testSetClientRefresh(); private: StoragePlugin* iStorage; MockTransport* iTransport; DataSync::SyncAgentConfig* iConfig; DataSync::ServerSessionHandler* iHandler; //QList iTargets; QString iClientId; DatabaseHandler* iDbHandler; }; #endif /* SERVERSESSIONHNDLAERTEST_H */ buteo-syncml-0.5.15/tests_meego/servertests/ServerSessionHandlerTest.pro000066400000000000000000000000401433763642500266330ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/servertests/servertests.pro000077500000000000000000000002231433763642500242620ustar00rootroot00000000000000include(../tests_common.pri) TEMPLATE = subdirs SUBDIRS = \ ServerSessionHandlerTest.pro \ # Dead code? #ServerCommandHandlerTest.pro buteo-syncml-0.5.15/tests_meego/syncelementstests/000077500000000000000000000000001433763642500223525ustar00rootroot00000000000000buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLAddTest.cpp000077500000000000000000000042741433763642500255060ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include "SyncMLAddTest.h" #include "SyncMLAdd.h" #include "QtEncoder.h" using namespace DataSync; //QString add QString( void SyncMLAddTest::testSyncMLAdd() { SyncMLAdd add(10); QFile toXMLfile("data/testAdd.txt"); if(!toXMLfile.open(QIODevice::ReadOnly)) { QFAIL("Failed to open the file data/testAlert.txt"); } else { QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( add, output, true ) ); QCOMPARE( output,toXMLfile.readAll()); toXMLfile.close(); } } QTEST_MAIN(SyncMLAddTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLAddTest.h000066400000000000000000000034511433763642500251440ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLADDTEST_H #define SYNCMLADDTEST_H #include class SyncMLAddTest: public QObject { Q_OBJECT private slots: void testSyncMLAdd(); }; #endif // SYNCMLADDTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLAddTest.pro000066400000000000000000000000401433763642500255040ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLAlertTest.cpp000077500000000000000000000047431433763642500260660ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLAlertTest.h" #include #include "SyncMLAlert.h" #include "QtEncoder.h" #include "Fragments.h" #include "TestUtils.h" using namespace DataSync; void SyncMLAlertTest::testSyncMLAlert() { CommandParams alertParams( CommandParams::COMMAND_ALERT ); alertParams.cmdId = -1; alertParams.data = QString::number( SLOW_SYNC ); DataSync::ItemParams item; item.target = "card"; item.source = "addressbook"; item.meta.anchor.last = "12345678"; item.meta.anchor.next = "12345679"; item.meta.type = "text"; alertParams.items.append(item); SyncMLAlert alert(alertParams); QByteArray expected; QVERIFY( readFile( "data/testAlert.txt", expected ) ); QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( alert, output, true ) ); QCOMPARE(output, expected); } QTEST_MAIN(SyncMLAlertTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLAlertTest.h000077500000000000000000000034651433763642500255330ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLALERTTEST_H #define SYNCMLALERTTEST_H #include class SyncMLAlertTest: public QObject { Q_OBJECT private slots: void testSyncMLAlert(); }; #endif // SYNCMLALERTTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLAlertTest.pro000066400000000000000000000000401433763642500260630ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLBodyTest.cpp000066400000000000000000000035741433763642500257120ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLBody.h" #include "SyncMLBodyTest.h" #include void SyncMLBodyTest::testGetXML() { DataSync::SyncMLBody body; // QByteArray xmlBody = body.GetXML(); // qDebug() << xmlBody; // QVERIFY ( !xmlBody.isEmpty()); } QTEST_MAIN(SyncMLBodyTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLBodyTest.h000066400000000000000000000034571433763642500253570ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLBODYTEST_H #define SYNCMLBODYTEST_H #include class SyncMLBodyTest: public QObject { Q_OBJECT private slots: void testGetXML(); }; #endif // SYNCMLBODYTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLBodyTest.pro000066400000000000000000000000401433763642500257110ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLCmdObjectTest.cpp000066400000000000000000000061741433763642500266460ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLCmdObjectTest.h" #include #include "SyncMLCmdObject.h" using namespace DataSync; void SyncMLCmdObjectTest::testSetGetNameValue() { QString name1("objname"); QString value1("objvalue"); // Test constructor SyncMLCmdObject obj( name1, value1 ); QVERIFY( obj.getName() == name1 ); QVERIFY( obj.getValue() == value1 ); QString name2("anotherobjname"); QString value2("anotherobjvalue"); obj.setName( name2 ); QVERIFY( obj.getName() == name2 ); obj.setValue( value2 ); QVERIFY( obj.getValue() == value2 ); } void SyncMLCmdObjectTest::testSetGetCData() { SyncMLCmdObject obj; obj.setCDATA( true ); QVERIFY( obj.getCDATA() == true ); obj.setCDATA( false ); QVERIFY( obj.getCDATA() == false ); } void SyncMLCmdObjectTest::testAddGetAttribute() { SyncMLCmdObject obj; QString attrName( "attrName" ); QString attrValue( "attrValue" ); QVERIFY( obj.getAttributes().count() == 0 ); obj.addAttribute( attrName, attrValue ); QVERIFY( obj.getAttributes().count() == 1 ); QVERIFY( obj.getAttributes().value( attrName) == attrValue ); } void SyncMLCmdObjectTest::testAddGetChildren() { SyncMLCmdObject obj; QVERIFY( obj.getChildren().count() == 0 ); SyncMLCmdObject* child = new SyncMLCmdObject; //CID 23347 obj.addChild( child ); // Ownership is transferred. QVERIFY( obj.getChildren().count() == 1 ); QVERIFY( obj.getChildren()[0] == child ); child = 0; } QTEST_MAIN(SyncMLCmdObjectTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLCmdObjectTest.h000066400000000000000000000036501433763642500263070ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLCMDOBJECTTEST_H #define SYNCMLCMDOBJECTTEST_H #include class SyncMLCmdObjectTest: public QObject { Q_OBJECT; private slots: void testSetGetNameValue(); void testSetGetCData(); void testAddGetAttribute(); void testAddGetChildren(); }; #endif // SYNCMLCMDOBJECTTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLCmdObjectTest.pro000066400000000000000000000000401433763642500266460ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLCredTest.cpp000066400000000000000000000035001433763642500256570ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLCredTest.h" // @todo: SyncMLCred no longer generates basic and md5 data by itself, now it // is handled by AuthHelper. Proper tests should be written for it QTEST_MAIN(SyncMLCredTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLCredTest.h000066400000000000000000000034261433763642500253330ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLCREDTEST_H #define SYNCMLCREDTEST_H #include class SyncMLCredTest: public QObject { Q_OBJECT private slots: }; #endif // SYNCMLCREDTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLCredTest.pro000066400000000000000000000000401433763642500256710ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLDeleteTest.cpp000077500000000000000000000032531433763642500262140ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLDeleteTest.h" QTEST_MAIN(SyncMLDeleteTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLDeleteTest.h000077500000000000000000000034361433763642500256640ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLDELETETEST_H #define SYNCMLDELETETEST_H #include class SyncMLDeleteTest: public QObject { Q_OBJECT private slots: }; #endif // SYNCMLDELETETEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLDeleteTest.pro000066400000000000000000000000401433763642500262160ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLDevInfTest.cpp000077500000000000000000000044241433763642500261660ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLDevInfTest.h" #include "SyncMLDevInf.h" #include "StoragePlugin.h" #include "DeviceInfo.h" #include "datatypes.h" #include "TestUtils.h" #include "QtEncoder.h" using namespace DataSync; void SyncMLDevInfTest::testSyncMLDevInf() { QList pluginList; DeviceInfo devInfo; SyncMLDevInf devInf( pluginList, devInfo, SYNCML_1_2, ROLE_CLIENT); QByteArray expected; QVERIFY( readFile("data/testDevInf.txt", expected ) ); QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( devInf, output, true ) ); QCOMPARE( expected.simplified(), output.simplified() ); } QTEST_MAIN(SyncMLDevInfTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLDevInfTest.h000077500000000000000000000034721433763642500256350ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLDEVINFTEST_H #define SYNCMLDEVINFTEST_H #include class SyncMLDevInfTest: public QObject { Q_OBJECT private slots: void testSyncMLDevInf(); }; #endif // SYNCMLDEVINFTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLDevInfTest.pro000066400000000000000000000000401433763642500261670ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLHdrTest.cpp000066400000000000000000000061171433763642500255260ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLHdrTest.h" #include "SyncMLHdr.h" #include "QtEncoder.h" #include "Fragments.h" #include "TestUtils.h" using namespace DataSync; void SyncMLHdrTest::testSyncMLHdr_11() { HeaderParams headerParams; headerParams.verDTD = SYNCML_DTD_VERSION_1_1; headerParams.verProto = DS_VERPROTO_1_1; headerParams.msgID = 100; headerParams.sessionID = "12345"; headerParams.sourceDevice = "addressbook"; headerParams.targetDevice = "card"; headerParams.meta.maxMsgSize = 20; headerParams.meta.maxObjSize = 40; SyncMLHdr hdr(headerParams); QByteArray expected; QVERIFY( readFile( "data/SyncMLHdrTest_11.txt", expected ) ); QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( hdr, output, true ) ); QCOMPARE( output, expected ); } void SyncMLHdrTest::testSyncMLHdr_12() { HeaderParams headerParams; headerParams.verDTD = SYNCML_DTD_VERSION_1_2; headerParams.verProto = DS_VERPROTO_1_2; headerParams.msgID = 100; headerParams.sessionID = "12345"; headerParams.sourceDevice = "addressbook"; headerParams.targetDevice = "card"; headerParams.meta.maxMsgSize = 20; headerParams.meta.maxObjSize = 40; SyncMLHdr hdr(headerParams); QByteArray expected; QVERIFY( readFile( "data/SyncMLHdrTest.txt", expected ) ); QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( hdr, output, true ) ); QCOMPARE( output, expected ); } QTEST_MAIN(SyncMLHdrTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLHdrTest.h000066400000000000000000000035251433763642500251730ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLHDRTEST_H #define SYNCMLHDRTEST_H #include class SyncMLHdrTest: public QObject { Q_OBJECT; private slots: void testSyncMLHdr_11(); void testSyncMLHdr_12(); private: }; #endif // SYNCMLHDRTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLHdrTest.pro000066400000000000000000000000401433763642500255310ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLItemTest.cpp000077500000000000000000000102401433763642500257020ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLItemTest.h" #include "SyncMLItem.h" #include "SyncItemKey.h" #include "QtEncoder.h" #include "LibWbXML2Encoder.h" #include "TestUtils.h" #include "datatypes.h" #include using namespace DataSync; void SyncMLItemTest::testSyncMLItem() { SyncItemKey source("contacts"); SyncItemKey target("calendar"); SyncItemKey sourceParent("contactsparent"); SyncItemKey targetParent("calendarparent"); SyncMLItem item; item.insertSource(source); item.insertTarget(target); item.insertSourceParent(sourceParent); item.insertTargetParent(targetParent); QByteArray data; QVERIFY( readFile("data/testItem.txt", data ) ); QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( item, output, false ) ); QCOMPARE( output.simplified(), data.simplified() ); } void SyncMLItemTest::regressionNB188615_01() { // Regression test for NB#188615: make sure that data encoded // in UTF-8 is written properly when constructing XML using // Qt const unsigned char utf[] = { 0xC5, 0x9F, 0 }; QByteArray data( (const char*)utf ); SyncMLItem item; item.insertData( data ); QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( item, output, false ) ); QVERIFY( output.contains( data ) ); } void SyncMLItemTest::regressionNB188615_02() { // Regression test for NB#188615: make sure that data encoded // in UTF-8 is written properly when constructing XML using // libwbxml2 const unsigned char utf[] = { 0xC5, 0x9F, 0 }; QByteArray data( (const char*)utf ); SyncMLItem item; // Add namespace attribute, needed by libwbxml2 item.addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_SYNCML12 ); item.insertData( data ); LibWbXML2Encoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( item, SYNCML_1_2, output, false ) ); QVERIFY( output.contains( data ) ); } void SyncMLItemTest::regressionNB188615_03() { // Regression test for NB#188615: make sure that data encoded // in UTF-8 is written properly when constructing WnXML using // libwbxml2 const unsigned char utf[] = { 0xC5, 0x9F, 0 }; QByteArray data( (const char*)utf ); SyncMLItem item; // Add namespace attribute, needed by libwbxml2 item.addAttribute( XML_NAMESPACE, XML_NAMESPACE_VALUE_SYNCML12 ); item.insertData( data ); LibWbXML2Encoder encoder; QByteArray output; QVERIFY( encoder.encodeToWbXML( item, SYNCML_1_2, output ) ); QVERIFY( output.contains( data ) ); } QTEST_MAIN(SyncMLItemTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLItemTest.h000077500000000000000000000036261433763642500253610ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLITEMTEST_H #define SYNCMLITEMTEST_H #include class SyncMLItemTest: public QObject { Q_OBJECT private slots: void testSyncMLItem(); void regressionNB188615_01(); void regressionNB188615_02(); void regressionNB188615_03(); }; #endif // SYNCMLITEMTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLItemTest.pro000066400000000000000000000000401433763642500257120ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLLocalChangeTest.cpp000077500000000000000000000032651433763642500271550ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLLocalChangeTest.h" QTEST_MAIN(SyncMLLocalChangeTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLLocalChangeTest.h000077500000000000000000000034621433763642500266210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLLOCALCHANGETEST_H #define SYNCMLLOCALCHANGETEST_H #include class SyncMLLocalChangeTest: public QObject { Q_OBJECT private slots: }; #endif // SYNCMLLOCALCHANGETEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLLocalChangeTest.pro000066400000000000000000000000401433763642500271540ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMapTest.cpp000066400000000000000000000054611433763642500255270ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMapTest.h" #include "datatypes.h" #include "SyncMLMap.h" #include "SyncMLMapItem.h" #include "QtEncoder.h" #include void SyncMLMapTest::testBasic() { DataSync::SyncMLMapItem* mapItem = new DataSync::SyncMLMapItem("guid", "luid"); DataSync::SyncMLMap* map = new DataSync::SyncMLMap( 1, "target", "source" ); QVERIFY(mapItem != 0); QVERIFY(map != 0); map->addChild(mapItem); QByteArray expected = "1targetsourceguidluid"; DataSync::QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( *map, output, true ) ); output = output.replace(QByteArray("\r"), QByteArray("")); output = output.replace(QByteArray("\n"), QByteArray("")); output = output.replace(QByteArray("\t"), QByteArray("")); output = output.replace(QByteArray(" "), QByteArray("")); expected = expected.replace(QByteArray(" "), QByteArray("")); delete map; map = NULL; QCOMPARE(output, expected); } QTEST_MAIN(SyncMLMapTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMapTest.h000066400000000000000000000034511433763642500251710ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMAPTEST_H #define SYNCMLMAPTEST_H #include class SyncMLMapTest: public QObject { Q_OBJECT private slots: void testBasic(); }; #endif // SYNCMLMAPTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMapTest.pro000066400000000000000000000000401433763642500255310ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMessageParserTest.cpp000066400000000000000000000606051433763642500275540ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMessageParserTest.h" #include #include #include #include "SyncMLMessageParser.h" #include "TestUtils.h" #include "RemoteDeviceInfo.h" using namespace DataSync; void SyncMLMessageParserTest::testResp1() { SyncMLMessageParser parser; QByteArray data; QVERIFY( readFile( "data/resp.txt", data ) ); QBuffer buffer(&data ); QVERIFY( buffer.open( QIODevice::ReadOnly ) ); QSignalSpy parsingSpy( &parser, SIGNAL(parsingComplete(bool)) ); QSignalSpy errorSpy( &parser, SIGNAL(parsingError(DataSync::ParserError)) ); parser.parseResponse( &buffer, true ); buffer.close(); QCOMPARE( parsingSpy.count(), 1 ); QCOMPARE( errorSpy.count(), 0 ); QList fragments = parser.takeFragments(); // Header QVERIFY( !fragments.isEmpty() ); DataSync::Fragment* fragment = fragments.takeFirst(); QCOMPARE( fragment->fragmentType, Fragment::FRAGMENT_HEADER ); HeaderParams* header = static_cast( fragment ); QCOMPARE( header->sessionID, QString("1230022352") ); QCOMPARE( header->msgID, 5 ); QCOMPARE( header->targetDevice, QString("sc-pim-75af2bff-3a5e-4cba-affb-4c555b9ee740")); QCOMPARE( header->sourceDevice, QString("http://82.77.123.71:8080/services/syncml")); QCOMPARE( header->respURI, QString("http://82.77.123.71:8080/services/syncml?s=RYHmRQAA&srv_id=002")); delete header; header = NULL; // Results QVERIFY( !fragments.isEmpty() ); fragment = fragments.takeFirst(); QCOMPARE( fragment->fragmentType, Fragment::FRAGMENT_RESULTS ); ResultsParams* results = static_cast( fragment ); delete results; results = NULL; // Status QVERIFY( !fragments.isEmpty() ); fragment = fragments.takeFirst(); QCOMPARE( fragment->fragmentType, Fragment::FRAGMENT_STATUS ); StatusParams* status = static_cast( fragment ); QCOMPARE(status->cmdId,1); QCOMPARE(status->data,SUCCESS); QCOMPARE(status->msgRef,5); QCOMPARE(status->cmdRef,0); QCOMPARE(status->cmd,QString(SYNCML_ELEMENT_SYNCHDR)); QCOMPARE(status->targetRef,QString("http://localhost:8080/funambol/ds/card")); QCOMPARE(status->sourceRef,QString("sc-pim-75af2bff-3a5e-4cba-affb-4c555b9ee740")); QVERIFY(!status->items.isEmpty()); QCOMPARE(status->items.at(0).target,QString("note")); QCOMPARE(status->items.at(0).source,QString("memo")); QCOMPARE(status->chal.meta.type,QString("syncml:auth-md5")); QCOMPARE(status->chal.meta.format,QString("b64")); QCOMPARE(status->chal.meta.nextNonce,QString("ZG9iZWhhdmUNCg==")); delete status; status = NULL; // Alert QVERIFY( !fragments.isEmpty() ); fragment = fragments.takeFirst(); QCOMPARE( fragment->fragmentType, Fragment::FRAGMENT_COMMAND ); CommandParams* command = static_cast( fragment ); QVERIFY( command->commandType == CommandParams::COMMAND_ALERT ); QCOMPARE(command->cmdId,2); QCOMPARE(command->data,QString( "201" ) ); QVERIFY(!command->items.isEmpty()); QCOMPARE(command->items.first().target,QString("addressbook")); QCOMPARE(command->items.first().source,QString("card")); QCOMPARE(command->items.first().meta.anchor.next,QString("1232981790235")); QCOMPARE(command->items.first().meta.anchor.last,QString("1232366487448")); delete command; command = NULL; // Sync QVERIFY( !fragments.isEmpty() ); fragment = fragments.takeFirst(); QCOMPARE( fragment->fragmentType, Fragment::FRAGMENT_SYNC ); SyncParams* sync = static_cast( fragment ); QCOMPARE(sync->cmdId,3); QCOMPARE(sync->target,QString("addressbook")); QCOMPARE(sync->source,QString("card")); QCOMPARE( sync->commands.count(), 3 ); verifyAdd( sync->commands.at(0) ); verifyReplace( sync->commands.at(1) ); verifyDelete( sync->commands.at(2) ); delete sync; sync = NULL; // Map QVERIFY( !fragments.isEmpty() ); fragment = fragments.takeFirst(); QCOMPARE( fragment->fragmentType, Fragment::FRAGMENT_MAP ); MapParams* map = static_cast( fragment ); QCOMPARE(map->cmdId,7); QCOMPARE(map->target,QString("http://www.datasync.org/servlet/syncit")); QCOMPARE(map->source,QString("IMEI:001004FF1234567")); QCOMPARE(map->mapItems.count(), 3 ); QCOMPARE(map->mapItems.at(0).target,QString("./0123456789ABCDEF")); QCOMPARE(map->mapItems.at(0).source,QString("./01")); QCOMPARE(map->mapItems.at(1).target,QString("./0123456789ABCDF0")); QCOMPARE(map->mapItems.at(1).source,QString("./02")); QCOMPARE(map->mapItems.at(2).target,QString("./0123456789ABCDF1")); QCOMPARE(map->mapItems.at(2).source,QString("./03")); delete map; map = NULL; // Final QVERIFY( fragments.isEmpty() ); QList signal1 = parsingSpy.at(0); QCOMPARE( signal1.count(), 1 ); bool final = signal1.at(0).toBool(); QCOMPARE( final, true ); } void SyncMLMessageParserTest::testInvalid1() { SyncMLMessageParser parser; QSignalSpy parsingSpy( &parser, SIGNAL(parsingComplete(bool)) ); QSignalSpy errorSpy( &parser, SIGNAL(parsingError(DataSync::ParserError)) ); QByteArray data; QVERIFY( readFile( "data/respinvalid1.txt", data ) ); QBuffer buffer(&data ); QVERIFY( buffer.open( QIODevice::ReadOnly ) ); parser.parseResponse( &buffer, true ); buffer.close(); QVERIFY( readFile( "data/respinvalid2.txt", data ) ); buffer.setBuffer(&data); QVERIFY( buffer.open( QIODevice::ReadOnly ) ); parser.parseResponse( &buffer, true ); buffer.close(); QVERIFY( readFile( "data/respinvalid3.txt", data ) ); buffer.setBuffer(&data); QVERIFY( buffer.open( QIODevice::ReadOnly ) ); parser.parseResponse( &buffer, true ); buffer.close(); QVERIFY( readFile( "data/respinvalid4.txt", data ) ); buffer.setBuffer(&data); QVERIFY( buffer.open( QIODevice::ReadOnly ) ); parser.parseResponse( &buffer, true ); buffer.close(); QVERIFY( readFile( "data/respinvalid5.txt", data ) ); buffer.setBuffer(&data); QVERIFY( buffer.open( QIODevice::ReadOnly ) ); parser.parseResponse( &buffer, true ); buffer.close(); QVERIFY( readFile( "data/respinvalid6.txt", data ) ); buffer.setBuffer(&data); QVERIFY( buffer.open( QIODevice::ReadOnly ) ); parser.parseResponse( &buffer, true ); buffer.close(); QCOMPARE( parsingSpy.count(), 0 ); QCOMPARE( errorSpy.count(), 6 ); } void SyncMLMessageParserTest::verifyAdd( const DataSync::CommandParams& aData ) { QCOMPARE(aData.cmdId,4); QCOMPARE(aData.meta.type,QString("text/x-vcard")); QCOMPARE(aData.items.count(), 1 ); QCOMPARE(aData.items[0].source, QString( "0" ) ); QCOMPARE(aData.items[0].sourceParent, QString( "1" ) ); QCOMPARE(aData.items[0].data.simplified(), QString( "BEGIN:VCARD VERSION:2.1 N:Lahtela;Tatu;;; FN:Lahtela, Tatu TEL;TYPE=PREF:+35840 7532165 EMAIL;INTERNET:tatu.lahtela TITLE: ORG:; END:VCARD") ); } void SyncMLMessageParserTest::verifyReplace( const DataSync::CommandParams& aData ) { QCOMPARE(aData.cmdId,5); QCOMPARE(aData.meta.type,QString("x-type/x-subtype")); QCOMPARE(aData.items.count(), 1); QCOMPARE(aData.items.at(0).target,QString("244")); QCOMPARE(aData.items.at(0).targetParent,QString("245")); QCOMPARE(aData.items.at(0).data,QString("ReplaceData")); } void SyncMLMessageParserTest::verifyDelete( const DataSync::CommandParams& aData ) { QCOMPARE(aData.cmdId,6); QCOMPARE(aData.meta.type,QString("x-type/x-subtype2")); QCOMPARE(aData.items.at(0).target,QString("128")); } void SyncMLMessageParserTest::testDevInf11() { QByteArray data; QVERIFY( readFile( "data/devinf01.txt", data ) ); QBuffer buffer( &data ); buffer.open( QIODevice::ReadOnly ); buffer.seek( 0 ); SyncMLMessageParser parser; parser.iReader.setDevice( &buffer ); DevInfItemParams params; parser.readDevInf( params ); buffer.close(); QCOMPARE( parser.iError, PARSER_ERROR_LAST ); const DeviceInfo& devInf = params.devInfo.deviceInfo(); QCOMPARE( devInf.getManufacturer(), QString( "FooManufacturer" ) ); QCOMPARE( devInf.getModel(), QString( "FooModel" ) ); QCOMPARE( devInf.getOEM(), QString( "FooOEM" ) ); QCOMPARE( devInf.getFirmwareVersion(), QString( "FwVersion" ) ); QCOMPARE( devInf.getSoftwareVersion(), QString( "v 21.0.045") ); QCOMPARE( devInf.getHardwareVersion(), QString( "HwVersion" ) ); QCOMPARE( devInf.getDeviceID(), QString( "IMEI:356064034969473" ) ); QVERIFY( params.devInfo.getSupportsLargeObjs() ); QVERIFY( params.devInfo.getSupportsNumberOfChanges() ); QVERIFY( params.devInfo.getSupportsUTC() ); const QList& datastores = params.devInfo.datastores(); QCOMPARE( datastores.count(), 3 ); QCOMPARE( datastores[0].getSourceURI(), QString( "./Contacts" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredRx().iType, QString( "text/x-vcard" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredRx().iVersion, QString( "2.1" ) ); QCOMPARE( datastores[0].formatInfo().rx().count(), 1 ); QCOMPARE( datastores[0].formatInfo().rx().at(0).iType, QString( "text/vcard" ) ); QCOMPARE( datastores[0].formatInfo().rx().at(0).iVersion, QString( "3.0" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredTx().iType, QString( "text/x-vcard" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredTx().iVersion, QString( "2.1" ) ); QVERIFY( !datastores[0].getSupportsHierarchicalSync() ); QCOMPARE( datastores[0].formatInfo().tx().count(), 0 ); QCOMPARE( datastores[0].syncCaps().count(), 5 ); QVERIFY( datastores[0].syncCaps().at(0) == SYNCTYPE_TWOWAY ); QVERIFY( datastores[0].syncCaps().at(1) == SYNCTYPE_TWOWAYSLOW ); QVERIFY( datastores[0].syncCaps().at(2) == SYNCTYPE_FROMCLIENT ); QVERIFY( datastores[0].syncCaps().at(3) == SYNCTYPE_FROMSERVER ); QVERIFY( datastores[0].syncCaps().at(4) == SYNCTYPE_SERVERALERTED ); QCOMPARE( datastores[0].ctCaps().count(), 1 ); QCOMPARE( datastores[0].ctCaps().at(0).getFormat().iType, QString( "text/x-vcard" ) ); QCOMPARE( datastores[0].ctCaps().at(0).properties().count(), 28 ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iName, QString( "TEL" ) ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iParameters.count(), 1 ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iParameters.at(0).iValues.count(), 8 ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iParameters.at(0).iValues.at(7), QString( "VIDEO") ); QCOMPARE( datastores[1].getSourceURI(), QString( "./Calendar" ) ); QCOMPARE( datastores[1].formatInfo().getPreferredRx().iType, QString( "text/x-vcalendar" ) ); QCOMPARE( datastores[1].formatInfo().getPreferredRx().iVersion, QString( "1.0" ) ); QCOMPARE( datastores[1].formatInfo().rx().count(), 0 ); QCOMPARE( datastores[1].formatInfo().getPreferredTx().iType, QString( "text/x-vcalendar" ) ); QCOMPARE( datastores[1].formatInfo().getPreferredTx().iVersion, QString( "1.0" ) ); QVERIFY( !datastores[1].getSupportsHierarchicalSync() ); QCOMPARE( datastores[1].formatInfo().tx().count(), 0 ); QCOMPARE( datastores[1].syncCaps().count(), 5 ); QVERIFY( datastores[1].syncCaps().at(0) == SYNCTYPE_TWOWAY ); QVERIFY( datastores[1].syncCaps().at(1) == SYNCTYPE_TWOWAYSLOW ); QVERIFY( datastores[1].syncCaps().at(2) == SYNCTYPE_FROMCLIENT ); QVERIFY( datastores[1].syncCaps().at(3) == SYNCTYPE_FROMSERVER ); QVERIFY( datastores[1].syncCaps().at(4) == SYNCTYPE_SERVERALERTED ); QCOMPARE( datastores[1].ctCaps().count(), 1 ); QCOMPARE( datastores[1].ctCaps().at(0).getFormat().iType, QString( "text/x-vcalendar" ) ); QCOMPARE( datastores[1].ctCaps().at(0).properties().count(), 35 ); QCOMPARE( datastores[2].getSourceURI(), QString( "./Notepad" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredRx().iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredRx().iVersion, QString( "1.0" ) ); QCOMPARE( datastores[2].formatInfo().rx().count(), 1 ); QCOMPARE( datastores[2].formatInfo().rx().at(0).iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].formatInfo().rx().at(0).iVersion, QString( "1.0" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredTx().iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredTx().iVersion, QString( "1.0" ) ); QVERIFY( !datastores[2].getSupportsHierarchicalSync() ); QCOMPARE( datastores[2].formatInfo().tx().count(), 0 ); QCOMPARE( datastores[2].syncCaps().count(), 5 ); QVERIFY( datastores[2].syncCaps().at(0) == SYNCTYPE_TWOWAY ); QVERIFY( datastores[2].syncCaps().at(1) == SYNCTYPE_TWOWAYSLOW ); QVERIFY( datastores[2].syncCaps().at(2) == SYNCTYPE_FROMCLIENT ); QVERIFY( datastores[2].syncCaps().at(3) == SYNCTYPE_FROMSERVER ); QVERIFY( datastores[2].syncCaps().at(4) == SYNCTYPE_SERVERALERTED ); QCOMPARE( datastores[2].ctCaps().count(), 1 ); QCOMPARE( datastores[2].ctCaps().at(0).getFormat().iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].ctCaps().at(0).properties().count(), 1 ); QVERIFY( datastores[2].ctCaps().at(0).properties().at(0).iName.isEmpty() ); QCOMPARE( datastores[2].ctCaps().at(0).properties().at(0).iType, QString( "chr" ) ); QCOMPARE( datastores[2].ctCaps().at(0).properties().at(0).iSize, 0 ); } void SyncMLMessageParserTest::testDevInf12() { QByteArray data; QVERIFY( readFile( "data/devinf02.txt", data ) ); QBuffer buffer( &data ); buffer.open( QIODevice::ReadOnly ); buffer.seek( 0 ); SyncMLMessageParser parser; parser.iReader.setDevice( &buffer ); DevInfItemParams params; parser.readDevInf( params ); buffer.close(); QCOMPARE( parser.iError, PARSER_ERROR_LAST ); QCOMPARE( params.devInfo.deviceInfo().getManufacturer(), QString( "FooManufacturer" ) ); QCOMPARE( params.devInfo.deviceInfo().getModel(), QString( "FooModel" ) ); QCOMPARE( params.devInfo.deviceInfo().getOEM(), QString( "FooOEM" ) ); QCOMPARE( params.devInfo.deviceInfo().getFirmwareVersion(), QString( "FwVersion" ) ); QCOMPARE( params.devInfo.deviceInfo().getSoftwareVersion(), QString( "v 21.0.045") ); QCOMPARE( params.devInfo.deviceInfo().getHardwareVersion(), QString( "HwVersion" ) ); QCOMPARE( params.devInfo.deviceInfo().getDeviceID(), QString( "IMEI:356064034969473" ) ); QVERIFY( params.devInfo.getSupportsLargeObjs() ); QVERIFY( params.devInfo.getSupportsNumberOfChanges() ); QVERIFY( params.devInfo.getSupportsUTC() ); const QList& datastores = params.devInfo.datastores(); QCOMPARE( datastores.count(), 3 ); QCOMPARE( datastores[0].getSourceURI(), QString( "./Contacts" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredRx().iType, QString( "text/x-vcard" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredRx().iVersion, QString( "2.1" ) ); QCOMPARE( datastores[0].formatInfo().rx().count(), 1 ); QCOMPARE( datastores[0].formatInfo().rx().at(0).iType, QString( "text/vcard" ) ); QCOMPARE( datastores[0].formatInfo().rx().at(0).iVersion, QString( "3.0" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredTx().iType, QString( "text/x-vcard" ) ); QCOMPARE( datastores[0].formatInfo().getPreferredTx().iVersion, QString( "2.1" ) ); QVERIFY( datastores[0].getSupportsHierarchicalSync() ); QCOMPARE( datastores[0].formatInfo().tx().count(), 0 ); QCOMPARE( datastores[0].syncCaps().count(), 5 ); QVERIFY( datastores[0].syncCaps().at(0) == SYNCTYPE_TWOWAY ); QVERIFY( datastores[0].syncCaps().at(1) == SYNCTYPE_TWOWAYSLOW ); QVERIFY( datastores[0].syncCaps().at(2) == SYNCTYPE_FROMCLIENT ); QVERIFY( datastores[0].syncCaps().at(3) == SYNCTYPE_FROMSERVER ); QVERIFY( datastores[0].syncCaps().at(4) == SYNCTYPE_SERVERALERTED ); QCOMPARE( datastores[0].ctCaps().count(), 1 ); QCOMPARE( datastores[0].ctCaps().at(0).getFormat().iType, QString( "text/x-vcard" ) ); QCOMPARE( datastores[0].ctCaps().at(0).properties().count(), 24 ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iName, QString( "TEL" ) ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iParameters.count(), 1 ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iParameters.at(0).iName, QString( "TYPE") ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iParameters.at(0).iValues.count(), 8 ); QCOMPARE( datastores[0].ctCaps().at(0).properties().at(6).iParameters.at(0).iValues.at(7), QString( "CAR") ); QCOMPARE( datastores[1].getSourceURI(), QString( "./Calendar" ) ); QCOMPARE( datastores[1].formatInfo().getPreferredRx().iType, QString( "text/x-vcalendar" ) ); QCOMPARE( datastores[1].formatInfo().getPreferredRx().iVersion, QString( "1.0" ) ); QCOMPARE( datastores[1].formatInfo().rx().count(), 0 ); QCOMPARE( datastores[1].formatInfo().getPreferredTx().iType, QString( "text/x-vcalendar" ) ); QCOMPARE( datastores[1].formatInfo().getPreferredTx().iVersion, QString( "1.0" ) ); QVERIFY( !datastores[1].getSupportsHierarchicalSync() ); QCOMPARE( datastores[1].formatInfo().tx().count(), 0 ); QCOMPARE( datastores[1].syncCaps().count(), 5 ); QVERIFY( datastores[1].syncCaps().at(0) == SYNCTYPE_TWOWAY ); QVERIFY( datastores[1].syncCaps().at(1) == SYNCTYPE_TWOWAYSLOW ); QVERIFY( datastores[1].syncCaps().at(2) == SYNCTYPE_FROMCLIENT ); QVERIFY( datastores[1].syncCaps().at(3) == SYNCTYPE_FROMSERVER ); QVERIFY( datastores[1].syncCaps().at(4) == SYNCTYPE_SERVERALERTED ); QCOMPARE( datastores[1].ctCaps().count(), 1 ); QCOMPARE( datastores[1].ctCaps().at(0).getFormat().iType, QString( "text/x-vcalendar" ) ); QCOMPARE( datastores[1].ctCaps().at(0).properties().count(), 25 ); QVERIFY( !datastores[1].ctCaps().at(0).properties().at(0).iNoTruncate ); QCOMPARE( datastores[2].getSourceURI(), QString( "./Notepad" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredRx().iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredRx().iVersion, QString( "1.0" ) ); QCOMPARE( datastores[2].formatInfo().rx().count(), 1 ); QCOMPARE( datastores[2].formatInfo().rx().at(0).iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].formatInfo().rx().at(0).iVersion, QString( "1.0" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredTx().iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].formatInfo().getPreferredTx().iVersion, QString( "1.0" ) ); QVERIFY( datastores[2].getSupportsHierarchicalSync() ); QCOMPARE( datastores[2].formatInfo().tx().count(), 0 ); QCOMPARE( datastores[2].syncCaps().count(), 5 ); QVERIFY( datastores[2].syncCaps().at(0) == SYNCTYPE_TWOWAY ); QVERIFY( datastores[2].syncCaps().at(1) == SYNCTYPE_TWOWAYSLOW ); QVERIFY( datastores[2].syncCaps().at(2) == SYNCTYPE_FROMCLIENT ); QVERIFY( datastores[2].syncCaps().at(3) == SYNCTYPE_FROMSERVER ); QVERIFY( datastores[2].syncCaps().at(4) == SYNCTYPE_SERVERALERTED ); QCOMPARE( datastores[2].ctCaps().count(), 1 ); QCOMPARE( datastores[2].ctCaps().at(0).getFormat().iType, QString( "text/plain" ) ); QCOMPARE( datastores[2].ctCaps().at(0).properties().count(), 1 ); QCOMPARE( datastores[2].ctCaps().at(0).properties().at(0).iName, QString( "Note" ) ); QCOMPARE( datastores[2].ctCaps().at(0).properties().at(0).iType, QString( "chr" ) ); QCOMPARE( datastores[2].ctCaps().at(0).properties().at(0).iSize, 0 ); QCOMPARE( datastores[2].ctCaps().at(0).properties().at(0).iMaxOccur, 5 ); QVERIFY( datastores[2].ctCaps().at(0).properties().at(0).iNoTruncate ); } void SyncMLMessageParserTest::testSubcommands() { QByteArray data; QVERIFY( readFile( "data/subcommands01.txt", data ) ); QBuffer buffer( &data ); buffer.open( QIODevice::ReadOnly ); buffer.seek( 0 ); SyncMLMessageParser parser; parser.parseResponse( &buffer, true ); QCOMPARE( parser.iError, PARSER_ERROR_LAST ); QList fragments = parser.takeFragments(); QCOMPARE( fragments.count(), 6 ); QVERIFY( fragments[0]->fragmentType == Fragment::FRAGMENT_HEADER ); QVERIFY( fragments[1]->fragmentType == Fragment::FRAGMENT_COMMAND ); QVERIFY( static_cast(fragments[1])->commandType == CommandParams::COMMAND_ALERT ); QVERIFY( fragments[2]->fragmentType == Fragment::FRAGMENT_COMMAND ); CommandParams* get = static_cast(fragments[2]); QVERIFY( get->commandType == CommandParams::COMMAND_GET ); QVERIFY( fragments[3]->fragmentType == Fragment::FRAGMENT_COMMAND ); CommandParams* atomic = static_cast(fragments[3]); QVERIFY( atomic->commandType == CommandParams::COMMAND_ATOMIC ); QCOMPARE( atomic->subCommands.count(), 2 ); QVERIFY( atomic->subCommands[0].commandType == CommandParams::COMMAND_ALERT ); QVERIFY( atomic->subCommands[1].commandType == CommandParams::COMMAND_ADD ); QVERIFY( fragments[4]->fragmentType == Fragment::FRAGMENT_COMMAND ); CommandParams* sequence = static_cast(fragments[4]); QVERIFY( sequence->commandType == CommandParams::COMMAND_SEQUENCE ); QCOMPARE( sequence->subCommands.count(), 2 ); QVERIFY( sequence->subCommands[0].commandType == CommandParams::COMMAND_ALERT ); QVERIFY( sequence->subCommands[1].commandType == CommandParams::COMMAND_ADD ); QVERIFY( fragments[5]->fragmentType == Fragment::FRAGMENT_SYNC ); SyncParams* sync = static_cast(fragments[5]); QCOMPARE( sync->commands.count(), 3 ); QVERIFY( sync->commands[0].commandType == CommandParams::COMMAND_ADD ); QVERIFY( sync->commands[1].commandType == CommandParams::COMMAND_ADD ); QVERIFY( sync->commands[2].commandType == CommandParams::COMMAND_ATOMIC ); atomic = &sync->commands[2]; QCOMPARE( atomic->subCommands.count(), 2 ); QVERIFY( atomic->subCommands[0].commandType == CommandParams::COMMAND_ADD ); QVERIFY( atomic->subCommands[1].commandType == CommandParams::COMMAND_ADD ); qDeleteAll(fragments); fragments.clear(); } void SyncMLMessageParserTest::testEmbeddedXML() { QByteArray data; QVERIFY( readFile( "data/resp2.txt", data ) ); QBuffer buffer( &data ); buffer.open( QIODevice::ReadOnly ); buffer.seek( 0 ); SyncMLMessageParser parser; const QString expected( "276" ); parser.parseResponse( &buffer, true ); QCOMPARE( parser.iError, PARSER_ERROR_LAST ); QList fragments = parser.takeFragments(); QCOMPARE( fragments.count(), 2 ); QVERIFY( fragments[0]->fragmentType == Fragment::FRAGMENT_HEADER ); QVERIFY( fragments[1]->fragmentType == Fragment::FRAGMENT_STATUS ); StatusParams* status = static_cast( fragments[1] ); QCOMPARE( status->items.count(), 1 ); QCOMPARE( status->items.first().data, expected ); } QTEST_MAIN(SyncMLMessageParserTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMessageParserTest.h000066400000000000000000000042741433763642500272210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMESSAGEBUILDERTEST_H #define SYNCMLMESSAGEBUILDERTEST_H #include #include "Fragments.h" class SyncMLMessageParserTest : public QObject { Q_OBJECT; public: private slots: void testResp1(); void testInvalid1(); void testDevInf11(); void testDevInf12(); void testSubcommands(); void testEmbeddedXML(); private: void verifyAdd( const DataSync::CommandParams& aData ); void verifyReplace( const DataSync::CommandParams& aData ); void verifyDelete( const DataSync::CommandParams& aData ); }; #endif // SYNCMLMESSAGEBUILDERTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMessageParserTest.pro000066400000000000000000000000401433763642500275550ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMessageTest.cpp000077500000000000000000000034001433763642500263700ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLMessageTest.h" void SyncMLMessageTest::testSyncMLMessage() { // @TODO add the actual test . } QTEST_MAIN(SyncMLMessageTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMessageTest.h000077500000000000000000000034771433763642500260530ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLMESSAGETEST_H #define SYNCMLMESSAGETEST_H #include class SyncMLMessageTest: public QObject { Q_OBJECT private slots: void testSyncMLMessage(); }; #endif // SYNCMLMESSAGETEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLMessageTest.pro000066400000000000000000000000401433763642500264000ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLPutTest.cpp000077500000000000000000000032451433763642500255630ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLPutTest.h" QTEST_MAIN(SyncMLPutTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLPutTest.h000077500000000000000000000034221433763642500252250ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLPUTTEST_H #define SYNCMLPUTTEST_H #include class SyncMLPutTest: public QObject { Q_OBJECT private slots: }; #endif // SYNCMLPUTTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLPutTest.pro000066400000000000000000000000401433763642500255640ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLReplaceTest.cpp000077500000000000000000000032551433763642500263670ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLReplaceTest.h" QTEST_MAIN(SyncMLReplaceTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLReplaceTest.h000077500000000000000000000034421433763642500260320ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLREPLACETEST_H #define SYNCMLREPLACETEST_H #include class SyncMLReplaceTest: public QObject { Q_OBJECT private slots: }; #endif // SYNCMLREPLACETEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLReplaceTest.pro000066400000000000000000000000401433763642500263670ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLResultsTest.cpp000077500000000000000000000032551433763642500264550ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLResultsTest.h" QTEST_MAIN(SyncMLResultsTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLResultsTest.h000077500000000000000000000034421433763642500261200ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLRESULTSTEST_H #define SYNCMLRESULTSTEST_H #include class SyncMLResultsTest: public QObject { Q_OBJECT private slots: }; #endif // SYNCMLRESULTSTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLResultsTest.pro000066400000000000000000000000401433763642500264550ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLStatusTest.cpp000077500000000000000000000033321433763642500262730ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLStatusTest.h" void SyncMLStatusTest::testSyncMLStatus() { } QTEST_MAIN(SyncMLStatusTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLStatusTest.h000077500000000000000000000034721433763642500257450ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLSTATUSTEST_H #define SYNCMLSTATUSTEST_H #include class SyncMLStatusTest: public QObject { Q_OBJECT private slots: void testSyncMLStatus(); }; #endif // SYNCMLSTATUSTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLStatusTest.pro000066400000000000000000000000401433763642500262770ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLSyncTest.cpp000066400000000000000000000054201433763642500257210ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SyncMLSyncTest.h" #include "SyncMLSync.h" #include "SyncMLAdd.h" #include "SyncMLDelete.h" #include "SyncMLReplace.h" #include "QtEncoder.h" #include void SyncMLSyncTest::testAddNumberOfChanges() { int cmdID = 1; QString source("foo"); QString target("bar"); DataSync::SyncMLSync sync(cmdID, source, target); int numOfChanges = 5; sync.addNumberOfChanges(numOfChanges); DataSync::QtEncoder encoder; QByteArray output; QVERIFY( encoder.encodeToXML( sync, output, true ) ); // remove any whitespace that might disturb the comparison output = output.replace(QByteArray("\r"), QByteArray("")); output = output.replace(QByteArray("\n"), QByteArray("")); output = output.replace(QByteArray("\t"), QByteArray("")); output = output.replace(QByteArray(" "), QByteArray("")); QByteArray expected = "1foobar5"; expected = expected.replace(QByteArray(" "), QByteArray("")); QCOMPARE(output, expected); } QTEST_MAIN(SyncMLSyncTest) buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLSyncTest.h000066400000000000000000000036001433763642500253640ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SYNCMLSYNCTEST_H #define SYNCMLSYNCTEST_H #include class SyncMLAdd; class SyncMLDelete; class SyncMLReplace; class SyncMLSyncTest : public QObject { Q_OBJECT private slots: void testAddNumberOfChanges(); private: }; #endif // SYNCMLSYNCTEST_H buteo-syncml-0.5.15/tests_meego/syncelementstests/SyncMLSyncTest.pro000066400000000000000000000000401433763642500257300ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/syncelementstests/syncelementstests.pro000077500000000000000000000010371433763642500266740ustar00rootroot00000000000000include(../tests_common.pri) TEMPLATE = subdirs SUBDIRS = \ SyncMLAddTest.pro \ SyncMLAlertTest.pro \ SyncMLBodyTest.pro \ SyncMLCmdObjectTest.pro \ SyncMLCredTest.pro \ SyncMLDeleteTest.pro \ SyncMLDevInfTest.pro \ SyncMLHdrTest.pro \ SyncMLItemTest.pro \ SyncMLLocalChangeTest.pro \ SyncMLMapTest.pro \ SyncMLMessageParserTest.pro \ SyncMLMessageTest.pro \ SyncMLPutTest.pro \ SyncMLReplaceTest.pro \ SyncMLResultsTest.pro \ SyncMLStatusTest.pro \ SyncMLSyncTest.pro \ buteo-syncml-0.5.15/tests_meego/testapplication.pri000066400000000000000000000011051433763642500224720ustar00rootroot00000000000000include(tests_common.pri) pro_file_basename = $$basename(_PRO_FILE_) pro_file_basename ~= s/\\.pro$// TEMPLATE = app TARGET = $${pro_file_basename} HEADERS = $${pro_file_basename}.h SOURCES = $${pro_file_basename}.cpp LIBS += -L$${OUT_PWD}/$${tests_subdir_r} -lTestUtils target.path = $${INSTALL_TESTDIR}/$${tests_subdir} INSTALLS += target check.depends = all check.commands = '\ cd "$${PWD}" \ && export LD_LIBRARY_PATH="$${OUT_PWD}/$${tests_subdir_r}/../src:\$\${LD_LIBRARY_PATH}" \ && $${OUT_PWD}/$${TARGET}' check.CONFIG = phony QMAKE_EXTRA_TARGETS += check buteo-syncml-0.5.15/tests_meego/tests.xml000066400000000000000000000176431433763642500204550ustar00rootroot00000000000000 /opt/tests/buteo-syncml-qt5/runstarget.sh AlertPackageTest /opt/tests/buteo-syncml-qt5/runstarget.sh AuthHelperTest /opt/tests/buteo-syncml-qt5/runstarget.sh AuthenticationPackageTest /opt/tests/buteo-syncml-qt5/runstarget.sh ChangeLogTest /opt/tests/buteo-syncml-qt5/runstarget.sh CommandHandlerTest /opt/tests/buteo-syncml-qt5/runstarget.sh ConflictResolverTest /opt/tests/buteo-syncml-qt5/runstarget.sh DevInfHandlerTest /opt/tests/buteo-syncml-qt5/runstarget.sh DevInfPackageTest /opt/tests/buteo-syncml-qt5/runstarget.sh FinalPackageTest /opt/tests/buteo-syncml-qt5/runstarget.sh LocalChangesPackageTest /opt/tests/buteo-syncml-qt5/runstarget.sh LocalMappingsPackageTest /opt/tests/buteo-syncml-qt5/runstarget.sh NonceStorageTest /opt/tests/buteo-syncml-qt5/runstarget.sh ResponseGeneratorTest /opt/tests/buteo-syncml-qt5/runstarget.sh SANTest /opt/tests/buteo-syncml-qt5/runstarget.sh SessionHandlerTest /opt/tests/buteo-syncml-qt5/runstarget.sh StorageHandlerTest /opt/tests/buteo-syncml-qt5/runstarget.sh SyncAgentConfigTest /opt/tests/buteo-syncml-qt5/runstarget.sh SyncAgentTest /opt/tests/buteo-syncml-qt5/runstarget.sh SyncItemPrefetcherTest /opt/tests/buteo-syncml-qt5/runstarget.sh SyncModeTest /opt/tests/buteo-syncml-qt5/runstarget.sh SyncResultTest /opt/tests/buteo-syncml-qt5/runstarget.sh SyncTargetTest /opt/tests/buteo-syncml-qt5/runstarget.sh clienttests/ClientSessionHandlerTest /opt/tests/buteo-syncml-qt5/runstarget.sh servertests/ServerSessionHandlerTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLAddTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLAlertTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLBodyTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLCmdObjectTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLCredTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLDeleteTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLDevInfTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLHdrTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLItemTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLLocalChangeTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLMapTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLMessageParserTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLMessageTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLPutTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLReplaceTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLResultsTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLStatusTest /opt/tests/buteo-syncml-qt5/runstarget.sh syncelementstests/SyncMLSyncTest /opt/tests/buteo-syncml-qt5/runstarget.sh transporttests/BaseTransportTest /opt/tests/buteo-syncml-qt5/runstarget.sh transporttests/ClientWorkerTest /opt/tests/buteo-syncml-qt5/runstarget.sh transporttests/HTTPTransportTest /opt/tests/buteo-syncml-qt5/runstarget.sh transporttests/OBEXTransportTest /opt/tests/buteo-syncml-qt5/runstarget.sh transporttests/ServerWorkerTest buteo-syncml-0.5.15/tests_meego/tests_common.pri000066400000000000000000000023261433763642500220070ustar00rootroot00000000000000isEmpty(TESTS_COMMON_PRI_INCLUDED) { TESTS_COMMON_PRI_INCLUDED = 1 tests_subdir = $$relative_path($$dirname(_PRO_FILE_), $${PWD}) tests_subdir_r = $$relative_path($${PWD}, $$dirname(_PRO_FILE_)) QT += testlib core sql network QT -= gui CONFIG += link_prl link_pkgconfig # DEFINES += QT_NO_DEBUG_OUTPUT # use the buteosyncml library objects directly to get better debugging data # So if remember to compile them when debugging LIBS += -L$${OUT_PWD}/$${tests_subdir_r}/../src/ PKGCONFIG += buteosyncfw5 \ libwbxml2 LIBS += -lbuteosyncml5 # This is needed to avoid adding the /usr/lib link directory before the # newer version in buteosyncml QMAKE_LIBDIR_QT = $${OUT_PWD}/$${tests_subdir_r}/../src $${QMAKE_LIBDIR_QT} QMAKE_CXXFLAGS += -Wall -g INCLUDEPATH = \ $${PWD} \ $${PWD}/../src/ \ $${PWD}/../src/syncelements \ $${PWD}/../src/transport \ $${PWD}/../src/server \ $${PWD}/../src/client \ # This way time to run qmake is reduced by ~35% CONFIG -= depend_includepath DEPENDPATH = \ $${PWD}/../src/syncelements \ $${PWD}/../src/transport \ $${PWD}/../src/server \ $${PWD}/../src/client \ INSTALL_TESTDIR = /opt/tests/buteo-syncml-qt5 INSTALL_TESTDATADIR = $${INSTALL_TESTDIR}/data } buteo-syncml-0.5.15/tests_meego/tests_meego.pro000066400000000000000000000030211433763642500216120ustar00rootroot00000000000000include(tests_common.pri) TEMPLATE = subdirs CONFIG += ordered PKGCONFIG = libwbxml2 SUBDIRS = \ TestUtils.pro \ generaltests.pro \ clienttests \ servertests \ syncelementstests \ transporttests \ OTHER_FILES += \ data/transport_initrequest_nohdr.txt \ data/transport_initrequest.txt \ data/toXMLtest.txt \ data/testURI.txt \ data/testMap.txt \ data/testAlert.txt \ data/syncml_resp5.txt \ data/syncml_resp4.txt \ data/syncml_resp3.txt \ data/syncml_resp2.txt \ data/syncml_resp.txt \ data/syncml_init.txt \ data/SyncMLHdrTest_11.txt \ data/SyncMLHdrTest.txt \ data/resp.txt \ data/basicbasetransport.txt \ data/basicbasetransport.bin \ data/basicbasetransport2.txt \ data/cmdhandler_put.txt \ data/cmdhandler_get.txt \ data/SAN01.bin \ data/SAN02.bin \ data/obexresp01.bin \ data/obexresp02.bin \ data/obexresp03.bin \ data/respinvalid1.txt \ data/respinvalid2.txt \ data/respinvalid3.txt \ data/respinvalid4.txt \ data/respinvalid5.txt \ data/respinvalid6.txt \ data/testconf.xsd \ data/testconf1.xml \ data/devinf01.txt \ data/devinf02.txt \ data/subcommands01.txt \ data/resp2.txt # install testdata.files = data/* testdata.path = $${INSTALL_TESTDATADIR} INSTALLS += testdata testdefinition.files = tests.xml testdefinition.path = $${INSTALL_TESTDIR} INSTALLS += testdefinition testwrapper.files = runstarget.sh testwrapper.path = $${INSTALL_TESTDIR} INSTALLS += testwrapper buteo-syncml-0.5.15/tests_meego/transporttests/000077500000000000000000000000001433763642500216755ustar00rootroot00000000000000buteo-syncml-0.5.15/tests_meego/transporttests/BaseTransportTest.cpp000066400000000000000000000204511433763642500260320ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "BaseTransportTest.h" #include "SyncMLMessage.h" #include "TestUtils.h" #include "Fragments.h" #include "Mock.h" #include #define SYNCML_CONTTYPE_XML "application/vnd.syncml+xml" #define SYNCML_CONTTYPE_WBXML "application/vnd.syncml+wbxml" Q_DECLARE_METATYPE( QIODevice* ); void BaseTransportTest::initTestCase() { qRegisterMetaType( "DataSync::TransportStatusEvent" ); qRegisterMetaType( "QIODevice*" ); } void BaseTransportTest::cleanupTestCase() { } void BaseTransportTest::testBasicXMLSend() { TestTransport transport( true ); QSignalSpy sendEvent( &transport, SIGNAL( sendEvent( DataSync::TransportStatusEvent, const QString& ) ) ); QSignalSpy readData( &transport, SIGNAL( readXMLData( QIODevice*, bool ) ) ); transport.setWbXml( false ); HeaderParams params; params.verDTD = SYNCML_DTD_VERSION_1_2; params.verProto = DS_VERPROTO_1_2; params.msgID = 1; params.targetDevice = "targetDevice"; params.sourceDevice = "sourceDevice"; SyncMLMessage* message = new SyncMLMessage( params, SYNCML_1_2 ); QVERIFY( transport.sendSyncML( NULL ) == false ); QVERIFY( sendEvent.count() == 0 ); QVERIFY( readData.count() == 0 ); QVERIFY( transport.sendSyncML( message ) == true ); QVERIFY( sendEvent.count() == 0 ); QVERIFY( readData.count() == 0 ); QByteArray correctOutput; QVERIFY( readFile( "data/basicbasetransport.txt", correctOutput ) ); QVERIFY( transport.iContentType == SYNCML_CONTTYPE_XML ); QVERIFY( transport.iData == correctOutput ); } void BaseTransportTest::testBasicXMLReceive() { TestTransport transport( true ); QSignalSpy sendEvent( &transport, SIGNAL( sendEvent( DataSync::TransportStatusEvent, const QString& ) ) ); QSignalSpy readData( &transport, SIGNAL( readXMLData( QIODevice*, bool ) ) ); transport.setWbXml( false ); transport.iContentType = SYNCML_CONTTYPE_XML; QVERIFY( readFile( "data/basicbasetransport.txt", transport.iData ) ); QVERIFY( transport.receive() == true ); QVERIFY( sendEvent.count() == 0 ); QVERIFY( readData.count() == 1 ); QIODevice* dev = qvariant_cast( readData.at(0).at(0) ); QByteArray data = dev->readAll(); QCOMPARE( data, transport.iData ); } void BaseTransportTest::testBasicWbXMLSend() { TestTransport transport( true ); QSignalSpy sendEvent( &transport, SIGNAL( sendEvent( DataSync::TransportStatusEvent, const QString& ) ) ); QSignalSpy readData( &transport, SIGNAL( readXMLData( QIODevice* ) ) ); transport.setWbXml( true ); HeaderParams params; params.msgID = 1; params.targetDevice = "targetDevice"; params.sourceDevice = "sourceDevice"; SyncMLMessage* message = new SyncMLMessage( params, SYNCML_1_2 ); QVERIFY( transport.sendSyncML( NULL ) == false ); QVERIFY( sendEvent.count() == 0 ); QVERIFY( readData.count() == 0 ); QVERIFY( transport.sendSyncML( message ) == true ); // Ownership of message is transferred. message = 0; QVERIFY( sendEvent.count() == 0 ); QVERIFY( readData.count() == 0 ); QByteArray correctOutput; QVERIFY( readFile( "data/basicbasetransport.bin", correctOutput ) == true ); QVERIFY( transport.iContentType == SYNCML_CONTTYPE_WBXML ); // These tests are failing outside scratchbox. This is probably due to differences // in the libwbxml2 output because different versions of the library are used. // Disabling these for now until we can figure out can we test this some other way. //QVERIFY( transport.iData == correctOutput ); } void BaseTransportTest::testBasicWbXMLReceive() { TestTransport transport( true ); QSignalSpy sendEvent( &transport, SIGNAL( sendEvent( DataSync::TransportStatusEvent, const QString& ) ) ); QSignalSpy readData( &transport, SIGNAL( readXMLData( QIODevice*, bool ) ) ); transport.setWbXml( true ); transport.iContentType = SYNCML_CONTTYPE_WBXML; QVERIFY( readFile( "data/basicbasetransport.bin", transport.iData ) ); QVERIFY( transport.receive() == true ); QVERIFY( sendEvent.count() == 0 ); QVERIFY( readData.count() == 1 ); QIODevice* dev = qvariant_cast( readData.at(0).at(0) ); QByteArray data = dev->readAll(); QByteArray correctOutput; QVERIFY( readFile( "data/basicbasetransport2.txt", correctOutput ) ); // These tests are failing outside scratchbox. This is probably due to differences // in the libwbxml2 output because different versions of the library are used. // Disabling these for now until we can figure out can we test this some other way. //QCOMPARE( data, correctOutput ); } void BaseTransportTest::testSANReceive01() { // testSANReceive01: test SAN receive with correct content type TestTransport transport( true ); QSignalSpy sendEvent( &transport, SIGNAL( sendEvent( DataSync::TransportStatusEvent, const QString& ) ) ); QSignalSpy readXMLData( &transport, SIGNAL( readXMLData( QIODevice* ) ) ); QSignalSpy readSANData( &transport, SIGNAL( readSANData( QIODevice* ) ) ); QByteArray contentType = SYNCML_CONTTYPE_SAN_DS; QByteArray originalData; QVERIFY( readFile( "data/SAN01.bin", originalData ) ); transport.iContentType = contentType; transport.iData = originalData; QVERIFY( transport.receive() == true ); QVERIFY( sendEvent.count() == 0 ); QVERIFY( readXMLData.count() == 0 ); QVERIFY( readSANData.count() == 1 ); QIODevice* dev = qvariant_cast( readSANData.at(0).at(0) ); QByteArray data = dev->readAll(); QCOMPARE( originalData, data ); } void BaseTransportTest::testSANReceive02() { // testSANReceive01: test SAN receive with bad content type. Nokia S60 seems to // use wbxml content type with SAN, even though standard specifies a distinct // content type for it TestTransport transport( true ); QSignalSpy sendEvent( &transport, SIGNAL( sendEvent( DataSync::TransportStatusEvent, const QString& ) ) ); QSignalSpy readXMLData( &transport, SIGNAL( readXMLData( QIODevice* ) ) ); QSignalSpy readSANData( &transport, SIGNAL( readSANData( QIODevice* ) ) ); QByteArray contentType = SYNCML_CONTTYPE_DS_WBXML; QByteArray originalData; QVERIFY( readFile( "data/SAN01.bin", originalData ) ); transport.iContentType = contentType; transport.iData = originalData; QVERIFY( transport.receive() == true ); QVERIFY( sendEvent.count() == 0 ); QVERIFY( readXMLData.count() == 0 ); QVERIFY( readSANData.count() == 1 ); QIODevice* dev = qvariant_cast( readSANData.at(0).at(0) ); QByteArray data = dev->readAll(); QCOMPARE( originalData, data ); } QTEST_MAIN(BaseTransportTest) buteo-syncml-0.5.15/tests_meego/transporttests/BaseTransportTest.h000066400000000000000000000040371433763642500255010ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef BASETRANSPORTTEST_H #define BASETRANSPORTTEST_H #include class BaseTransportTest : public QObject { Q_OBJECT; public: private slots: void initTestCase(); void cleanupTestCase(); void testBasicXMLSend(); void testBasicXMLReceive(); void testBasicWbXMLSend(); void testBasicWbXMLReceive(); void testSANReceive01(); void testSANReceive02(); }; #endif // BASETRANSPORTTEST_H buteo-syncml-0.5.15/tests_meego/transporttests/BaseTransportTest.pro000066400000000000000000000000401433763642500260400ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/transporttests/ClientWorkerTest.cpp000066400000000000000000000237421433763642500256610ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ClientWorkerTest.h" #include #include #include #include #include "TestUtils.h" #include "OBEXClientWorker.h" #include "SyncMLLogging.h" using namespace DataSync; const int MTU = 1024; const int TIMEOUT = 5; ClientWorkerTest::ClientWorkerTest() : iServerThread( 0 ), iClientSocket( 0 ) { } ClientWorkerTest::~ClientWorkerTest() { delete iClientSocket; iClientSocket = 0; delete iServerThread; iServerThread = 0; } void ClientWorkerTest::init() { iServerThread = new ServerThread; iServerThread->start(); while( iServerThread->port() == 0 ) { } iClientSocket = new QTcpSocket; iClientSocket->connectToHost( "127.0.0.1", iServerThread->port() ); QVERIFY( iClientSocket->waitForConnected() ); } void ClientWorkerTest::cleanup() { iClientSocket->close(); delete iClientSocket; iClientSocket = 0; iServerThread->exit(); iServerThread->wait(); delete iServerThread; iServerThread = 0; } void ClientWorkerTest::testConnectSuccess() { // Case to test successful OBEX CONNECT QByteArray rsp1; QVERIFY( readFile( "data/obexresp01.bin", rsp1 ) ); iServerThread->addResponse( rsp1 ); OBEXClientWorker worker( iClientSocket->socketDescriptor(), MTU, TIMEOUT ); QSignalSpy dataSpy( &worker, SIGNAL(incomingData( QByteArray, QString )) ); QSignalSpy connFailureSpy( &worker, SIGNAL(connectionFailed()) ); QSignalSpy connTimeoutSpy( &worker, SIGNAL(connectionTimeout()) ); QSignalSpy connErrorSpy( &worker, SIGNAL(connectionError()) ); worker.connect(); QVERIFY( worker.isConnected() ); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); } void ClientWorkerTest::testConnectLinkFailure() { // Case to test unsuccessful OBEX CONNECT due to link failure. // As connection is not up yet, stack should not send error signals OBEXClientWorker worker( iClientSocket->socketDescriptor(), MTU, TIMEOUT ); QSignalSpy dataSpy( &worker, SIGNAL(incomingData( QByteArray, QString )) ); QSignalSpy connFailureSpy( &worker, SIGNAL(connectionFailed()) ); QSignalSpy connTimeoutSpy( &worker, SIGNAL(connectionTimeout()) ); QSignalSpy connErrorSpy( &worker, SIGNAL(connectionError()) ); worker.connect(); QVERIFY( !worker.isConnected() ); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); } void ClientWorkerTest::testConnectRefused() { // Case to test unsuccessful OBEX CONNECT due to remote device refusing the // request // As connection is not up yet, stack should not send error signals QByteArray rsp1; QVERIFY( readFile( "data/obexresp02.bin", rsp1 ) ); iServerThread->addResponse( rsp1 ); OBEXClientWorker worker( iClientSocket->socketDescriptor(), MTU, TIMEOUT ); QSignalSpy dataSpy( &worker, SIGNAL(incomingData( QByteArray, QString )) ); QSignalSpy connFailureSpy( &worker, SIGNAL(connectionFailed()) ); QSignalSpy connTimeoutSpy( &worker, SIGNAL(connectionTimeout()) ); QSignalSpy connErrorSpy( &worker, SIGNAL(connectionError()) ); worker.connect(); QVERIFY( !worker.isConnected() ); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); } void ClientWorkerTest::testDisconnectSuccess() { // Case to test successful OBEX DISCONNECT QByteArray rsp1; QVERIFY( readFile( "data/obexresp01.bin", rsp1 ) ); iServerThread->addResponse( rsp1 ); QByteArray rsp2; QVERIFY( readFile( "data/obexresp03.bin", rsp2 ) ); iServerThread->addResponse( rsp2 ); OBEXClientWorker worker( iClientSocket->socketDescriptor(), MTU, TIMEOUT ); QSignalSpy dataSpy( &worker, SIGNAL(incomingData( QByteArray, QString )) ); QSignalSpy connFailureSpy( &worker, SIGNAL(connectionFailed()) ); QSignalSpy connTimeoutSpy( &worker, SIGNAL(connectionTimeout()) ); QSignalSpy connErrorSpy( &worker, SIGNAL(connectionError()) ); worker.connect(); QVERIFY( worker.isConnected() ); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); worker.disconnect(); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); } void ClientWorkerTest::testDisconnectLinkFailure() { // Case to test unsuccessful OBEX DISCONNECT due to link failure. // As connection is being broken down, stack should not send error signal // about the failure QByteArray rsp1; QVERIFY( readFile( "data/obexresp01.bin", rsp1 ) ); iServerThread->addResponse( rsp1 ); OBEXClientWorker worker( iClientSocket->socketDescriptor(), MTU, TIMEOUT ); QSignalSpy dataSpy( &worker, SIGNAL(incomingData( QByteArray, QString )) ); QSignalSpy connFailureSpy( &worker, SIGNAL(connectionFailed()) ); QSignalSpy connTimeoutSpy( &worker, SIGNAL(connectionTimeout()) ); QSignalSpy connErrorSpy( &worker, SIGNAL(connectionError()) ); worker.connect(); QVERIFY( worker.isConnected() ); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); worker.disconnect(); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); } void ClientWorkerTest::testDisconnectRefused() { // Case to test unsuccessful OBEX DISCONNECT due to remote device refusing the // request QByteArray rsp1; QVERIFY( readFile( "data/obexresp01.bin", rsp1 ) ); iServerThread->addResponse( rsp1 ); QByteArray rsp2; QVERIFY( readFile( "data/obexresp02.bin", rsp2 ) ); iServerThread->addResponse( rsp2 ); OBEXClientWorker worker( iClientSocket->socketDescriptor(), MTU, TIMEOUT ); QSignalSpy dataSpy( &worker, SIGNAL(incomingData( QByteArray, QString )) ); QSignalSpy connFailureSpy( &worker, SIGNAL(connectionFailed()) ); QSignalSpy connTimeoutSpy( &worker, SIGNAL(connectionTimeout()) ); QSignalSpy connErrorSpy( &worker, SIGNAL(connectionError()) ); worker.connect(); QVERIFY( worker.isConnected() ); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); worker.disconnect(); QCOMPARE( dataSpy.count(), 0 ); QCOMPARE( connFailureSpy.count(), 0 ); QCOMPARE( connTimeoutSpy.count(), 0 ); QCOMPARE( connErrorSpy.count(), 0 ); } ServerThread::ServerThread() : iPort( 0 ), iServerSocket( 0 ) { } ServerThread::~ServerThread() { delete iServerSocket; iServerSocket = 0; } quint16 ServerThread::port() const { return iPort; } void ServerThread::addResponse( const QByteArray& aResponse ) { iResponses.append(aResponse); } void ServerThread::run() { QTcpServer server; if( !server.listen( QHostAddress::LocalHost, iPort ) ) { qCCritical(lcSyncML) << "Could not start listening"; return; } iPort = server.serverPort(); qCDebug(lcSyncML) << "Listening port" << iPort; if( !server.waitForNewConnection(1000) ) { qCCritical(lcSyncML) << "No connection received"; return; } iServerSocket = server.nextPendingConnection(); connect( iServerSocket, SIGNAL( readyRead() ), this, SLOT( readData() ), Qt::DirectConnection ); qCDebug(lcSyncML) << "Entering event loop"; exec(); qCDebug(lcSyncML) << "Exiting event loop"; delete iServerSocket; iServerSocket = 0; server.close(); } void ServerThread::readData() { QByteArray request = iServerSocket->readAll(); qCDebug(lcSyncML) << "Received request:" << request.toHex(); if( !iResponses.isEmpty() ) { QByteArray response = iResponses.takeFirst(); qCDebug(lcSyncML) << "Writing response:" << response.toHex(); iServerSocket->write( response ); } else { qCDebug(lcSyncML) << "No responses, exiting"; exit(); } } QTEST_MAIN(DataSync::ClientWorkerTest) buteo-syncml-0.5.15/tests_meego/transporttests/ClientWorkerTest.h000066400000000000000000000051751433763642500253260ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CLIENTWORKERTEST_H #define CLIENTWORKERTEST_H #include #include class QTcpSocket; namespace DataSync { class ServerThread; class ClientWorkerTest : public QObject { Q_OBJECT; public: ClientWorkerTest(); virtual ~ClientWorkerTest(); private slots: void init(); void cleanup(); void testConnectSuccess(); void testConnectLinkFailure(); void testConnectRefused(); void testDisconnectSuccess(); void testDisconnectLinkFailure(); void testDisconnectRefused(); private: ServerThread* iServerThread; QTcpSocket* iClientSocket; }; class ServerThread : public QThread { Q_OBJECT; public: ServerThread(); virtual ~ServerThread(); quint16 port() const; void addResponse( const QByteArray& aResponse ); protected: virtual void run(); private slots: void readData(); private: volatile quint16 iPort; QTcpSocket* iServerSocket; QList iResponses; }; } #endif // CLIENTWORKERTEST_H buteo-syncml-0.5.15/tests_meego/transporttests/ClientWorkerTest.pro000066400000000000000000000000401433763642500256610ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/transporttests/HTTPTransportTest.cpp000066400000000000000000000074241433763642500257440ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "HTTPTransportTest.h" #include "SyncMLMessage.h" #include "HTTPTransport.h" #include "SyncAgentConfigProperties.h" #include #include "TestUtils.h" #include "Fragments.h" #include "Mock.h" #include "SyncMLLogging.h" #include #include Q_DECLARE_METATYPE(QIODevice*); void HTTPTransportTest::initTestCase() { } void HTTPTransportTest::cleanupTestCase() { } void HTTPTransportTest::testBasicXMLSend() { HTTPTransport transport; QSignalSpy sendEvent(&transport, SIGNAL(sendEvent(DataSync::TransportStatusEvent, const QString&))); QSignalSpy readData(&transport, SIGNAL(readXMLData(QIODevice*, bool))); transport.setWbXml(false); transport.init(); HeaderParams params; params.verDTD = SYNCML_DTD_VERSION_1_2; params.verProto = DS_VERPROTO_1_2; params.msgID = 1; params.targetDevice = "targetDevice"; params.sourceDevice = "sourceDevice"; transport.addXheader("foo", "bar"); SyncMLMessage* message = new SyncMLMessage(params, SYNCML_1_2); QVERIFY(transport.sendSyncML(NULL) == false); QVERIFY(sendEvent.count() == 0); QVERIFY(readData.count() == 0); QVERIFY(transport.sendSyncML(message) == true); QVERIFY(sendEvent.count() == 0); QVERIFY(readData.count() == 0); transport.close(); } void HTTPTransportTest::testSetProperty() { HTTPTransport transport; transport.setProperty("foo", "bar"); QString proxyHost("http://foo.bar.net"); transport.setProperty(HTTPNUMBEROFRESENDATTEMPTSPROP, "10"); transport.setProperty(HTTPPROXYHOSTPROP, proxyHost); transport.setProperty(HTTPPROXYPORTPROP, "5555"); QNetworkProxy proxy = transport.getProxyConfig(); QCOMPARE(proxy.hostName(), proxyHost); QCOMPARE(proxy.port(), (quint16)5555); } void HTTPTransportTest::testSetProxy() { HTTPTransport transport; QNetworkProxy proxy; QString proxyHost("http://foo.bar.net"); quint16 port = 5555; proxy.setHostName(proxyHost); proxy.setPort(port); transport.setProxyConfig(proxy); proxy = transport.getProxyConfig(); QCOMPARE(proxy.hostName(), proxyHost); QCOMPARE(proxy.port(), port); } QTEST_MAIN(HTTPTransportTest) buteo-syncml-0.5.15/tests_meego/transporttests/HTTPTransportTest.h000066400000000000000000000036661433763642500254150ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef HTTPTRANSPORTTEST_H #define HTTPTRANSPORTTEST_H #include class HTTPTransportTest : public QObject { Q_OBJECT; public: private slots: void initTestCase(); void cleanupTestCase(); void testBasicXMLSend(); void testSetProperty(); void testSetProxy(); }; #endif // HTTPTRANSPORTTEST_H buteo-syncml-0.5.15/tests_meego/transporttests/HTTPTransportTest.pro000066400000000000000000000000401433763642500257450ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/transporttests/OBEXTransportTest.cpp000066400000000000000000000065601433763642500257220ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "OBEXTransportTest.h" #include "SyncMLMessage.h" #include "OBEXTransport.h" #include "SyncAgentConfigProperties.h" #include "TestUtils.h" #include "Fragments.h" #include "Mock.h" #include "SyncMLLogging.h" #include Q_DECLARE_METATYPE(QIODevice*); using namespace DataSync; void OBEXTransportTest::initTestCase() { } void OBEXTransportTest::cleanupTestCase() { } void OBEXTransportTest::testServerSend() { OBEXConnectionTest conn(true); OBEXTransport transport(conn, OBEXTransport::MODE_OBEX_SERVER); transport.init(); HeaderParams params; params.verDTD = SYNCML_DTD_VERSION_1_2; params.verProto = DS_VERPROTO_1_2; params.msgID = 1; params.targetDevice = "targetDevice"; params.sourceDevice = "sourceDevice"; SyncMLMessage* message = new SyncMLMessage(params, SYNCML_1_2); QByteArray data; QCOMPARE(transport.getData(SYNCML_CONTTYPE_DS_XML, data), false); QCOMPARE(transport.sendSyncML(message), true); QCOMPARE(transport.getData(SYNCML_CONTTYPE_DS_XML, data), true); QCOMPARE(transport.getData("InexistentDataType", data), false); transport.close(); } void OBEXTransportTest::testClientSend() { OBEXConnectionTest conn(true); OBEXTransport transport(conn, OBEXTransport::MODE_OBEX_CLIENT); transport.setProperty(OBEXTIMEOUTPROP, "5"); transport.init(); HeaderParams params; params.verDTD = SYNCML_DTD_VERSION_1_2; params.verProto = DS_VERPROTO_1_2; params.msgID = 1; params.targetDevice = "targetDevice"; params.sourceDevice = "sourceDevice"; SyncMLMessage* message = new SyncMLMessage(params, SYNCML_1_2); QCOMPARE(transport.sendSyncML(NULL), false); transport.sendSyncML(message); transport.close(); } QTEST_MAIN(OBEXTransportTest) buteo-syncml-0.5.15/tests_meego/transporttests/OBEXTransportTest.h000066400000000000000000000036331433763642500253650ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OBEXTRANSPORTTEST_H #define OBEXTRANSPORTTEST_H #include class OBEXTransportTest : public QObject { Q_OBJECT; public: private slots: void initTestCase(); void cleanupTestCase(); void testClientSend(); void testServerSend(); }; #endif // OBEXTRANSPORTTEST_H buteo-syncml-0.5.15/tests_meego/transporttests/OBEXTransportTest.pro000066400000000000000000000000401433763642500257230ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/transporttests/ServerWorkerTest.cpp000066400000000000000000000117731433763642500257120ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ServerWorkerTest.h" #include #include #include #include #include "OBEXServerWorker.h" #include "Mock.h" #include "SyncMLLogging.h" using namespace DataSync; const int MTU = 1024; const int TIMEOUT = 5; ServerWorkerTest::ServerWorkerTest() : iServer( 0 ), iClientThread( 0 ), iServerSocket( 0 ) { } ServerWorkerTest::~ServerWorkerTest() { } bool ServerWorkerTest::getData( const QString& aContentType, QByteArray& aData ) { Q_UNUSED(aContentType); Q_UNUSED(aData); Q_ASSERT(0); return false; } void ServerWorkerTest::init() { //Logger::createInstance(); iServer = new QTcpServer; QVERIFY( iServer->listen() ); qCDebug(lcSyncML) << "Listening port" << iServer->serverPort(); iClientThread = new ClientThread( iServer->serverPort() ); iClientThread->start(); QVERIFY( iServer->waitForNewConnection(1000) ); iServerSocket = iServer->nextPendingConnection(); } void ServerWorkerTest::cleanup() { iServerSocket->close(); delete iServerSocket; iServerSocket = 0; iServer->close(); delete iServer; iServer = 0; iClientThread->exit(); iClientThread->wait(); delete iClientThread; iClientThread = 0; //Logger::deleteInstance(); } // @todo: commented out until implementation finished /* void ServerWorkerTest::testConnectSuccess() { // Case to test successful OBEX CONNECT QByteArray rqst; iClientThread->addRequest( "foo" ); OBEXUsbConnection connection( iServerSocket->socketDescriptor() ); OBEXServerWorker worker( &connection, *this, TIMEOUT ); QSignalSpy dataSpy( &worker, SIGNAL(incomingData( QByteArray, QString )) ); QSignalSpy connFailureSpy( &worker, SIGNAL(connectionFailed()) ); QSignalSpy connTimeoutSpy( &worker, SIGNAL(connectionTimeout()) ); QSignalSpy connErrorSpy( &worker, SIGNAL(connectionError()) ); //QTimer::singleShot( 2000, iClientThread, SLOT( begin() ) ) QMetaObject::invokeMethod( iClientThread, "begin", Qt::QueuedConnection ); //iClientThread->begin(); worker.waitForConnect(); QVERIFY( worker.isConnected() ); } */ ClientThread::ClientThread( quint16 aPort ) : iPort( aPort ), iClientSocket( 0 ) { } ClientThread::~ClientThread() { delete iClientSocket; iClientSocket = 0; } void ClientThread::addRequest( const QByteArray& aRequest ) { iRequests.append(aRequest); } void ClientThread::begin() { sendNextRequest(); } void ClientThread::run() { iClientSocket = new QTcpSocket; iClientSocket->connectToHost( "127.0.0.1", iPort ); if( !iClientSocket->waitForDisconnected() ) { return; } connect( iClientSocket, SIGNAL( readyRead() ), this, SLOT( readData() ), Qt::DirectConnection ); exec(); iClientSocket->close(); delete iClientSocket; iClientSocket = 0; } void ClientThread::readData() { QByteArray response = iClientSocket->readAll(); qCDebug(lcSyncML) << "Received response:" << response.toHex(); sendNextRequest(); } void ClientThread::sendNextRequest() { if( !iRequests.isEmpty() ) { QByteArray request = iRequests.takeFirst(); qCDebug(lcSyncML) << "Writing request:" << request.toHex(); iClientSocket->write( request ); } else { qCDebug(lcSyncML) << "No requests, exiting"; exit(); } } QTEST_MAIN(DataSync::ServerWorkerTest) buteo-syncml-0.5.15/tests_meego/transporttests/ServerWorkerTest.h000066400000000000000000000053661433763642500253600ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SERVERWORKERTEST_H #define SERVERWORKERTEST_H #include #include #include "OBEXServerWorker.h" class QTcpServer; class QTcpSocket; namespace DataSync { class ClientThread; class ServerWorkerTest : public QObject, public OBEXServerDataSource { Q_OBJECT public: ServerWorkerTest(); virtual ~ServerWorkerTest(); virtual bool getData( const QString& aContentType, QByteArray& aData ); private slots: void init(); void cleanup(); // @todo: commented out until implementation is finished //void testConnectSuccess(); private: QTcpServer* iServer; ClientThread* iClientThread; QTcpSocket* iServerSocket; }; class ClientThread : public QThread { Q_OBJECT public: ClientThread( quint16 aPort ); virtual ~ClientThread(); void addRequest( const QByteArray& aRequest ); public slots: void begin(); protected: virtual void run(); private slots: void readData(); private: void sendNextRequest(); QList iRequests; quint16 iPort; QTcpSocket* iClientSocket; }; } #endif // SERVERWORKERTEST_H buteo-syncml-0.5.15/tests_meego/transporttests/ServerWorkerTest.pro000066400000000000000000000000401433763642500257110ustar00rootroot00000000000000include(../testapplication.pri) buteo-syncml-0.5.15/tests_meego/transporttests/SocketPair.cpp000066400000000000000000000053241433763642500244510ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SocketPair.h" #include #include using namespace DataSync; SocketPair::SocketPair(QObject *aParent) : QObject(aParent), iServer(new QTcpServer(this)), iClientSocket(0), iServerSocket(0) { } SocketPair::~SocketPair() { delete iClientSocket; iClientSocket = 0; delete iServerSocket; iServer = 0; delete iServer; iServer = 0; } bool SocketPair::init() { if (iServer == 0) return false; if (!iServer->listen()) return false; iClientSocket = new QTcpSocket(this); iClientSocket->connectToHost("127.0.0.1", iServer->serverPort()); if (!iClientSocket->waitForConnected(1000)) { delete iClientSocket; iClientSocket = 0; return false; } if (!iServer->waitForNewConnection()) { delete iClientSocket; iClientSocket = 0; return false; } iServerSocket = iServer->nextPendingConnection(); return true; } QTcpSocket *SocketPair::clientSocket() { return iClientSocket; } QTcpSocket *SocketPair::serverSocket() { return iServerSocket; } buteo-syncml-0.5.15/tests_meego/transporttests/SocketPair.h000066400000000000000000000065201433763642500241150ustar00rootroot00000000000000/* * This file is part of buteo-syncml package * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Sateesh Kavuri * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef SOCKETPAIR_H #define SOCKETPAIR_H #include class QTcpSocket; class QTcpServer; namespace DataSync { /*! \brief Creates a local TCP socket pair and connects them together. * * Data written to the client socket can be read from the server socket * and vice versa. Despite their names, the client and server sockets are * similar and they can be used in peer-to-peer communication. */ class SocketPair : public QObject { Q_OBJECT public: //! \brief Constructor SocketPair(QObject *aParent = 0); //! \brief Destructor virtual ~SocketPair(); /*! \brief Initializes the socket pair. * * Must be called before getting client or server socket pointers. * \return Success indicator. */ bool init(); /*! \brief Gets client socket pointer. Ownership is not transferred. * * The instance of this class is the parent of the returned socket * and must exist as long as the socket is used. * socketDescriptor can be called for the returned socket to get a * descriptor that can be used for example with QFile. * \return Client socket pointer. 0 if not available. */ QTcpSocket *clientSocket(); /*! \brief Gets server socket pointer. Ownership is not transferred. * * The instance of this class is the parent of the returned socket * and must exist as long as the socket is used. * socketDescriptor can be called for the returned socket to get a * descriptor that can be used for example with QFile. * \return Server socket pointer. 0 if not available. */ QTcpSocket *serverSocket(); private: QTcpServer *iServer; QTcpSocket *iClientSocket; QTcpSocket *iServerSocket; }; } #endif // SOCKETPAIR_H buteo-syncml-0.5.15/tests_meego/transporttests/transporttests.pro000077500000000000000000000003621433763642500255420ustar00rootroot00000000000000include(../tests_common.pri) TEMPLATE = subdirs SUBDIRS = \ BaseTransportTest.pro \ ClientWorkerTest.pro \ HTTPTransportTest.pro \ OBEXTransportTest.pro \ ServerWorkerTest.pro \ # Dead code? #SocketPair.cpp #SocketPair.h