aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/jabber/ScServiceDiscoveryManager.java
blob: de2ce3eb263198c51aca4f60cd4d2a5bdf96dace (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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
/*
 * 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.impl.protocol.jabber;

import java.util.*;
import java.util.concurrent.*;

import net.java.sip.communicator.impl.protocol.jabber.extensions.caps.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.util.*;
import org.jivesoftware.smackx.*;
import org.jivesoftware.smackx.packet.*;

/**
 * An wrapper to smack's default {@link ServiceDiscoveryManager} that adds
 * support for XEP-0115 - Entity Capabilities.
 *
 * This work is based on Jonas Adahl's smack fork.
 *
 * @author Emil Ivov
 * @author Lubomir Marinov
 */
public class ScServiceDiscoveryManager
    implements PacketInterceptor,
               NodeInformationProvider
{
    /**
     * The <tt>Logger</tt> used by the <tt>ScServiceDiscoveryManager</tt>
     * class and its instances for logging output.
     */
    private static final Logger logger
        = Logger.getLogger(ScServiceDiscoveryManager.class);

    /**
     * The flag which indicates whether we are currently storing non-caps.
     */
    private final boolean cacheNonCaps;

    /**
     * The cache of non-caps. Used only if {@link #cacheNonCaps} is
     * <tt>true</tt>.
     */
    private final Map<String, DiscoverInfo> nonCapsCache
        = new ConcurrentHashMap<String, DiscoverInfo>();

    /**
     * The <tt>EntitiCapsManager</tt> used by this instance to handle entity
     * capabilities.
     */
    private final EntityCapsManager capsManager;

    /**
     * The {@link ServiceDiscoveryManager} that we are wrapping.
     */
    private final ServiceDiscoveryManager discoveryManager;

    /**
     * The parent provider
     */
    private final ProtocolProviderService parentProvider;

    /**
     * The {@link Connection} that this manager is responsible for.
     */
    private final Connection connection;

    /**
     * A local copy that we keep in sync with {@link ServiceDiscoveryManager}'s
     * feature list that as we add and remove features to it.
     */
    private final List<String> features;

    /**
     * The unmodifiable view of {@link #features} which can be exposed to the
     * public through {@link #getFeatures()}, for example.
     */
    private final List<String> unmodifiableFeatures;

    /**
     * A {@link List} of the identities we use in our disco answers.
     */
    private final List<DiscoverInfo.Identity> identities;

    /**
     * Capabilities to put in ext attribute of capabilities stanza.
     */
    private final List<String> extCapabilities = new ArrayList<String>();

    /**
     * The runnable responsible for retrieving discover info.
     */
    private DiscoveryInfoRetriever retriever = new DiscoveryInfoRetriever();

    /**
     * Creates a new <tt>ScServiceDiscoveryManager</tt> wrapping the default
     * discovery manager of the specified <tt>connection</tt>.
     *
     * @param parentProvider the parent provider that creates discovery manager.
     * @param connection Smack connection object that will be used by this
     * instance to handle XMPP connection.
     * @param featuresToRemove an array of <tt>String</tt>s representing the
     * features to be removed from the <tt>ServiceDiscoveryManager</tt> of the
     * specified <tt>connection</tt> which is to be wrapped by the new instance
     * @param featuresToAdd an array of <tt>String</tt>s representing the
     * features to be added to the new instance and to the
     * <tt>ServiceDiscoveryManager</tt> of the specified <tt>connection</tt>
     * which is to be wrapped by the new instance
     * @param cacheNonCaps <tt>true</tt> if we want to cache entity features
     *                     even though it does not support XEP-0115
     */
    public ScServiceDiscoveryManager(
            ProtocolProviderService parentProvider,
            Connection connection,
            String[] featuresToRemove,
            String[] featuresToAdd,
            boolean cacheNonCaps)
    {
        this.parentProvider = parentProvider;
        this.connection = connection;

        this.discoveryManager
            = ServiceDiscoveryManager.getInstanceFor(connection);

        this.features = new ArrayList<String>();
        this.unmodifiableFeatures = Collections.unmodifiableList(this.features);
        this.identities = new ArrayList<DiscoverInfo.Identity>();

        this.cacheNonCaps = cacheNonCaps;

        DiscoverInfo.Identity identity
            = new DiscoverInfo.Identity(
                    "client",
                    ServiceDiscoveryManager.getIdentityName());

        identity.setType(ServiceDiscoveryManager.getIdentityType());
        identities.add(identity);

        //add support for capabilities
        discoveryManager.addFeature(CapsPacketExtension.NAMESPACE);

        /*
         * Reflect featuresToRemove and featuresToAdd before
         * updateEntityCapsVersion() in order to persist only the complete
         * node#ver association with our own DiscoverInfo. Otherwise, we'd
         * persist all intermediate ones upon each addFeature() and
         * removeFeature().
         */
        // featuresToRemove
        if (featuresToRemove != null)
        {
            for (String featureToRemove : featuresToRemove)
                discoveryManager.removeFeature(featureToRemove);
        }
        // featuresToAdd
        if (featuresToAdd != null)
        {
            for (String featureToAdd : featuresToAdd)
                if (!discoveryManager.includesFeature(featureToAdd))
                    discoveryManager.addFeature(featureToAdd);
        }

        // For every XMPPConnection, add one EntityCapsManager.
        this.capsManager = new EntityCapsManager();
        capsManager.addPacketListener(connection);

        /*
         * XXX initFeatures() has to happen before updateEntityCapsVersion().
         * Otherwise, updateEntityCapsVersion() will not include the features of
         * the wrapped discoveryManager.
         */
        initFeatures();
        updateEntityCapsVersion();

        // Now, make sure we intercept presence packages and add caps data when
        // intended. XEP-0115 specifies that a client SHOULD include entity
        // capabilities with every presence notification it sends.
        connection.addPacketInterceptor(
                this,
                new PacketTypeFilter(Presence.class));
    }

    /**
     * Registers that a new feature is supported by this XMPP entity. When this
     * client is queried for its information the registered features will be
     * answered.
     * <p>
     * Since no packet is actually sent to the server it is safe to perform
     * this operation before logging to the server. In fact, you may want to
     * configure the supported features before logging to the server so that
     * the information is already available if it is required upon login.
     *
     * @param feature the feature to register as supported.
     */
    public void addFeature(String feature)
    {
        synchronized (features)
        {
            features.add(feature);
            discoveryManager.addFeature(feature);
        }
        updateEntityCapsVersion();
    }

    /**
     * Recalculates the entity capabilities caps ver string according to what's
     * currently available in our own discovery info.
     */
    private void updateEntityCapsVersion()
    {
        // If a XMPPConnection is the managed one, see that the new version is
        // updated
        if ((connection != null) && (capsManager != null))
            capsManager.calculateEntityCapsVersion(getOwnDiscoverInfo());
    }

    /**
     * Returns a reference to our local copy of the feature list supported by
     * this implementation.
     *
     * @return a reference to our local copy of the feature list supported by
     * this implementation.
     */
    public List<String> getFeatures()
    {
        return unmodifiableFeatures;
    }

    /**
     * Get a DiscoverInfo for the current entity caps node.
     *
     * @return a DiscoverInfo for the current entity caps node
     */
    public DiscoverInfo getOwnDiscoverInfo()
    {
        DiscoverInfo di = new DiscoverInfo();

        di.setType(IQ.Type.RESULT);
        di.setNode(capsManager.getNode() + "#" + getEntityCapsVersion());

        // Add discover info
        addDiscoverInfoTo(di);
        return di;
    }

    /**
     * Returns the caps version as returned by our caps manager or <tt>null</tt>
     * if we don't have a caps manager yet.
     *
     * @return the caps version as returned by our caps manager or <tt>null</tt>
     * if we don't have a caps manager yet.
     */
    private String getEntityCapsVersion()
    {
        return (capsManager == null) ? null : capsManager.getCapsVersion();
    }

    /**
     * Populates a specific <tt>DiscoverInfo</tt> with the identity and features
     * of the current entity caps node.
     *
     * @param response the discover info response packet
     */
    private void addDiscoverInfoTo(DiscoverInfo response)
    {
        // Set this client identity
        DiscoverInfo.Identity identity
            = new DiscoverInfo.Identity(
                    "client",
                    ServiceDiscoveryManager.getIdentityName());

        identity.setType(ServiceDiscoveryManager.getIdentityType());
        response.addIdentity(identity);

        // Add the registered features to the response

        // Add Entity Capabilities (XEP-0115) feature node.
        /*
         * XXX Only addFeature if !containsFeature. Otherwise, the DiscoverInfo
         * may end up with repeating features.
         */
        if (!response.containsFeature(CapsPacketExtension.NAMESPACE))
            response.addFeature(CapsPacketExtension.NAMESPACE);

        Iterable<String> features = getFeatures();

        synchronized (features)
        {
            for (String feature : features)
                if (!response.containsFeature(feature))
                    response.addFeature(feature);
        }
    }

    /**
     * Returns <tt>true</tt> if the specified feature is registered in our
     * {@link ServiceDiscoveryManager} and <tt>false</tt> otherwise.
     *
     * @param feature the feature to look for.
     *
     * @return a boolean indicating if the specified featured is registered or
     * not.
     */
    public boolean includesFeature(String feature)
    {
        return this.discoveryManager.includesFeature(feature);
    }

    /**
     * Removes the specified feature from the supported features by the
     * encapsulated ServiceDiscoveryManager.<p>
     *
     * Since no packet is actually sent to the server it is safe to perform
     * this operation before logging to the server.
     *
     * @param feature the feature to remove from the supported features.
     */
    public void removeFeature(String feature)
    {
        synchronized (features)
        {
            features.remove(feature);
            discoveryManager.removeFeature(feature);
        }
        updateEntityCapsVersion();
    }

    /**
     * Add feature to put in "ext" attribute.
     *
     * @param ext ext feature to add
     */
    public void addExtFeature(String ext)
    {
        synchronized(extCapabilities)
        {
            extCapabilities.add(ext);
        }
    }

    /**
     * Remove "ext" feature.
     *
     * @param ext ext feature to remove
     */
    public void removeExtFeature(String ext)
    {
        synchronized(extCapabilities)
        {
            extCapabilities.remove(ext);
        }
    }

    /**
     * Get "ext" value.
     *
     * @return string that represents "ext" value
     */
    public synchronized String getExtFeatures()
    {
        StringBuilder bldr = new StringBuilder("");

        for(String e : extCapabilities)
        {
            bldr.append(e);
            bldr.append(" ");
        }

        return bldr.toString();
    }

    /**
     * Intercepts outgoing presence packets and adds entity capabilities at
     * their ends.
     *
     * @param packet the (hopefully presence) packet we need to add a "c"
     * element to.
     */
    public void interceptPacket(Packet packet)
    {
        if ((packet instanceof Presence) && (capsManager != null))
        {
            String ver = getEntityCapsVersion();
            CapsPacketExtension caps
                = new CapsPacketExtension(
                        getExtFeatures(),
                        capsManager.getNode(),
                        CapsPacketExtension.HASH_METHOD,
                        ver);

            //make sure we'll be able to handle requests for the newly generated
            //node once we've used it.
            discoveryManager.setNodeInformationProvider(
                    caps.getNode() + "#" + caps.getVersion(),
                    this);

            // Remove old capabilities extension if present
            PacketExtension oldCaps
                = packet.getExtension(
                        CapsPacketExtension.ELEMENT_NAME,
                        CapsPacketExtension.NAMESPACE);
            if (oldCaps != null)
            {
                packet.removeExtension(oldCaps);
            }
            // Put new capabilities extension
            packet.addExtension(caps);
        }
    }

    /**
     * Returns a list of the Items
     * {@link org.jivesoftware.smackx.packet.DiscoverItems.Item} defined in the
     * node or in other words <tt>null</tt> since we don't support any.
     *
     * @return always <tt>null</tt> since we don't support items.
     */
    public List<DiscoverItems.Item> getNodeItems()
    {
        return null;
    }

    /**
     * Returns a list of the features defined in the node. For
     * example, the entity caps protocol specifies that an XMPP client
     * should answer with each feature supported by the client version
     * or extension.
     *
     * @return a list of the feature strings defined in the node.
     */
    public List<String> getNodeFeatures()
    {
        return getFeatures();
    }

    /**
     * Returns a list of the identities defined in the node. For example, the
     * x-command protocol must provide an identity of category automation and
     * type command-node for each command.
     *
     * @return a list of the Identities defined in the node.
     */
    public List<DiscoverInfo.Identity> getNodeIdentities()
    {
        return identities;
    }

    /**
     * Initialize our local features copy in a way that would
     */
    private void initFeatures()
    {
        Iterator<String> defaultFeatures = discoveryManager.getFeatures();

        synchronized (features)
        {
            while (defaultFeatures.hasNext())
            {
                String feature = defaultFeatures.next();

                this.features.add( feature );
            }
        }
    }

    /**
     * Returns the discovered information of a given XMPP entity addressed by
     * its JID.
     *
     * @param entityID the address of the XMPP entity.
     * @return the discovered information.
     * @throws XMPPException if the operation failed for some reason.
     */
    public DiscoverInfo discoverInfo(String entityID)
        throws XMPPException
    {
        DiscoverInfo discoverInfo = capsManager.getDiscoverInfoByUser(entityID);

        if (discoverInfo != null)
            return discoverInfo;

        EntityCapsManager.Caps caps = capsManager.getCapsByUser(entityID);

        // if caps is not valid, has empty hash
        if (cacheNonCaps && (caps == null || !caps.isValid(discoverInfo)))
        {
            discoverInfo = nonCapsCache.get(entityID);
            if (discoverInfo != null)
                return discoverInfo;
        }

        discoverInfo
            = discoverInfo(
                    entityID,
                    (caps == null) ? null : caps.getNodeVer());

        if ((caps != null) && !caps.isValid(discoverInfo))
        {
            if(!caps.hash.equals(""))
            {
                logger.error(
                        "Invalid DiscoverInfo for " + caps.getNodeVer() + ": "
                            + discoverInfo);
            }
            caps = null;
        }

        if (caps == null)
        {
            if (cacheNonCaps)
                nonCapsCache.put(entityID, discoverInfo);
        }
        else
            EntityCapsManager.addDiscoverInfoByCaps(caps, discoverInfo);
        return discoverInfo;
    }

    /**
     * Returns the discovered information of a given XMPP entity addressed by
     * its JID if locally cached, otherwise schedules for retrieval.
     *
     * @param entityID the address of the XMPP entity.
     * @return the discovered information.
     * @throws XMPPException if the operation failed for some reason.
     */
    public DiscoverInfo discoverInfoNonBlocking(String entityID)
        throws XMPPException
    {
        DiscoverInfo discoverInfo = capsManager.getDiscoverInfoByUser(entityID);

        if (discoverInfo != null)
            return discoverInfo;

        EntityCapsManager.Caps caps = capsManager.getCapsByUser(entityID);

        // if caps is not valid, has empty hash
        if (cacheNonCaps && (caps == null || !caps.isValid(discoverInfo)))
        {
            discoverInfo = nonCapsCache.get(entityID);
            if (discoverInfo != null)
                return discoverInfo;
        }

        // add to retrieve thread
        retriever.addEntityForRetrieve(
            entityID,
            caps);

        return null;
    }

    /**
     * Returns the discovered information of a given XMPP entity addressed by
     * its JID and note attribute. Use this message only when trying to query
     * information which is not directly addressable.
     *
     * @param entityID the address of the XMPP entity.
     * @param node the attribute that supplements the 'jid' attribute.
     *
     * @return the discovered information.
     *
     * @throws XMPPException if the operation failed for some reason.
     */
    public DiscoverInfo discoverInfo(String entityID, String node)
        throws XMPPException
    {
        return discoveryManager.discoverInfo(entityID, node);
    }

    /**
     * Returns the discovered items of a given XMPP entity addressed by its JID.
     *
     * @param entityID the address of the XMPP entity.
     *
     * @return the discovered information.
     *
     * @throws XMPPException if the operation failed for some reason.
     */
    public DiscoverItems discoverItems(String entityID) throws XMPPException
    {
        return discoveryManager.discoverItems(entityID);
    }

    /**
     * Returns the discovered items of a given XMPP entity addressed by its JID
     * and note attribute. Use this message only when trying to query
     * information which is not directly addressable.
     *
     * @param entityID the address of the XMPP entity.
     * @param node the attribute that supplements the 'jid' attribute.
     *
     * @return the discovered items.
     *
     * @throws XMPPException if the operation failed for some reason.
     */
    public DiscoverItems discoverItems(String entityID, String node)
        throws XMPPException
    {
        return discoveryManager.discoverItems(entityID, node);
    }

    /**
     * Returns <tt>true</tt> if <tt>jid</tt> supports the specified
     * <tt>feature</tt> and <tt>false</tt> otherwise. The method may check the
     * information locally if we've already cached this <tt>jid</tt>'s disco
     * info, or retrieve it from the network.
     *
     * @param jid the jabber ID we'd like to test for support
     * @param feature the URN feature we are interested in
     *
     * @return true if <tt>jid</tt> is discovered to support <tt>feature</tt>
     * and <tt>false</tt> otherwise.
     */
    public boolean supportsFeature(String jid, String feature)
    {
        DiscoverInfo info;

        try
        {
            info = this.discoverInfo(jid);
        }
        catch(XMPPException ex)
        {
            logger.info("failed to retrieve disco info for " + jid
                                + " feature " + feature, ex);
            return false;
        }

        return ((info != null) && info.containsFeature(feature));
    }

    /**
     * Gets the <tt>EntityCapsManager</tt> which handles the entity capabilities
     * for this <tt>ScServiceDiscoveryManager</tt>.
     *
     * @return the <tt>EntityCapsManager</tt> which handles the entity
     * capabilities for this <tt>ScServiceDiscoveryManager</tt>
     */
    public EntityCapsManager getCapsManager()
    {
        return capsManager;
    }

    /**
     * Clears/stops what's needed.
     */
    public void stop()
    {
        if(retriever != null)
            retriever.stop();
    }

    /**
     * Thread that runs the discovery info.
     */
    private class DiscoveryInfoRetriever
        implements Runnable
    {
        /**
         * start/stop.
         */
        private boolean stopped = true;

        /**
         * The thread that runs this dispatcher.
         */
        private Thread retrieverThread = null;

        /**
         * Entities to be processed and their caps.
         * HashMap so we can store null caps.
         */
        private Map<String, EntityCapsManager.Caps> entities
            = new HashMap<String, EntityCapsManager.Caps>();

        /**
         * Our capability operation set.
         */
        private OperationSetContactCapabilitiesJabberImpl capabilitiesOpSet;

        /**
         * Runs in different thread.
         */
        public void run()
        {
            try
            {
                stopped = false;

                while(!stopped)
                {
                    Map.Entry<String, EntityCapsManager.Caps>
                        entityToProcess = null;

                    synchronized(entities)
                    {
                        if(entities.size() == 0)
                        {
                            try
                            {
                                entities.wait();
                            }
                            catch (InterruptedException iex){}
                        }

                        Iterator<Map.Entry<String, EntityCapsManager.Caps>>
                            iter = entities.entrySet().iterator();
                        if(iter.hasNext())
                        {
                            entityToProcess = iter.next();
                            iter.remove();
                        }
                    }

                    if(entityToProcess != null)
                    {
                        // process
                        requestDiscoveryInfo(
                            entityToProcess.getKey(),
                            entityToProcess.getValue());
                    }

                    entityToProcess = null;
                }
            } catch(Throwable t)
            {
                logger.error("Error requesting discovery info, " +
                    "thread ended unexpectedly", t);
            }
        }

        /**
         * Requests the discovery info and fires the event if
         * retrieved.
         * @param entityID the entity to request
         * @param caps and its capability.
         */
        private void requestDiscoveryInfo(final String entityID,
                                          EntityCapsManager.Caps caps)
        {
            try
            {
                DiscoverInfo discoverInfo = discoverInfo(
                            entityID,
                            (caps == null ) ? null : caps.getNodeVer());

                if ((caps != null) && !caps.isValid(discoverInfo))
                {
                    if(!caps.hash.equals(""))
                    {
                        logger.error("Invalid DiscoverInfo for "
                            + caps.getNodeVer() + ": " + discoverInfo);
                    }
                    caps = null;
                }

                boolean fireEvent = false;

                if (caps == null)
                {
                    if (cacheNonCaps)
                    {
                        nonCapsCache.put(entityID, discoverInfo);
                        fireEvent = true;
                    }
                }
                else
                {
                    EntityCapsManager.addDiscoverInfoByCaps(caps, discoverInfo);
                    fireEvent = true;
                }

                // fire event
                if(fireEvent && capabilitiesOpSet != null)
                {
                    capabilitiesOpSet.fireContactCapabilitiesChanged(
                        entityID,
                        capsManager.getFullJidsByBareJid(
                            StringUtils.parseBareAddress(entityID))
                        );
                }
            }
            catch(XMPPException ex)
            {
                // print discovery info errors only when trace is enabled
                if(logger.isTraceEnabled())
                    logger.error("Error requesting discover info for "
                        + entityID, ex);
            }
        }

        /**
         * Queue entities for retrieval.
         * @param entityID the entity.
         * @param caps and its capability.
         */
        public void addEntityForRetrieve(String entityID,
                                         EntityCapsManager.Caps caps)
        {
            synchronized(entities)
            {

                if(!entities.containsKey(entityID))
                {
                    entities.put(entityID, caps);
                    entities.notifyAll();

                    if(retrieverThread == null)
                    {
                        start();
                    }
                }
            }
        }

        /**
         * Start thread.
         */
        private void start()
        {
            capabilitiesOpSet = (OperationSetContactCapabilitiesJabberImpl)
                parentProvider.getOperationSet(
                    OperationSetContactCapabilities.class);

            retrieverThread = new Thread(
                this,
                ScServiceDiscoveryManager.class.getName());
            retrieverThread.setDaemon(true);

            retrieverThread.start();


        }

        /**
         * Stops and clears.
         */
        void stop()
        {
            synchronized(entities)
            {
                stopped = true;
                entities.notifyAll();

                retrieverThread = null;
            }
        }
    }
}