RosterItem.java 22 KB
Newer Older
1
/**
2
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
3
 *
4 5 6 7 8 9 10 11 12 13 14
 * 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.
15 16
 */

17
package org.jivesoftware.openfire.roster;
18

19 20 21 22 23 24
import org.jivesoftware.openfire.SharedGroupException;
import org.jivesoftware.openfire.group.Group;
import org.jivesoftware.openfire.group.GroupManager;
import org.jivesoftware.openfire.group.GroupNotFoundException;
import org.jivesoftware.openfire.user.UserNameManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
Gaston Dombiak's avatar
Gaston Dombiak committed
25 26
import org.jivesoftware.util.cache.CacheSizes;
import org.jivesoftware.util.cache.Cacheable;
27
import org.jivesoftware.util.cache.CannotCalculateSizeException;
Gaston Dombiak's avatar
Gaston Dombiak committed
28
import org.jivesoftware.util.cache.ExternalizableUtil;
29 30
import org.xmpp.packet.JID;

Gaston Dombiak's avatar
Gaston Dombiak committed
31 32 33 34
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
import java.util.*;

/**
 * <p>Represents a single roster item for a User's Roster.</p>
 * <p>The server doesn't need to know anything about roster groups so they are
 * not stored with easy retrieval or manipulation in mind. The important data
 * elements of a roster item (beyond the jid adddress of the roster entry) includes:</p>
 * <ul>
 * <li>nick   - A nickname for the user when used in this roster</li>
 * <li>sub    - A subscription type: to, from, none, both</li>
 * <li>ask    - An optional subscription ask status: subscribe, unsubscribe</li>
 * <li>groups - A list of groups to organize roster entries under (e.g. friends, co-workers, etc)</li>
 * </ul>
 *
 * @author Gaston Dombiak
 */
Gaston Dombiak's avatar
Gaston Dombiak committed
51
public class RosterItem implements Cacheable, Externalizable {
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
    public enum SubType {

        /**
         * Indicates the roster item should be removed.
         */
        REMOVE(-1),
        /**
         * No subscription is established.
         */
        NONE(0),
        /**
         * The roster owner has a subscription to the roster item's presence.
         */
        TO(1),
        /**
         * The roster item has a subscription to the roster owner's presence.
         */
        FROM(2),
        /**
         * The roster item and owner have a mutual subscription.
         */
        BOTH(3);

        private final int value;

        SubType(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        public String getName() {
            return name().toLowerCase();
88 89 90
        }

        public static SubType getTypeFromInt(int value) {
91 92 93 94 95 96
            for (SubType subType : values()) {
                if (subType.value == value) {
                    return subType;
                }
            }
            return null;
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
    public enum AskType {

        /**
         * The roster item has no pending subscription requests.
         */
        NONE(-1),
        /**
         * The roster item has been asked for permission to subscribe to their presence
         * but no response has been received.
         */
        SUBSCRIBE(0),
        /**
         * The roster owner has asked to the roster item to unsubscribe from it's
         * presence but has not received confirmation.
         */
        UNSUBSCRIBE(1);

        private final int value;

        AskType(int value) {
            this.value = value;

        }

        public int getValue() {
            return value;
126 127 128
        }

        public static AskType getTypeFromInt(int value) {
129 130 131 132 133 134
            for (AskType askType : values()) {
                if (askType.value == value) {
                    return askType;
                }
            }
            return null;
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
    public enum RecvType {

        /**
         * There are no subscriptions that have been received but not presented to the user.
         */
        NONE(-1),
        /**
         * The server has received a subscribe request, but has not forwarded it to the user.
         */
        SUBSCRIBE(1),
        /**
         * The server has received an unsubscribe request, but has not forwarded it to the user.
         */
        UNSUBSCRIBE(2);

        private final int value;

        RecvType(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
161 162 163
        }

        public static RecvType getTypeFromInt(int value) {
164 165 166 167 168 169
            for (RecvType recvType : values()) {
                if (recvType.value == value) {
                    return recvType;
                }
            }
            return null;
170 171 172 173 174 175
        }
    }

    /**
     * <p>Indicates the roster item should be removed.</p>
     */
176
    public static final SubType SUB_REMOVE = SubType.REMOVE;
177 178 179
    /**
     * <p>No subscription is established.</p>
     */
180
    public static final SubType SUB_NONE = SubType.NONE;
181 182 183
    /**
     * <p>The roster owner has a subscription to the roster item's presence.</p>
     */
184
    public static final SubType SUB_TO = SubType.TO;
185 186 187
    /**
     * <p>The roster item has a subscription to the roster owner's presence.</p>
     */
188
    public static final SubType SUB_FROM = SubType.FROM;
189 190 191
    /**
     * <p>The roster item and owner have a mutual subscription.</p>
     */
192
    public static final SubType SUB_BOTH = SubType.BOTH;
193 194

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
195
     * <p>The roster item has no pending subscription requests.</p>
196
     */
197
    public static final AskType ASK_NONE = AskType.NONE;
198 199 200 201
    /**
     * <p>The roster item has been asked for permission to subscribe to their presence
     * but no response has been received.</p>
     */
202
    public static final AskType ASK_SUBSCRIBE = AskType.SUBSCRIBE;
203 204 205 206
    /**
     * <p>The roster owner has asked to the roster item to unsubscribe from it's
     * presence but has not received confirmation.</p>
     */
207
    public static final AskType ASK_UNSUBSCRIBE = AskType.UNSUBSCRIBE;
208 209 210 211

    /**
     * <p>There are no subscriptions that have been received but not presented to the user.</p>
     */
212
    public static final RecvType RECV_NONE = RecvType.NONE;
213 214 215
    /**
     * <p>The server has received a subscribe request, but has not forwarded it to the user.</p>
     */
216
    public static final RecvType RECV_SUBSCRIBE = RecvType.SUBSCRIBE;
217 218 219
    /**
     * <p>The server has received an unsubscribe request, but has not forwarded it to the user.</p>
     */
220
    public static final RecvType RECV_UNSUBSCRIBE = RecvType.UNSUBSCRIBE;
221 222 223 224 225

    protected RecvType recvStatus;
    protected JID jid;
    protected String nickname;
    protected List<String> groups;
226 227
    protected Set<String> sharedGroups = new HashSet<>();
    protected Set<String> invisibleSharedGroups = new HashSet<>();
228 229
    protected SubType subStatus;
    protected AskType askStatus;
Gaston Dombiak's avatar
Gaston Dombiak committed
230 231 232 233
    /**
     * Holds the ID that uniquely identifies the roster in the backend store. A value of
     * zero means that the roster item is not persistent.
     */
234 235
    private long rosterID;

Gaston Dombiak's avatar
Gaston Dombiak committed
236 237 238 239 240 241
    /**
     * Constructor added for Externalizable. Do not use this constructor.
     */
    public RosterItem() {
    }

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    public RosterItem(long id,
                                JID jid,
                                SubType subStatus,
                                AskType askStatus,
                                RecvType recvStatus,
                                String nickname,
                                List<String> groups) {
        this(jid, subStatus, askStatus, recvStatus, nickname, groups);
        this.rosterID = id;
    }

    public RosterItem(JID jid,
                           SubType subStatus,
                           AskType askStatus,
                           RecvType recvStatus,
                           String nickname,
                           List<String> groups) {
        this.jid = jid;
        this.subStatus = subStatus;
        this.askStatus = askStatus;
        this.recvStatus = recvStatus;
        this.nickname = nickname;
264
        this.groups = new LinkedList<>();
265 266 267 268 269 270 271 272
        if (groups != null) {
            for (String group : groups) {
                this.groups.add(group);
            }
        }
    }

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
273
     * Create a roster item from the data in another one.
274
     *
Gaston Dombiak's avatar
Gaston Dombiak committed
275
     * @param item Item that contains the info of the roster item.
276 277 278 279 280 281 282
     */
    public RosterItem(org.xmpp.packet.Roster.Item item) {
        this(item.getJID(),
                getSubType(item),
                getAskStatus(item),
                RosterItem.RECV_NONE,
                item.getName(),
283
                new LinkedList<>(item.getGroups()));
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
    }

    private static RosterItem.AskType getAskStatus(org.xmpp.packet.Roster.Item item) {
        if (item.getAsk() == org.xmpp.packet.Roster.Ask.subscribe) {
            return RosterItem.ASK_SUBSCRIBE;
        }
        else if (item.getAsk() == org.xmpp.packet.Roster.Ask.unsubscribe) {
            return RosterItem.ASK_UNSUBSCRIBE;
        }
        else {
            return RosterItem.ASK_NONE;
        }
    }

    private static RosterItem.SubType getSubType(org.xmpp.packet.Roster.Item item) {
        if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.to) {
            return RosterItem.SUB_TO;
        }
        else if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.from) {
            return RosterItem.SUB_FROM;
        }
        else if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.both) {
            return RosterItem.SUB_BOTH;
        }
        else if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.remove) {
            return RosterItem.SUB_REMOVE;
        }
        else {
            return RosterItem.SUB_NONE;
        }
    }

    /**
     * <p>Obtain the current subscription status of the item.</p>
     *
     * @return The subscription status of the item
     */
    public SubType getSubStatus() {
        return subStatus;
    }

    /**
     * <p>Set the current subscription status of the item.</p>
     *
     * @param subStatus The subscription status of the item
     */
    public void setSubStatus(SubType subStatus) {
Gaston Dombiak's avatar
Gaston Dombiak committed
331 332 333 334 335 336 337 338 339
        // Optimization: Load user only if we need to set the nickname of the roster item
        if ("".equals(nickname) && (subStatus == SUB_BOTH || subStatus == SUB_TO)) {
            try {
                nickname = UserNameManager.getUserName(jid);
            }
            catch (UserNotFoundException e) {
                // Do nothing
            }
        }
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
        this.subStatus = subStatus;
    }

    /**
     * <p>Obtain the current ask status of the item.</p>
     *
     * @return The ask status of the item
     */
    public AskType getAskStatus() {
        if (isShared()) {
            // Redefine the ask status since the item belongs to a shared group
            return ASK_NONE;
        }
        else {
            return askStatus;
        }
    }

    /**
     * <p>Set the current ask status of the item.</p>
     *
     * @param askStatus The ask status of the item
     */
    public void setAskStatus(AskType askStatus) {
        this.askStatus = askStatus;
    }

    /**
     * <p>Obtain the current recv status of the item.</p>
     *
     * @return The recv status of the item
     */
    public RecvType getRecvStatus() {
        return recvStatus;
    }

    /**
     * <p>Set the current recv status of the item.</p>
     *
     * @param recvStatus The recv status of the item
     */
    public void setRecvStatus(RecvType recvStatus) {
        this.recvStatus = recvStatus;
    }

    /**
     * <p>Obtain the address of the item.</p>
     *
     * @return The address of the item
     */
    public JID getJid() {
        return jid;
    }

    /**
     * <p>Obtain the current nickname for the item.</p>
     *
     * @return The subscription status of the item
     */
    public String getNickname() {
        return nickname;
    }

    /**
     * <p>Set the current nickname for the item.</p>
     *
     * @param nickname The subscription status of the item
     */
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    /**
     * Returns the groups for the item. Shared groups won't be included in the answer.
     *
     * @return The groups for the item.
     */
    public List<String> getGroups() {
        return groups;
    }

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
422
     * Set the current groups for the item.
423 424
     *
     * @param groups The new lists of groups the item belongs to.
Gaston Dombiak's avatar
Gaston Dombiak committed
425
     * @throws org.jivesoftware.openfire.SharedGroupException if trying to remove shared group.
426 427 428
     */
    public void setGroups(List<String> groups) throws SharedGroupException {
        if (groups == null) {
429
            this.groups = new LinkedList<>();
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
        }
        else {
            // Raise an error if the user is trying to remove the item from a shared group
            for (Group group: getSharedGroups()) {
                // Get the display name of the group
                String groupName = group.getProperties().get("sharedRoster.displayName");
                // Check if the group has been removed from the new groups list
                if (!groups.contains(groupName)) {
                    throw new SharedGroupException("Cannot remove item from shared group");
                }
            }

            // Remove shared groups from the param
            for (Iterator<String> it=groups.iterator(); it.hasNext();) {
                String groupName = it.next();
                try {
                    Group group = GroupManager.getInstance().getGroup(groupName);
447 448 449 450
                	if (RosterManager.isSharedGroup(group)) {
                		it.remove();
                	}
                } catch (GroupNotFoundException e) {
451
                    // Check now if there is a group whose display name matches the requested group
452 453 454 455 456 457 458 459 460 461
                	Collection<Group> groupsWithProp = GroupManager
    						.getInstance()
    						.search("sharedRoster.displayName", groupName);
                	Iterator<Group> itr = groupsWithProp.iterator();
                	while(itr.hasNext()) {
                		Group group = itr.next();
                    	if (RosterManager.isSharedGroup(group)) {
                    		it.remove();
                    	}
                	}
462 463 464 465 466 467 468 469 470 471 472 473
                }
            }
            this.groups = groups;
        }
    }

    /**
     * Returns the shared groups for the item.
     *
     * @return The shared groups this item belongs to.
     */
    public Collection<Group> getSharedGroups() {
474
        Collection<Group> groups = new ArrayList<>(sharedGroups.size());
475 476 477 478 479
        for (String groupName : sharedGroups) {
            try {
                groups.add(GroupManager.getInstance().getGroup(groupName));
            }
            catch (GroupNotFoundException e) {
480
                // Do nothing
481 482 483
            }
        }
        return groups;
484 485 486 487 488 489 490 491 492 493
    }

    /**
     * Returns the invisible shared groups for the item. These groups are for internal use
     * and help track the reason why a roster item has a presence subscription of type FROM
     * when using shared groups.
     *
     * @return The shared groups this item belongs to.
     */
    public Collection<Group> getInvisibleSharedGroups() {
494
        Collection<Group> groups = new ArrayList<>(invisibleSharedGroups.size());
495 496 497 498 499
        for (String groupName : invisibleSharedGroups) {
            try {
                groups.add(GroupManager.getInstance().getGroup(groupName));
            }
            catch (GroupNotFoundException e) {
500
                // Do nothing
501 502 503
            }
        }
        return groups;
504 505
    }

506 507 508 509 510 511 512 513
    Set<String> getInvisibleSharedGroupsNames() {
        return invisibleSharedGroups;
    }

    void setInvisibleSharedGroupsNames(Set<String> groupsNames) {
        invisibleSharedGroups = groupsNames;
    }

514 515 516 517 518 519
    /**
     * Adds a new group to the shared groups list.
     *
     * @param sharedGroup The shared group to add to the list of shared groups.
     */
    public void addSharedGroup(Group sharedGroup) {
520 521
        sharedGroups.add(sharedGroup.getName());
        invisibleSharedGroups.remove(sharedGroup.getName());
522 523 524 525 526 527 528 529 530 531
    }

    /**
     * Adds a new group to the list shared groups that won't be sent to the user. These groups
     * are for internal use and help track the reason why a roster item has a presence
     * subscription of type FROM when using shared groups.
     *
     * @param sharedGroup The shared group to add to the list of shared groups.
     */
    public void addInvisibleSharedGroup(Group sharedGroup) {
532
        invisibleSharedGroups.add(sharedGroup.getName());
533 534 535 536 537 538 539 540
    }

    /**
     * Removes a group from the shared groups list.
     *
     * @param sharedGroup The shared group to remove from the list of shared groups.
     */
    public void removeSharedGroup(Group sharedGroup) {
541 542
        sharedGroups.remove(sharedGroup.getName());
        invisibleSharedGroups.remove(sharedGroup.getName());
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    }

    /**
     * Returns true if this item belongs to a shared group. Return true even if the item belongs
     * to a personal group and a shared group.
     *
     * @return true if this item belongs to a shared group.
     */
    public boolean isShared() {
        return !sharedGroups.isEmpty() || !invisibleSharedGroups.isEmpty();
    }

    /**
     * Returns true if this item belongs ONLY to shared groups. This means that the the item is
     * considered to be "only shared" if it doesn't belong to a personal group but only to shared
     * groups.
     *
     * @return true if this item belongs ONLY to shared groups.
     */
    public boolean isOnlyShared() {
        return isShared() && groups.isEmpty();
    }

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
567 568 569 570
     * Returns the roster ID associated with this particular roster item. A value of zero
     * means that the roster item is not being persisted in the backend store.<p>
     *
     * Databases can use the roster ID as the key in locating roster items.
571 572 573 574 575 576 577
     *
     * @return The roster ID
     */
    public long getID() {
        return rosterID;
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
578 579 580 581 582 583 584 585
    /**
     * Sets the roster ID associated with this particular roster item. A value of zero
     * means that the roster item is not being persisted in the backend store.<p>
     *
     * Databases can use the roster ID as the key in locating roster items.
     *
     * @param rosterID The roster ID.
     */
586 587 588 589 590 591 592 593 594
    public void setID(long rosterID) {
        this.rosterID = rosterID;
    }

    /**
     * <p>Update the cached item as a copy of the given item.</p>
     * <p>A convenience for getting the item and setting each attribute.</p>
     *
     * @param item The item who's settings will be copied into the cached copy
Gaston Dombiak's avatar
Gaston Dombiak committed
595
     * @throws org.jivesoftware.openfire.SharedGroupException if trying to remove shared group.
596 597
     */
    public void setAsCopyOf(org.xmpp.packet.Roster.Item item) throws SharedGroupException {
598
        setGroups(new LinkedList<>(item.getGroups()));
599 600 601
        setNickname(item.getName());
    }

602 603 604 605 606
    /*
	 * (non-Javadoc)
	 * 
	 * @see org.jivesoftware.util.cache.Cacheable#getCachedSize()
	 */
607
    @Override
608
    public int getCachedSize() throws CannotCalculateSizeException {
609 610 611
        int size = jid.toBareJID().length();
        size += CacheSizes.sizeOfString(nickname);
        size += CacheSizes.sizeOfCollection(groups);
612 613
        size += CacheSizes.sizeOfCollection(invisibleSharedGroups);
        size += CacheSizes.sizeOfCollection(sharedGroups);
614 615
        size += CacheSizes.sizeOfInt(); // subStatus
        size += CacheSizes.sizeOfInt(); // askStatus
616
        size += CacheSizes.sizeOfInt(); // recvStatus
617 618 619
        size += CacheSizes.sizeOfLong(); // id
        return size;
    }
Gaston Dombiak's avatar
Gaston Dombiak committed
620

621
    @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
622
    public void writeExternal(ObjectOutput out) throws IOException {
623
        ExternalizableUtil.getInstance().writeSerializable(out, jid);
Gaston Dombiak's avatar
Gaston Dombiak committed
624 625 626 627 628 629 630 631 632 633 634 635 636
        ExternalizableUtil.getInstance().writeBoolean(out, nickname != null);
        if (nickname != null) {
            ExternalizableUtil.getInstance().writeSafeUTF(out, nickname);
        }
        ExternalizableUtil.getInstance().writeStrings(out, groups);
        ExternalizableUtil.getInstance().writeStrings(out, sharedGroups);
        ExternalizableUtil.getInstance().writeStrings(out, invisibleSharedGroups);
        ExternalizableUtil.getInstance().writeInt(out, recvStatus.getValue());
        ExternalizableUtil.getInstance().writeInt(out, subStatus.getValue());
        ExternalizableUtil.getInstance().writeInt(out, askStatus.getValue());
        ExternalizableUtil.getInstance().writeLong(out, rosterID);
    }

637
    @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
638
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
639
        jid = (JID) ExternalizableUtil.getInstance().readSerializable(in);
Gaston Dombiak's avatar
Gaston Dombiak committed
640 641 642
        if (ExternalizableUtil.getInstance().readBoolean(in)) {
            nickname = ExternalizableUtil.getInstance().readSafeUTF(in);
        }
643
        this.groups = new LinkedList<>();
Gaston Dombiak's avatar
Gaston Dombiak committed
644 645 646 647 648 649 650 651
        ExternalizableUtil.getInstance().readStrings(in, groups);
        ExternalizableUtil.getInstance().readStrings(in, sharedGroups);
        ExternalizableUtil.getInstance().readStrings(in, invisibleSharedGroups);
        recvStatus = RecvType.getTypeFromInt(ExternalizableUtil.getInstance().readInt(in));
        subStatus = SubType.getTypeFromInt(ExternalizableUtil.getInstance().readInt(in));
        askStatus = AskType.getTypeFromInt(ExternalizableUtil.getInstance().readInt(in));
        rosterID = ExternalizableUtil.getInstance().readLong(in);
    }
652
}