HistoryStrategy.java 10.5 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3157 $
 * $Date: 2005-12-04 22:54:55 -0300 (Sun, 04 Dec 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7 8
 *
 * This software is published under the terms of the GNU Public License (GPL),
9 10
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
11 12
 */

13
package org.jivesoftware.openfire.muc;
14

15
import org.jivesoftware.openfire.muc.cluster.UpdateHistoryStrategy;
16
import org.jivesoftware.openfire.muc.spi.MUCPersistenceManager;
17
import org.jivesoftware.util.Log;
18
import org.jivesoftware.util.cache.CacheFactory;
19 20
import org.xmpp.packet.Message;

21
import java.util.*;
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
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * <p>Multi-User Chat rooms may cache history of the conversations in the room in order to
 * play them back to newly arriving members.</p>
 * 
 * <p>This class is an internal component of MUCRoomHistory that describes the strategy that can 
 * be used, and provides a method of administering the history behavior.</p>
 *
 * @author Gaston Dombiak
 * @author Derek DeMoro
 */
public class HistoryStrategy {

    /**
     * The type of strategy being used.
     */
    private Type type = Type.number;

    /**
     * List containing the history of messages.
     */
    private ConcurrentLinkedQueue<Message> history = new ConcurrentLinkedQueue<Message>();
    /**
     * Default max number.
     */
    private static final int DEFAULT_MAX_NUMBER = 25;
    /**
     * The maximum number of chat history messages stored for the room.
     */
    private int maxNumber;
    /**
     * The parent history used for default settings, or null if no parent
     * (chat server defaults).
     */
    private HistoryStrategy parent;
    /**
     * Track the latest room subject change or null if none exists yet.
     */
    private Message roomSubject = null;
    /**
     * The string prefix to be used on the context property names
     * (do not include trailing dot).
     */
    private String contextPrefix = null;
67 68 69 70
    /**
     * The subdomain of the service the properties are set on.
     */
    private String contextSubdomain = null;
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

    /**
     * Create a history strategy with the given parent strategy (for defaults) or null if no 
     * parent exists.
     *
     * @param parentStrategy The parent strategy of this strategy or null if none exists.
     */
    public HistoryStrategy(HistoryStrategy parentStrategy) {
        this.parent = parentStrategy;
        if (parent == null) {
            maxNumber = DEFAULT_MAX_NUMBER;
        }
        else {
            type = Type.defaulType;
            maxNumber = parent.getMaxNumber();
        }
    }

    /**
     * Obtain the maximum number of messages for strategies using message number limitations.
     *
     * @return The maximum number of messages to store in applicable strategies.
     */
    public int getMaxNumber() {
        return maxNumber;
    }

    /**
     * Set the maximum number of messages for strategies using message number limitations.
     *
Matt Tucker's avatar
Matt Tucker committed
101
     * @param max the maximum number of messages to store in applicable strategies.
102 103
     */
    public void setMaxNumber(int max) {
104 105 106 107
        if (maxNumber == max) {
            // Do nothing since value has not changed
            return;
        }
108 109
        this.maxNumber = max;
        if (contextPrefix != null){
110
            MUCPersistenceManager.setProperty(contextSubdomain, contextPrefix + ".maxNumber", Integer.toString(maxNumber));
111
        }
112 113
        if (parent == null) {
            // Update the history strategy of the MUC service
114
            CacheFactory.doClusterTask(new UpdateHistoryStrategy(contextSubdomain, this));
115
        }
116 117 118 119 120 121 122 123
    }

    /**
     * Set the type of history strategy being used.
     *
     * @param newType The new type of chat history to use.
     */
    public void setType(Type newType){
124 125 126 127
        if (type == newType) {
            // Do nothing since value has not changed
            return;
        }
128 129 130 131
        if (newType != null){
            type = newType;
        }
        if (contextPrefix != null){
132
            MUCPersistenceManager.setProperty(contextSubdomain, contextPrefix + ".type", type.toString());
133
        }
134 135
        if (parent == null) {
            // Update the history strategy of the MUC service
136
            CacheFactory.doClusterTask(new UpdateHistoryStrategy(contextSubdomain, this));
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
    }

    /**
     * Obtain the type of history strategy being used.
     *
     * @return The current type of strategy being used.
     */
    public Type getType(){
        return type;
    }

    /**
     * Add a message to the current chat history. The strategy type will determine what 
     * actually happens to the message.
     *
     * @param packet The packet to add to the chatroom's history.
     */
    public void addMessage(Message packet){
        // get the conditions based on default or not
        Type strategyType;
        int strategyMaxNumber;
        if (type == Type.defaulType && parent != null) {
            strategyType = parent.getType();
            strategyMaxNumber = parent.getMaxNumber();
        }
        else {
            strategyType = type;
            strategyMaxNumber = maxNumber;
        }

        // Room subject change messages are special
        boolean subjectChange = false;
        if (packet.getSubject() != null && packet.getSubject().length() > 0){
            subjectChange = true;
            roomSubject = packet;
        }

        // store message according to active strategy
        if (strategyType == Type.none){
            if (subjectChange) {
                history.clear();
                history.add(packet);
            }
        }
        else if (strategyType == Type.all) {
            history.add(packet);
        }
        else if (strategyType == Type.number) {
            if (history.size() >= strategyMaxNumber) {
                // We have to remove messages so the new message won't exceed
                // the max history size
                // This is complicated somewhat because we must skip over the
                // last room subject
                // message because we want to preserve the room subject if
                // possible.
                Iterator historyIter = history.iterator();
                while (historyIter.hasNext() && history.size() > strategyMaxNumber) {
                    if (historyIter.next() != roomSubject) {
                        historyIter.remove();
                    }
                }
            }
            history.add(packet);
        }
    }

    boolean isHistoryEnabled() {
        Type strategyType = type;
        if (type == Type.defaulType && parent != null) {
            strategyType = parent.getType();
        }
        return strategyType != HistoryStrategy.Type.none;
    }

    /**
     * Obtain the current history as an iterator of messages to play back to a new room member.
     * 
     * @return An iterator of Message objects to be sent to the new room member.
     */
    public Iterator<Message> getMessageHistory(){
        LinkedList<Message> list = new LinkedList<Message>(history);
219 220
        // Sort messages. Messages may be out of order when running inside of a cluster
        Collections.sort(list, new MessageComparator());
221 222 223 224 225 226 227 228 229 230 231 232
        return list.iterator();
    }

    /**
     * Obtain the current history to be iterated in reverse mode. This means that the returned list 
     * iterator will be positioned at the end of the history so senders of this message must 
     * traverse the list in reverse mode.
     * 
     * @return A list iterator of Message objects positioned at the end of the list.
     */
    public ListIterator<Message> getReverseMessageHistory(){
        LinkedList<Message> list = new LinkedList<Message>(history);
233 234
        // Sort messages. Messages may be out of order when running inside of a cluster
        Collections.sort(list, new MessageComparator());
235 236 237 238 239 240 241
        return list.listIterator(list.size());
    }

    /**
     * Strategy type.
     */
    public enum Type {
Matt Tucker's avatar
Matt Tucker committed
242
        defaulType, none, all, number
243
    };
244 245 246 247

    /**
     * Obtain the strategy type from string name. See the Type enumeration name
     * strings for the names strings supported. If nothing matches
Matt Tucker's avatar
Matt Tucker committed
248 249
     * and parent is not null, then the default strategy is used. Otherwise the number
     * strategy is used.
250
     *
Matt Tucker's avatar
Matt Tucker committed
251
     * @param typeName the text name of the strategy type.
252 253 254
     */
    public void setTypeFromString(String typeName) {
        try {
255
            type = Type.valueOf(typeName);
256 257 258
        }
        catch (Exception e) {
            if (parent != null) {
259
                type = Type.defaulType;
260 261
            }
            else {
262
                type = Type.number;
263 264 265 266 267 268 269 270
            }
        }
    }

    /**
     * Sets the prefix to use for retrieving and saving settings (and also
     * triggers an immediate loading of properties).
     *
271
     * @param subdomain the subdomain of the muc service to pull properties for.
272 273
     * @param prefix the prefix to use (without trailing dot) on property names.
     */
274
    public void setContext(String subdomain, String prefix) {
275
        this.contextSubdomain = subdomain;
276
        this.contextPrefix = prefix;
277 278
        setTypeFromString(MUCPersistenceManager.getProperty(subdomain, prefix + ".type"));
        String maxNumberString = MUCPersistenceManager.getProperty(subdomain, prefix + ".maxNumber");
279 280
        if (maxNumberString != null && maxNumberString.trim().length() > 0){
            try {
281
                this.maxNumber = Integer.parseInt(maxNumberString);
Matt Tucker's avatar
Matt Tucker committed
282 283 284
            }
            catch (Exception e){
                Log.info("Jive property " + prefix + ".maxNumber not a valid number.");
285 286 287 288 289 290 291 292 293 294 295 296 297 298
            }
        }
    }

    /**
     * Returns true if there is a message within the history of the room that has changed the
     * room's subject.
     *
     * @return true if there is a message within the history of the room that has changed the
     *         room's subject.
     */
    public boolean hasChangedSubject() {
        return roomSubject != null;
    }
299 300 301 302 303 304 305 306

    private static class MessageComparator implements Comparator<Message> {
        public int compare(Message o1, Message o2) {
            String stamp1 = o1.getChildElement("x", "jabber:x:delay").attributeValue("stamp");
            String stamp2 = o2.getChildElement("x", "jabber:x:delay").attributeValue("stamp");
            return stamp1.compareTo(stamp2);
        }
    }
307
}