OfflineMessageStore.java 18.6 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 2911 $
 * $Date: 2005-10-03 12:35:52 -0300 (Mon, 03 Oct 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * 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.
19 20
 */

21
package org.jivesoftware.openfire;
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

37
import org.dom4j.DocumentException;
38 39 40 41
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
42 43 44 45 46
import org.jivesoftware.openfire.container.BasicModule;
import org.jivesoftware.openfire.event.UserEventDispatcher;
import org.jivesoftware.openfire.event.UserEventListener;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
47 48 49
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.StringUtils;
50
import org.jivesoftware.util.XMPPDateTimeFormat;
51 52 53 54
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
55
import org.xmpp.packet.JID;
56 57 58 59 60 61 62 63 64 65 66
import org.xmpp.packet.Message;

/**
 * Represents the user's offline message storage. A message store holds messages that were
 * sent to the user while they were unavailable. The user can retrieve their messages by
 * setting their presence to "available". The messages will then be delivered normally.
 * Offline message storage is optional, in which case a null implementation is returned that
 * always throws UnauthorizedException when adding messages to the store.
 *
 * @author Iain Shigeoka
 */
67
public class OfflineMessageStore extends BasicModule implements UserEventListener {
68

69 70
	private static final Logger Log = LoggerFactory.getLogger(OfflineMessageStore.class);

71
    private static final String INSERT_OFFLINE =
72
        "INSERT INTO ofOffline (username, messageID, creationDate, messageSize, stanza) " +
73 74
        "VALUES (?, ?, ?, ?, ?)";
    private static final String LOAD_OFFLINE =
75
        "SELECT stanza, creationDate FROM ofOffline WHERE username=?";
76
    private static final String LOAD_OFFLINE_MESSAGE =
77
        "SELECT stanza FROM ofOffline WHERE username=? AND creationDate=?";
78
    private static final String SELECT_SIZE_OFFLINE =
79
        "SELECT SUM(messageSize) FROM ofOffline WHERE username=?";
80
    private static final String SELECT_SIZE_ALL_OFFLINE =
81
        "SELECT SUM(messageSize) FROM ofOffline";
82
    private static final String DELETE_OFFLINE =
83
        "DELETE FROM ofOffline WHERE username=?";
84
    private static final String DELETE_OFFLINE_MESSAGE =
85
        "DELETE FROM ofOffline WHERE username=? AND creationDate=?";
86

guus's avatar
guus committed
87 88
    private static final int POOL_SIZE = 10;
    
Gaston Dombiak's avatar
Gaston Dombiak committed
89
    private Cache<String, Integer> sizeCache;
90

91 92 93 94 95
    /**
     * Pattern to use for detecting invalid XML characters. Invalid XML characters will
     * be removed from the stored offline messages.
     */
    private Pattern pattern = Pattern.compile("&\\#[\\d]+;");
96 97 98 99 100 101 102 103 104 105 106 107 108

    /**
     * Returns the instance of <tt>OfflineMessageStore</tt> being used by the XMPPServer.
     *
     * @return the instance of <tt>OfflineMessageStore</tt> being used by the XMPPServer.
     */
    public static OfflineMessageStore getInstance() {
        return XMPPServer.getInstance().getOfflineMessageStore();
    }

    /**
     * Pool of SAX Readers. SAXReader is not thread safe so we need to have a pool of readers.
     */
guus's avatar
guus committed
109
    private BlockingQueue<SAXReader> xmlReaders = new LinkedBlockingQueue<SAXReader>(POOL_SIZE);
110 111 112 113 114 115

    /**
     * Constructs a new offline message store.
     */
    public OfflineMessageStore() {
        super("Offline Message Store");
116
        sizeCache = CacheFactory.createCache("Offline Message Size");
117 118 119 120 121 122 123 124 125 126 127 128
    }

    /**
     * Adds a message to this message store. Messages will be stored and made
     * available for later delivery.
     *
     * @param message the message to store.
     */
    public void addMessage(Message message) {
        if (message == null) {
            return;
        }
129
		// ignore empty bodied message (typically chat-state notifications).
130
        if (message.getBody() == null || message.getBody().length() == 0) {
131 132 133 134 135
        	// allow empty pubsub messages (OF-191)
        	if (message.getChildElement("event", "http://jabber.org/protocol/pubsub#event") == null)
        	{ 
        		return; 
        	}
136
        }
137 138
        JID recipient = message.getTo();
        String username = recipient.getNode();
139
        // If the username is null (such as when an anonymous user), don't store.
140
        if (username == null || !UserManager.getInstance().isRegisteredUser(recipient)) {
141 142
            return;
        }
143
        else
144
        if (!XMPPServer.getInstance().getServerInfo().getXMPPDomain().equals(recipient.getDomain())) {
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
            // Do not store messages sent to users of remote servers
            return;
        }

        long messageID = SequenceManager.nextID(JiveConstants.OFFLINE);

        // Get the message in XML format.
        String msgXML = message.getElement().asXML();

        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(INSERT_OFFLINE);
            pstmt.setString(1, username);
            pstmt.setLong(2, messageID);
            pstmt.setString(3, StringUtils.dateToMillis(new java.util.Date()));
            pstmt.setInt(4, msgXML.length());
            pstmt.setString(5, msgXML);
            pstmt.executeUpdate();
        }

        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        finally {
171
            DbConnectionManager.closeConnection(pstmt, con);
172 173 174 175
        }

        // Update the cached size if it exists.
        if (sizeCache.containsKey(username)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
176
            int size = sizeCache.get(username);
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
            size += msgXML.length();
            sizeCache.put(username, size);
        }
    }

    /**
     * Returns a Collection of all messages in the store for a user.
     * Messages may be deleted after being selected from the database depending on
     * the delete param.
     *
     * @param username the username of the user who's messages you'd like to receive.
     * @param delete true if the offline messages should be deleted.
     * @return An iterator of packets containing all offline messages.
     */
    public Collection<OfflineMessage> getMessages(String username, boolean delete) {
        List<OfflineMessage> messages = new ArrayList<OfflineMessage>();
193
        SAXReader xmlReader = null;
194 195
        Connection con = null;
        PreparedStatement pstmt = null;
196
        ResultSet rs = null;
197 198 199 200 201 202
        try {
            // Get a sax reader from the pool
            xmlReader = xmlReaders.take();
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_OFFLINE);
            pstmt.setString(1, username);
203
            rs = pstmt.executeQuery();
204 205 206
            while (rs.next()) {
                String msgXML = rs.getString(1);
                Date creationDate = new Date(Long.parseLong(rs.getString(2).trim()));
207 208 209 210 211 212 213 214 215 216 217 218 219
                OfflineMessage message;
                try {
                    message = new OfflineMessage(creationDate,
                            xmlReader.read(new StringReader(msgXML)).getRootElement());
                } catch (DocumentException e) {
                    // Try again after removing invalid XML chars (e.g. &#12;)
                    Matcher matcher = pattern.matcher(msgXML);
                    if (matcher.find()) {
                        msgXML = matcher.replaceAll("");
                    }
                    message = new OfflineMessage(creationDate,
                            xmlReader.read(new StringReader(msgXML)).getRootElement());
                }
220 221 222

                // Add a delayed delivery (XEP-0203) element to the message.
                Element delay = message.addChildElement("delay", "urn:xmpp:delay");
223
                delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getXMPPDomain());
224
                delay.addAttribute("stamp", XMPPDateTimeFormat.format(creationDate));
225 226 227
                // Add a legacy delayed delivery (XEP-0091) element to the message. XEP is obsolete and support should be dropped in future.
                delay = message.addChildElement("x", "jabber:x:delay");
                delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getXMPPDomain());
228
                delay.addAttribute("stamp", XMPPDateTimeFormat.formatOld(creationDate));
229 230
                messages.add(message);
            }
231 232 233
            // Check if the offline messages loaded should be deleted, and that there are
            // messages to delete.
            if (delete && !messages.isEmpty()) {
234 235 236 237 238 239 240 241 242 243 244 245 246
                PreparedStatement pstmt2 = null;
                try {
                    pstmt2 = con.prepareStatement(DELETE_OFFLINE);
                    pstmt2.setString(1, username);
                    pstmt2.executeUpdate();
                    removeUsernameFromSizeCache(username);
                }
                catch (Exception e) {
                    Log.error("Error deleting offline messages of username: " + username, e);
                }
                finally {
                    DbConnectionManager.closeStatement(pstmt2);
                } 
247 248 249
            }
        }
        catch (Exception e) {
Gaston Dombiak's avatar
Gaston Dombiak committed
250
            Log.error("Error retrieving offline messages of username: " + username, e);
251 252
        }
        finally {
253
            DbConnectionManager.closeConnection(rs, pstmt, con);
254
            // Return the sax reader to the pool
255 256 257
            if (xmlReader != null) {
                xmlReaders.add(xmlReader);
            }
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        }
        return messages;
    }

    /**
     * Returns the offline message of the specified user with the given creation date. The
     * returned message will NOT be deleted from the database.
     *
     * @param username the username of the user who's message you'd like to receive.
     * @param creationDate the date when the offline message was stored in the database.
     * @return the offline message of the specified user with the given creation stamp.
     */
    public OfflineMessage getMessage(String username, Date creationDate) {
        OfflineMessage message = null;
        Connection con = null;
        PreparedStatement pstmt = null;
274
        ResultSet rs = null;
275 276 277 278 279 280 281 282
        SAXReader xmlReader = null;
        try {
            // Get a sax reader from the pool
            xmlReader = xmlReaders.take();
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_OFFLINE_MESSAGE);
            pstmt.setString(1, username);
            pstmt.setString(2, StringUtils.dateToMillis(creationDate));
283
            rs = pstmt.executeQuery();
284 285
            while (rs.next()) {
                String msgXML = rs.getString(1);
286 287
                message = new OfflineMessage(creationDate,
                        xmlReader.read(new StringReader(msgXML)).getRootElement());
288 289
                // Add a delayed delivery (XEP-0203) element to the message.
                Element delay = message.addChildElement("delay", "urn:xmpp:delay");
290
                delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getXMPPDomain());
291
                delay.addAttribute("stamp", XMPPDateTimeFormat.format(creationDate));
292 293 294
                // Add a legacy delayed delivery (XEP-0091) element to the message. XEP is obsolete and support should be dropped in future.
                delay = message.addChildElement("x", "jabber:x:delay");
                delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getXMPPDomain());
295
                delay.addAttribute("stamp", XMPPDateTimeFormat.formatOld(creationDate));
296 297 298
            }
        }
        catch (Exception e) {
Gaston Dombiak's avatar
Gaston Dombiak committed
299 300
            Log.error("Error retrieving offline messages of username: " + username +
                    " creationDate: " + creationDate, e);
301 302 303
        }
        finally {
            // Return the sax reader to the pool
304 305 306 307
            if (xmlReader != null) {
                xmlReaders.add(xmlReader);
            }
            DbConnectionManager.closeConnection(rs, pstmt, con);
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        }
        return message;
    }

    /**
     * Deletes all offline messages in the store for a user.
     *
     * @param username the username of the user who's messages are going to be deleted.
     */
    public void deleteMessages(String username) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_OFFLINE);
            pstmt.setString(1, username);
            pstmt.executeUpdate();
            
            removeUsernameFromSizeCache(username);
        }
        catch (Exception e) {
Gaston Dombiak's avatar
Gaston Dombiak committed
329
            Log.error("Error deleting offline messages of username: " + username, e);
330 331
        }
        finally {
332
            DbConnectionManager.closeConnection(pstmt, con);
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
        }
    }

    private void removeUsernameFromSizeCache(String username) {
        // Update the cached size if it exists.
        if (sizeCache.containsKey(username)) {
            sizeCache.remove(username);
        }
    }

    /**
     * Deletes the specified offline message in the store for a user. The way to identify the
     * message to delete is based on the creationDate and username.
     *
     * @param username the username of the user who's message is going to be deleted.
     * @param creationDate the date when the offline message was stored in the database.
     */
    public void deleteMessage(String username, Date creationDate) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_OFFLINE_MESSAGE);
            pstmt.setString(1, username);
            pstmt.setString(2, StringUtils.dateToMillis(creationDate));
            pstmt.executeUpdate();
            
360 361 362
            // Force a refresh for next call to getSize(username),
            // it's easier than loading the message to be deleted just
            // to update the cache.
363 364 365
            removeUsernameFromSizeCache(username);
        }
        catch (Exception e) {
Gaston Dombiak's avatar
Gaston Dombiak committed
366 367
            Log.error("Error deleting offline messages of username: " + username +
                    " creationDate: " + creationDate, e);
368 369
        }
        finally {
370
            DbConnectionManager.closeConnection(pstmt, con);
371 372 373 374 375 376 377 378 379 380 381 382 383
        }
    }

    /**
     * Returns the approximate size (in bytes) of the XML messages stored for
     * a particular user.
     *
     * @param username the username of the user.
     * @return the approximate size of stored messages (in bytes).
     */
    public int getSize(String username) {
        // See if the size is cached.
        if (sizeCache.containsKey(username)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
384
            return sizeCache.get(username);
385 386 387 388
        }
        int size = 0;
        Connection con = null;
        PreparedStatement pstmt = null;
389
        ResultSet rs = null;
390 391 392 393
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(SELECT_SIZE_OFFLINE);
            pstmt.setString(1, username);
394
            rs = pstmt.executeQuery();
395 396 397 398 399 400 401 402 403 404
            if (rs.next()) {
                size = rs.getInt(1);
            }
            // Add the value to cache.
            sizeCache.put(username, size);
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        finally {
405
            DbConnectionManager.closeConnection(rs, pstmt, con);
406 407 408 409 410 411 412 413 414 415 416 417 418 419
        }
        return size;
    }

    /**
     * Returns the approximate size (in bytes) of the XML messages stored for all
     * users.
     *
     * @return the approximate size of all stored messages (in bytes).
     */
    public int getSize() {
        int size = 0;
        Connection con = null;
        PreparedStatement pstmt = null;
420
        ResultSet rs = null;
421 422 423
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(SELECT_SIZE_ALL_OFFLINE);
424
            rs = pstmt.executeQuery();
425 426 427 428 429 430 431 432
            if (rs.next()) {
                size = rs.getInt(1);
            }
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        finally {
433
            DbConnectionManager.closeConnection(rs, pstmt, con);
434 435 436 437
        }
        return size;
    }

438 439 440 441 442 443 444 445 446 447 448 449 450
    public void userCreated(User user, Map params) {
        //Do nothing
    }

    public void userDeleting(User user, Map params) {
        // Delete all offline messages of the user
        deleteMessages(user.getUsername());
    }

    public void userModified(User user, Map params) {
        //Do nothing
    }

451 452
    @Override
	public void start() throws IllegalStateException {
453 454
        super.start();
        // Initialize the pool of sax readers
guus's avatar
guus committed
455
        for (int i=0; i<POOL_SIZE; i++) {
456 457 458
            SAXReader xmlReader = new SAXReader();
            xmlReader.setEncoding("UTF-8");
            xmlReaders.add(xmlReader);
459
        }
460 461 462
        // Add this module as a user event listener so we can delete
        // all offline messages when a user is deleted
        UserEventDispatcher.addListener(this);
463 464
    }

465 466
    @Override
	public void stop() {
467 468 469
        super.stop();
        // Clean up the pool of sax readers
        xmlReaders.clear();
470 471
        // Remove this module as a user event listener
        UserEventDispatcher.removeListener(this);
472 473
    }
}