001/**
002 *
003 * Copyright 2003-2007 Jive Software.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.disco.packet;
018
019import java.util.ArrayList;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.HashSet;
023import java.util.LinkedList;
024import java.util.List;
025import java.util.Set;
026
027import org.jivesoftware.smack.XMPPConnection;
028import org.jivesoftware.smack.packet.IQ;
029import org.jivesoftware.smack.packet.IqData;
030import org.jivesoftware.smack.util.EqualsUtil;
031import org.jivesoftware.smack.util.HashCode;
032import org.jivesoftware.smack.util.StringUtils;
033import org.jivesoftware.smack.util.XmlStringBuilder;
034
035import org.jxmpp.util.XmppStringUtils;
036
037/**
038 * A DiscoverInfo IQ packet, which is used by XMPP clients to request and receive information
039 * to/from other XMPP entities.<p>
040 *
041 * The received information may contain one or more identities of the requested XMPP entity, and
042 * a list of supported features by the requested XMPP entity.
043 *
044 * @author Gaston Dombiak
045 */
046public class DiscoverInfo extends IQ implements DiscoverInfoView {
047
048    public static final String ELEMENT = QUERY_ELEMENT;
049    public static final String NAMESPACE = "http://jabber.org/protocol/disco#info";
050
051    private final List<Feature> features = new ArrayList<>();
052    private final Set<Feature> featuresSet = new HashSet<>();
053    private final List<Identity> identities = new ArrayList<>();
054    private final Set<String> identitiesSet = new HashSet<>();
055    private String node;
056    private boolean containsDuplicateFeatures;
057
058    DiscoverInfo(DiscoverInfoBuilder builder, boolean validate) {
059        super(builder, ELEMENT, NAMESPACE);
060
061        features.addAll(builder.getFeatures());
062        identities.addAll(builder.getIdentities());
063        node = builder.getNode();
064
065
066        for (Feature feature : features) {
067            boolean featureIsNew = featuresSet.add(feature);
068            if (!featureIsNew) {
069                containsDuplicateFeatures = true;
070            }
071        }
072
073        for (Identity identity : identities) {
074            identitiesSet.add(identity.getKey());
075        }
076
077        if (!validate) {
078            return;
079        }
080
081        if (containsDuplicateFeatures) {
082            throw new IllegalArgumentException("The disco#info request contains duplicate features.");
083        }
084    }
085
086    /**
087     * Deprecated.
088     *
089     * @deprecated use {@link DiscoverInfoBuilder} instead.
090     */
091    @Deprecated
092    // TODO: Remove in Smack 4.5.
093    public DiscoverInfo() {
094        super(ELEMENT, NAMESPACE);
095    }
096
097    /**
098     * Copy constructor.
099     *
100     * @param d TODO javadoc me please
101     */
102    public DiscoverInfo(DiscoverInfo d) {
103        super(d);
104
105        // Set node
106        node = d.getNode();
107
108        // Copy features
109        features.addAll(d.features);
110        featuresSet.addAll(d.featuresSet);
111
112        // Copy identities
113        identities.addAll(d.identities);
114        identitiesSet.addAll(d.identitiesSet);
115    }
116
117    /**
118     * Adds a new feature to the discovered information.
119     *
120     * @param feature the discovered feature
121     * @return true if the feature did not already exist.
122     * @deprecated use {@link DiscoverInfoBuilder#addFeature(String)} instead.
123     */
124    @Deprecated
125    // TODO: Remove in Smack 4.5.
126    public boolean addFeature(String feature) {
127        return addFeature(new Feature(feature));
128    }
129
130    /**
131     * Adds a collection of features to the packet. Does noting if featuresToAdd is null.
132     *
133     * @param featuresToAdd TODO javadoc me please
134     * @deprecated use {@link DiscoverInfoBuilder#addFeatures(Collection)} instead.
135     */
136    @Deprecated
137    // TODO: Remove in Smack 4.5.
138    public void addFeatures(Collection<String> featuresToAdd) {
139        if (featuresToAdd == null) return;
140        for (String feature : featuresToAdd) {
141            addFeature(feature);
142        }
143    }
144
145    /**
146     * Deprecated.
147     *
148     * @param feature the future.
149     * @return true if the feature is new.
150     * @deprecated use {@link DiscoverInfoBuilder#addFeature(DiscoverInfo.Feature)} instead.
151     */
152    @Deprecated
153    // TODO: Remove in Smack 4.5.
154    public boolean addFeature(Feature feature) {
155        features.add(feature);
156        boolean featureIsNew = featuresSet.add(feature);
157        if (!featureIsNew) {
158            containsDuplicateFeatures = true;
159        }
160        return featureIsNew;
161    }
162
163    @Override
164    public List<Feature> getFeatures() {
165        return Collections.unmodifiableList(features);
166    }
167
168    /**
169     * Adds a new identity of the requested entity to the discovered information.
170     *
171     * @param identity the discovered entity's identity
172     * @deprecated use {@link DiscoverInfoBuilder#addIdentity(DiscoverInfo.Identity)} instead.
173     */
174    @Deprecated
175    // TODO: Remove in Smack 4.5.
176    public void addIdentity(Identity identity) {
177        identities.add(identity);
178        identitiesSet.add(identity.getKey());
179    }
180
181    /**
182     * Adds identities to the DiscoverInfo stanza.
183     *
184     * @param identitiesToAdd TODO javadoc me please
185     * @deprecated use {@link DiscoverInfoBuilder#addIdentities(Collection)} instead.
186     */
187    @Deprecated
188    // TODO: Remove in Smack 4.5.
189    public void addIdentities(Collection<Identity> identitiesToAdd) {
190        if (identitiesToAdd == null) return;
191        for (Identity identity : identitiesToAdd) {
192            addIdentity(identity);
193        }
194    }
195
196    @Override
197    public List<Identity> getIdentities() {
198        return Collections.unmodifiableList(identities);
199    }
200
201    /**
202     * Returns true if this DiscoverInfo contains at least one Identity of the given category and type.
203     *
204     * @param category the category to look for.
205     * @param type the type to look for.
206     * @return true if this DiscoverInfo contains a Identity of the given category and type.
207     */
208    public boolean hasIdentity(String category, String type) {
209        String key = XmppStringUtils.generateKey(category, type);
210        return identitiesSet.contains(key);
211    }
212
213    /**
214     * Returns all Identities of the given category and type of this DiscoverInfo.
215     *
216     * @param category category the category to look for.
217     * @param type type the type to look for.
218     * @return a list of Identites with the given category and type.
219     */
220    public List<Identity> getIdentities(String category, String type) {
221        List<Identity> res = new ArrayList<>(identities.size());
222        for (Identity identity : identities) {
223            if (identity.getCategory().equals(category) && identity.getType().equals(type)) {
224                res.add(identity);
225            }
226        }
227        return res;
228    }
229
230    @Override
231    public String getNode() {
232        return node;
233    }
234
235    /**
236     * Sets the node attribute that supplements the 'jid' attribute. A node is merely
237     * something that is associated with a JID and for which the JID can provide information.<p>
238     *
239     * Node attributes SHOULD be used only when trying to provide or query information which
240     * is not directly addressable.
241     *
242     * @param node the node attribute that supplements the 'jid' attribute
243     * @deprecated use {@link DiscoverInfoBuilder#setNode(String)} instead.
244     */
245    @Deprecated
246    // TODO: Remove in Smack 4.5.
247    public void setNode(String node) {
248        this.node = StringUtils.requireNullOrNotEmpty(node, "The node can not be the empty string");
249    }
250
251    /**
252     * Returns true if the specified feature is part of the discovered information.
253     *
254     * @param feature the feature to check
255     * @return true if the requests feature has been discovered
256     */
257    public boolean containsFeature(CharSequence feature) {
258        return features.contains(new Feature(feature));
259    }
260
261    public static boolean nullSafeContainsFeature(DiscoverInfo discoverInfo, CharSequence feature) {
262        if (discoverInfo == null) {
263            return false;
264        }
265
266        return discoverInfo.containsFeature(feature);
267    }
268
269    @Override
270    protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
271        xml.optAttribute("node", getNode());
272        xml.rightAngleBracket();
273        for (Identity identity : identities) {
274            xml.append(identity.toXML());
275        }
276        for (Feature feature : features) {
277            xml.append(feature.toXML());
278        }
279
280        return xml;
281    }
282
283    /**
284     * Test if a DiscoverInfo response contains duplicate identities.
285     *
286     * @return true if duplicate identities where found, otherwise false
287     */
288    public boolean containsDuplicateIdentities() {
289        List<Identity> checkedIdentities = new LinkedList<>();
290        for (Identity i : identities) {
291            for (Identity i2 : checkedIdentities) {
292                if (i.equals(i2))
293                    return true;
294            }
295            checkedIdentities.add(i);
296        }
297        return false;
298    }
299
300    /**
301     * Test if a DiscoverInfo response contains duplicate features.
302     *
303     * @return true if duplicate identities where found, otherwise false
304     */
305    public boolean containsDuplicateFeatures() {
306        return containsDuplicateFeatures;
307    }
308
309    public DiscoverInfoBuilder asBuilder(String stanzaId) {
310        return new DiscoverInfoBuilder(this, stanzaId);
311    }
312
313    /**
314     * Deprecated, do not use.
315     *
316     * @deprecated use {@link #asBuilder(String)} instead.
317     */
318    // TODO: Remove in Smack 4.5.
319    @Deprecated
320    @Override
321    public DiscoverInfo clone() {
322        return new DiscoverInfo(this);
323    }
324
325    public static DiscoverInfoBuilder builder(XMPPConnection connection) {
326        return new DiscoverInfoBuilder(connection);
327    }
328
329    public static DiscoverInfoBuilder builder(IqData iqData) {
330        return new DiscoverInfoBuilder(iqData);
331    }
332
333    public static DiscoverInfoBuilder builder(String stanzaId) {
334        return new DiscoverInfoBuilder(stanzaId);
335    }
336
337    /**
338     * Represents the identity of a given XMPP entity. An entity may have many identities but all
339     * the identities SHOULD have the same name.<p>
340     *
341     * Refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>
342     * in order to get the official registry of values for the <i>category</i> and <i>type</i>
343     * attributes.
344     *
345     */
346    public static final class Identity implements Comparable<Identity> {
347
348        private final String category;
349        private final String type;
350        private final String key;
351        private final String name;
352        private final String lang; // 'xml:lang;
353
354        /**
355         * Creates a new identity for an XMPP entity.
356         *
357         * @param category the entity's category (required as per XEP-30).
358         * @param type the entity's type (required as per XEP-30).
359         */
360        public Identity(String category, String type) {
361            this(category, type, null, null);
362        }
363
364        /**
365         * Creates a new identity for an XMPP entity.
366         * 'category' and 'type' are required by
367         * <a href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
368         *
369         * @param category the entity's category (required as per XEP-30).
370         * @param name the entity's name.
371         * @param type the entity's type (required as per XEP-30).
372         */
373        public Identity(String category, String name, String type) {
374            this(category, type, name, null);
375        }
376
377        /**
378         * Creates a new identity for an XMPP entity.
379         * 'category' and 'type' are required by
380         * <a href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
381         *
382         * @param category the entity's category (required as per XEP-30).
383         * @param type the entity's type (required as per XEP-30).
384         * @param name the entity's name.
385         * @param lang the entity's lang.
386         */
387        public Identity(String category, String type, String name, String lang) {
388            this.category = StringUtils.requireNotNullNorEmpty(category, "category cannot be null");
389            this.type = StringUtils.requireNotNullNorEmpty(type, "type cannot be null");
390            this.key = XmppStringUtils.generateKey(category, type);
391            this.name = name;
392            this.lang = lang;
393        }
394
395        /**
396         * Returns the entity's category. To get the official registry of values for the
397         * 'category' attribute refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>.
398         *
399         * @return the entity's category.
400         */
401        public String getCategory() {
402            return category;
403        }
404
405        /**
406         * Returns the identity's name.
407         *
408         * @return the identity's name.
409         */
410        public String getName() {
411            return name;
412        }
413
414        /**
415         * Returns the entity's type. To get the official registry of values for the
416         * 'type' attribute refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>.
417         *
418         * @return the entity's type.
419         */
420        public String getType() {
421            return type;
422        }
423
424        /**
425         * Returns the identities natural language if one is set.
426         *
427         * @return the value of xml:lang of this Identity
428         */
429        public String getLanguage() {
430            return lang;
431        }
432
433        private String getKey() {
434            return key;
435        }
436
437        /**
438         * Returns true if this identity is of the given category and type.
439         *
440         * @param category the category.
441         * @param type the type.
442         * @return true if this identity is of the given category and type.
443         */
444        public boolean isOfCategoryAndType(String category, String type) {
445            return this.category.equals(category) && this.type.equals(type);
446        }
447
448        public XmlStringBuilder toXML() {
449            XmlStringBuilder xml = new XmlStringBuilder();
450            xml.halfOpenElement("identity");
451            xml.xmllangAttribute(lang);
452            xml.attribute("category", category);
453            xml.optAttribute("name", name);
454            xml.optAttribute("type", type);
455            xml.closeEmptyElement();
456            return xml;
457        }
458
459        /**
460         * Check equality for Identity  for category, type, lang and name
461         * in that order as defined by
462         * <a href="http://xmpp.org/extensions/xep-0115.html#ver-proc">XEP-0015 5.4 Processing Method (Step 3.3)</a>.
463         *
464         */
465        @Override
466        public boolean equals(Object obj) {
467            return EqualsUtil.equals(this, obj, (e, o) -> {
468                e.append(key, o.key)
469                 .append(lang, o.lang)
470                 .append(name, o.name);
471            });
472        }
473
474        private final HashCode.Cache hashCodeCache = new HashCode.Cache();
475
476        @Override
477        public int hashCode() {
478            return hashCodeCache.getHashCode(c ->
479                c.append(key)
480                 .append(lang)
481                 .append(name)
482            );
483        }
484
485        /**
486         * Compares this identity with another one. The comparison order is: Category, Type, Lang.
487         * If all three are identical the other Identity is considered equal. Name is not used for
488         * comparison, as defined by XEP-0115
489         *
490         * @param other TODO javadoc me please
491         * @return a negative integer, zero, or a positive integer as this object is less than,
492         *         equal to, or greater than the specified object.
493         */
494        @Override
495        public int compareTo(DiscoverInfo.Identity other) {
496            String otherLang = other.lang == null ? "" : other.lang;
497            String thisLang = lang == null ? "" : lang;
498
499            // This can be removed once the deprecated constructor is removed.
500            String otherType = other.type == null ? "" : other.type;
501            String thisType = type == null ? "" : type;
502
503            if (category.equals(other.category)) {
504                if (thisType.equals(otherType)) {
505                    if (thisLang.equals(otherLang)) {
506                        // Don't compare on name, XEP-30 says that name SHOULD
507                        // be equals for all identities of an entity
508                        return 0;
509                    } else {
510                        return thisLang.compareTo(otherLang);
511                    }
512                } else {
513                    return thisType.compareTo(otherType);
514                }
515            } else {
516                return category.compareTo(other.category);
517            }
518        }
519
520        @Override
521        public String toString() {
522            return toXML().toString();
523        }
524    }
525
526    /**
527     * Represents the features offered by the item. This information helps the requester to determine
528     * what actions are possible with regard to this item (registration, search, join, etc.)
529     * as well as specific feature types of interest, if any (e.g., for the purpose of feature
530     * negotiation).
531     */
532    public static final class Feature {
533
534        private final String variable;
535
536        public Feature(Feature feature) {
537            this.variable = feature.variable;
538        }
539
540        public Feature(CharSequence variable) {
541            this(variable.toString());
542        }
543
544        /**
545         * Creates a new feature offered by an XMPP entity or item.
546         *
547         * @param variable the feature's variable.
548         */
549        public Feature(String variable) {
550            this.variable = StringUtils.requireNotNullNorEmpty(variable, "variable cannot be null");
551        }
552
553        /**
554         * Returns the feature's variable.
555         *
556         * @return the feature's variable.
557         */
558        public String getVar() {
559            return variable;
560        }
561
562        public XmlStringBuilder toXML() {
563            XmlStringBuilder xml = new XmlStringBuilder();
564            xml.halfOpenElement("feature");
565            xml.attribute("var", variable);
566            xml.closeEmptyElement();
567            return xml;
568        }
569
570        @Override
571        public boolean equals(Object obj) {
572            return EqualsUtil.equals(this, obj, (e, o) -> {
573                e.append(variable, o.variable);
574            });
575        }
576
577        @Override
578        public int hashCode() {
579            return variable.hashCode();
580        }
581
582        @Override
583        public String toString() {
584            return toXML().toString();
585        }
586    }
587}