aboutsummaryrefslogtreecommitdiffstats
path: root/test/net/java/sip/communicator/slick/protocol/yahoo/TestOperationSetPersistentPresence.java
blob: 2ebf0e617d5a5a5ed4fa241aa3188dacfb36bdcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.slick.protocol.yahoo;

import java.util.*;

import junit.framework.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.slick.protocol.generic.*;
import net.java.sip.communicator.util.*;

/**
 * @author Damian Minkov
 */
public class TestOperationSetPersistentPresence
    extends TestCase
{
    private static final Logger logger =
        Logger.getLogger(TestOperationSetPersistentPresence.class);

    private YahooSlickFixture fixture = new YahooSlickFixture();
    private OperationSetPersistentPresence opSetPersPresence1 = null;
    private OperationSetPersistentPresence opSetPersPresence2 = null;
    private static final String testGroupName = "NewGroup";
    private static final String testGroupName2 = "Renamed";

    public TestOperationSetPersistentPresence(String name)
    {
        super(name);
    }

    /**
     * Creates a test suite containing all tests of this class followed by
     * test methods that we want executed in a specified order.
     * @return the Test suite to run
     */
    public static Test suite()
    {
        TestSuite suite =
            new TestSuite();

        //the following 2 need to be run in the specified order.
        //(postTestRemoveGroup() needs the group created from
        //postTestCreateGroup() )
        suite.addTest(
            new TestOperationSetPersistentPresence("postTestCreateGroup"));

        //rename
        //suite.addTest( new TestOperationSetPersistentPresence(
        //    "postTestRenameGroup"));

        suite.addTest(
            new TestOperationSetPersistentPresence("postTestRemoveGroup"));

        // create the contact list
        suite.addTest(
            new TestOperationSetPersistentPresence("prepareContactList"));

        suite.addTestSuite(TestOperationSetPersistentPresence.class);

        return suite;
    }

    @Override
    protected void setUp() throws Exception
    {
        super.setUp();
        fixture.setUp();

        Map<String, OperationSet> supportedOperationSets1 =
            fixture.provider1.getSupportedOperationSets();

        if ( supportedOperationSets1 == null
            || supportedOperationSets1.size() < 1)
            throw new NullPointerException(
                "No OperationSet implementations are supported by "
                +"this Yahoo implementation. ");

        //get the operation set presence here.
        opSetPersPresence1 =
            (OperationSetPersistentPresence)supportedOperationSets1.get(
                OperationSetPersistentPresence.class.getName());

        //if still null then the implementation doesn't offer a presence
        //operation set which is unacceptable for yahoo.
        if (opSetPersPresence1 == null)
            throw new NullPointerException(
                "An implementation of the Yahoo service must provide an "
                + "implementation of at least the one of the Presence "
                + "Operation Sets");

        // lets do it once again for the second provider
        Map<String, OperationSet> supportedOperationSets2 =
            fixture.provider2.getSupportedOperationSets();

        if (supportedOperationSets2 == null
            || supportedOperationSets2.size() < 1)
            throw new NullPointerException(
                "No OperationSet implementations are supported by "
                + "this Yahoo implementation. ");

        //get the operation set presence here.
        opSetPersPresence2 =
            (OperationSetPersistentPresence) supportedOperationSets2.get(
                OperationSetPersistentPresence.class.getName());

        //if still null then the implementation doesn't offer a presence
        //operation set which is unacceptable for yahoo.
        if (opSetPersPresence2 == null)
            throw new NullPointerException(
                "An implementation of the yahoo service must provide an "
                + "implementation of at least the one of the Presence "
                + "Operation Sets");
    }

    @Override
    protected void tearDown() throws Exception
    {
        fixture.tearDown();
        super.tearDown();
    }

    /**
     * Retrieves a server stored contact list and checks whether it contains
     * all contacts that have been added there during the initialization
     * phase by the testerAgent.
     */
    public void testRetrievingServerStoredContactList()
    {
        ContactGroup rootGroup
            = opSetPersPresence1.getServerStoredContactListRoot();

        logger.debug("=========== Server Stored Contact List =================");

        logger.debug("rootGroup="+rootGroup.getGroupName()
                     +" rootGroup.childContacts="+rootGroup.countContacts()
                     + "rootGroup.childGroups="+rootGroup.countSubgroups()
                     + "Printing rootGroupContents=\n"+rootGroup.toString());

        Hashtable<String, List<String>> expectedContactList
            = AdHocMultiUserChatSlickFixture.preInstalledBuddyList;

        logger.debug("============== Expected Contact List ===================");
        logger.debug(expectedContactList);

        //Go through the contact list retrieved by the persistence presence set
        //and remove the name of every contact and group that we find there from
        //the expected contct list hashtable.
        Iterator<ContactGroup> groups = rootGroup.subgroups();
        while (groups.hasNext() )
        {
            ContactGroup group = groups.next();

            List<String> expectedContactsInGroup
                = expectedContactList.get(group.getGroupName());

            // When sending the offline message
            // the sever creates a group NotInContactList,
            // because the buddy we are sending message to is not in
            // the contactlist. So this group must be ignored
            // Also we must ignore the group created by default
            // from the yahoo lib
            if(!group.getGroupName().equals("NotInContactList") &&
                !group.getGroupName().equals("Default group"))
            {
                assertNotNull("Group " + group.getGroupName() +
                              " was returned by "
                              +
                    "the server but was not in the expected contact list."
                              , expectedContactsInGroup);

                Iterator<Contact> contactsIter = group.contacts();
                while(contactsIter.hasNext())
                {
                    String contactID = contactsIter.next().getAddress();
                    expectedContactsInGroup.remove(contactID);
                }

                //If we've removed all the sub contacts, remove the group too.
                if(expectedContactsInGroup.size() == 0)
                    expectedContactList.remove(group.getGroupName());
            }
        }

        //whatever we now have in the expected contact list snapshot are groups,
        //that have been added by the testerAgent but that were not retrieved
        //by the persistent presence operation set.
        assertTrue("The following contacts were on the server sidec contact "
                   +"list, but were not returned by the pers. pres. op. set"
                   + expectedContactList.toString()
                   , expectedContactList.isEmpty());
    }

    /**
     * Creates a group in the server stored contact list, makes sure that the
     * corresponding event has been generated and verifies that the group is
     * in the list.
     *
     * @throws java.lang.Exception
     */
    public void postTestCreateGroup()
        throws Exception
    {
        // first clear the list
        fixture.clearProvidersLists();

        waitFor(5000);

        logger.trace("testing creation of server stored groups");
        //first add a listener
        GroupChangeCollector groupChangeCollector = new GroupChangeCollector();
        opSetPersPresence1
            .addServerStoredGroupChangeListener(groupChangeCollector);

        //create the group
        opSetPersPresence1.createServerStoredContactGroup(
            opSetPersPresence1.getServerStoredContactListRoot(), testGroupName);

        groupChangeCollector.waitForEvent(10000);

        opSetPersPresence1
            .removeServerStoredGroupChangeListener(groupChangeCollector);

        // check whether we got group created event
        assertEquals("Collected Group Change events: ",
                     1, groupChangeCollector.collectedEvents.size());

        assertEquals("Group name.",  testGroupName,
            ((ServerStoredGroupEvent)groupChangeCollector.collectedEvents
                .get(0)).getSourceGroup().getGroupName());

        // check whether the group is retrievable
        ContactGroup group = opSetPersPresence1.getServerStoredContactListRoot()
            .getGroup(testGroupName);

        assertNotNull("A newly created group was not in the contact list.",
                      group);

        assertEquals("New group name", testGroupName, group.getGroupName());

        // when opearting with groups . the group must have entries
        // so changes to take effect. Otherwise group will be lost after loggingout
        try
        {
            opSetPersPresence1.subscribe(group, fixture.userID2);

            waitFor(1500);
        }
        catch (Exception ex)
        {
            fail("error adding entry to group : " +
                 group.getGroupName() + " " +
                 ex.getMessage());
        }
    }


    /**
     * Removes the group created in the server stored contact list by the create
     * group test, makes sure that the corresponding event has been generated
     * and verifies that the group is not in the list any more.
     */
    public void postTestRemoveGroup()
    {
        logger.trace("testing removal of server stored groups");

        //first add a listener
        GroupChangeCollector groupChangeCollector = new GroupChangeCollector();
        opSetPersPresence1
            .addServerStoredGroupChangeListener(groupChangeCollector);

        try
        {
            //remove the group
            opSetPersPresence1.removeServerStoredContactGroup(
                opSetPersPresence1.getServerStoredContactListRoot()
                    .getGroup(testGroupName));
        }
        catch(OperationFailedException ex)
        {
            logger.error("error removing group", ex);
        }

        groupChangeCollector.waitForEvent(10000);

        opSetPersPresence1
            .removeServerStoredGroupChangeListener(groupChangeCollector);

        // check whether we got group created event
        assertEquals("Collected Group Change event",
                     1, groupChangeCollector.collectedEvents.size());

        assertEquals("Group name.",  testGroupName,
            ((ServerStoredGroupEvent)groupChangeCollector.collectedEvents
                .get(0)).getSourceGroup().getGroupName());

        // check whether the group is still on the contact list
        ContactGroup group = opSetPersPresence1.getServerStoredContactListRoot()
            .getGroup(testGroupName);

        assertNull("A freshly removed group was still on the contact list. - " + group,
                      group);
    }

    /**
     * Renames our test group and checks whether corresponding events are
     * triggered. Verifies whether the group has really changed its name and
     * whether it is findable by its new name. Also makes sure that it does
     * not exist under its previous name any more.
     */
    public void postTestRenameGroup()
    {
        logger.trace("Testing renaming groups.");

        ContactGroup group = opSetPersPresence1.getServerStoredContactListRoot()
                                .getGroup(testGroupName);

        //first add a listener
        GroupChangeCollector groupChangeCollector = new GroupChangeCollector();
        opSetPersPresence1
            .addServerStoredGroupChangeListener(groupChangeCollector);

        //change the name and wait for a confirmation event
        opSetPersPresence1.renameServerStoredContactGroup(group, testGroupName2);

        groupChangeCollector.waitForEvent(10000);

        opSetPersPresence1
            .removeServerStoredGroupChangeListener(groupChangeCollector);

        //examine the event
        assertEquals("Collected Group Change event",
                     1, groupChangeCollector.collectedEvents.size());

        assertEquals("Group name.",  testGroupName2,
            ((ServerStoredGroupEvent)groupChangeCollector.collectedEvents
                .get(0)).getSourceGroup().getGroupName());

        // check whether the group is still on the contact list
        ContactGroup oldGroup = opSetPersPresence1.getServerStoredContactListRoot()
            .getGroup(testGroupName);

        assertNull("A group was still findable by its old name after renaming.",
                      oldGroup);

        //make sure that we could find the group by its new name.
        ContactGroup newGroup = opSetPersPresence1.getServerStoredContactListRoot()
            .getGroup(testGroupName2);

        assertNotNull("Could not find a renamed group by its new name.",
                      newGroup);
    }

    /**
     * Create the contact list. Later will be test to be sure that creating is ok
     * @throws Exception
     */
    public void prepareContactList()
        throws Exception
    {
        logger.trace("prepareContactList");

        fixture.clearProvidersLists();

        waitFor(3000);

        String contactList = System.getProperty(
            YahooProtocolProviderServiceLick.CONTACT_LIST_PROPERTY_NAME, null);

        logger.debug("The "
                     + YahooProtocolProviderServiceLick.CONTACT_LIST_PROPERTY_NAME
                     + " property is set to=" + contactList);

        if(    contactList == null
            || contactList.trim().length() < 6)//at least 4 for a UIN, 1 for the
                                               // dot and 1 for the grp name
            throw new IllegalArgumentException(
                "The " +
                YahooProtocolProviderServiceLick.CONTACT_LIST_PROPERTY_NAME +
                " property did not contain a contact list.");
        StringTokenizer tokenizer = new StringTokenizer(contactList, " \n\t");

        logger.debug("tokens contained by the CL tokenized="
            +tokenizer.countTokens());

        Hashtable<String, List<String>> contactListToCreate = new Hashtable<String, List<String>>();

        //go over all group.uin tokens
        while (tokenizer.hasMoreTokens())
        {
            String groupUinToken = tokenizer.nextToken();
            int dotIndex = groupUinToken.indexOf(".");

            if ( dotIndex == -1 )
            {
                throw new IllegalArgumentException(groupUinToken
                    + " is not a valid Group.UIN token");
            }

            String groupName = groupUinToken.substring(0, dotIndex);
            String uin = groupUinToken.substring(dotIndex + 1);

            if(    groupName.trim().length() < 1
                || uin.trim().length() < 4 )
            {
                throw new IllegalArgumentException(
                    groupName + " or " + uin +
                    " are not a valid group name or yahoo UIN.");
            }

            //check if we've already seen this group and if not - add it
            List<String> uinInThisGroup = contactListToCreate.get(groupName);
            if (uinInThisGroup == null)
            {
                uinInThisGroup = new ArrayList<String>();
                contactListToCreate.put(groupName, uinInThisGroup);
            }

            uinInThisGroup.add(uin);
        }

        // now init the list
        Enumeration<String> newGroupsEnum = contactListToCreate.keys();

        GroupChangeCollector groupChangeCollector = new GroupChangeCollector();
        opSetPersPresence1.addServerStoredGroupChangeListener(groupChangeCollector);

        //go over all groups in the contactsToAdd table
        while (newGroupsEnum.hasMoreElements())
        {
            String groupName = newGroupsEnum.nextElement();
            logger.debug("Will add group " + groupName);

            opSetPersPresence1.createServerStoredContactGroup(
                opSetPersPresence1.getServerStoredContactListRoot(), groupName);

            groupChangeCollector.waitForEvent(3000);

            ContactGroup newlyCreatedGroup =
                opSetPersPresence1.getServerStoredContactListRoot().getGroup(groupName);

            Iterator<String> contactsToAddToThisGroup
                = contactListToCreate.get(groupName).iterator();
            while (contactsToAddToThisGroup.hasNext())
            {
                String id = contactsToAddToThisGroup.next();

                logger.debug("Will add buddy " + id);
                opSetPersPresence1.subscribe(newlyCreatedGroup, id);
            }
        }

        waitFor(4000);

        //store the created contact list for later reference
        YahooSlickFixture.preInstalledBuddyList = contactListToCreate;
    }

    private void waitFor(long time)
        throws Exception
    {
        Object o = new Object();
        synchronized(o)
        {
            o.wait(time);
        }
    }

    /**
     * The class would listen for and store received events delivered to
     * <tt>ServerStoredGroupListener</tt>s.
     */
    private class GroupChangeCollector implements ServerStoredGroupListener
    {
        public ArrayList<EventObject> collectedEvents = new ArrayList<EventObject>();

        /**
         * Blocks until at least one event is received or until waitFor
         * miliseconds pass (whicever happens first).
         *
         * @param waitFor the number of miliseconds that we should be waiting
         * for an event before simply bailing out.
         */
        public void waitForEvent(long waitFor)
        {
            synchronized(this)
            {
                if(collectedEvents.size() > 0)
                    return;

                try{
                    wait(waitFor);
                }
                catch (InterruptedException ex)
                {
                    logger.debug(
                        "Interrupted while waiting for a subscription evt", ex);
                }
            }
        }

        /**
         * Called whnever an indication is received that a new server stored
         * group is created.
         * @param evt a ServerStoredGroupChangeEvent containing a reference to
         * the newly created group.
         */
        public void groupCreated(ServerStoredGroupEvent evt)
        {
            synchronized(this)
            {
                logger.debug("Collected evt("+collectedEvents.size()+")= "+evt);
                collectedEvents.add(evt);
                notifyAll();
            }
        }

        /**
         * Called when an indication is received that the name of a server stored
         * contact group has changed.
         * @param evt a ServerStoredGroupChangeEvent containing the details of the
         * name change.
         */
        public void groupNameChanged(ServerStoredGroupEvent evt)
        {
            synchronized(this)
            {
                logger.debug("Collected evt("+collectedEvents.size()+")= "+evt);
                collectedEvents.add(evt);
                notifyAll();
            }
        }

        /**
         * Called whnever an indication is received that an existing server stored
         * group has been removed.
         * @param evt a ServerStoredGroupChangeEvent containing a reference to the
         * newly created group.
         */
        public void groupRemoved(ServerStoredGroupEvent evt)
        {
            synchronized(this)
            {
                logger.debug("Collected evt("+collectedEvents.size()+")= "+evt);
                collectedEvents.add(evt);
                notifyAll();
            }
        }

        /**
         * Called whnever an indication is received that an existing server
         * stored group has been resolved.
         * @param evt a ServerStoredGroupChangeEvent containing a reference to
         * the resolved group.
         */
        public void groupResolved(ServerStoredGroupEvent evt)
        {
            synchronized(this)
            {
                logger.debug("Collected evt("+collectedEvents.size()+")= "+evt);
                collectedEvents.add(evt);
                notifyAll();
            }
        }
    }
}