OfflineMessageStore.java 16.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/**
 * $RCSfile$
 * $Revision: 2911 $
 * $Date: 2005-10-03 12:35:52 -0300 (Mon, 03 Oct 2005) $
 *
 * Copyright (C) 2004 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

12
package org.jivesoftware.openfire;
13

14
import org.dom4j.DocumentException;
15 16 17 18
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
19
import org.jivesoftware.util.*;
20
import org.jivesoftware.util.cache.Cache;
21
import org.jivesoftware.util.cache.CacheFactory;
22 23 24 25 26
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;
27
import org.xmpp.packet.JID;
28 29 30 31 32 33 34 35 36
import org.xmpp.packet.Message;

import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
37 38
import java.util.regex.Matcher;
import java.util.regex.Pattern;
39 40 41 42 43 44 45 46 47 48

/**
 * 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
 */
49
public class OfflineMessageStore extends BasicModule implements UserEventListener {
50 51

    private static final String INSERT_OFFLINE =
52
        "INSERT INTO jiveOffline (username, messageID, creationDate, messageSize, stanza) " +
53 54
        "VALUES (?, ?, ?, ?, ?)";
    private static final String LOAD_OFFLINE =
55
        "SELECT stanza, creationDate FROM jiveOffline WHERE username=?";
56
    private static final String LOAD_OFFLINE_MESSAGE =
57
        "SELECT stanza FROM jiveOffline WHERE username=? AND creationDate=?";
58 59 60 61 62 63 64 65 66
    private static final String SELECT_SIZE_OFFLINE =
        "SELECT SUM(messageSize) FROM jiveOffline WHERE username=?";
    private static final String SELECT_SIZE_ALL_OFFLINE =
        "SELECT SUM(messageSize) FROM jiveOffline";
    private static final String DELETE_OFFLINE =
        "DELETE FROM jiveOffline WHERE username=?";
    private static final String DELETE_OFFLINE_MESSAGE =
        "DELETE FROM jiveOffline WHERE username=? AND creationDate=?";

Gaston Dombiak's avatar
Gaston Dombiak committed
67
    private Cache<String, Integer> sizeCache;
68
    private FastDateFormat dateFormat;
69 70 71 72 73
    /**
     * 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]+;");
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

    /**
     * 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.
     */
    private BlockingQueue<SAXReader> xmlReaders = new LinkedBlockingQueue<SAXReader>();

    /**
     * Constructs a new offline message store.
     */
    public OfflineMessageStore() {
        super("Offline Message Store");
94 95
        dateFormat = FastDateFormat.getInstance(JiveConstants.XMPP_DELAY_DATETIME_FORMAT,
                TimeZone.getTimeZone("UTC"));
96
        sizeCache = CacheFactory.createCache("Offline Message Size");
97 98 99 100 101 102 103 104 105 106 107 108
    }

    /**
     * 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;
        }
109 110
        JID recipient = message.getTo();
        String username = recipient.getNode();
111
        // If the username is null (such as when an anonymous user), don't store.
112
        if (username == null || !UserManager.getInstance().isRegisteredUser(recipient)) {
113 114
            return;
        }
115 116
        else
        if (!XMPPServer.getInstance().getServerInfo().getName().equals(recipient.getDomain())) {
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
            // 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 {
143
            DbConnectionManager.closeConnection(pstmt, con);
144 145 146 147
        }

        // Update the cached size if it exists.
        if (sizeCache.containsKey(username)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
148
            int size = sizeCache.get(username);
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
            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>();
        Connection con = null;
        PreparedStatement pstmt = null;
        SAXReader xmlReader = null;
        try {
            // Get a sax reader from the pool
            xmlReader = xmlReaders.take();
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_OFFLINE);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String msgXML = rs.getString(1);
                Date creationDate = new Date(Long.parseLong(rs.getString(2).trim()));
178 179 180 181 182 183 184 185 186 187 188 189 190
                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());
                }
191 192 193
                // Add a delayed delivery (JEP-0091) element to the message.
                Element delay = message.addChildElement("x", "jabber:x:delay");
                delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getName());
194
                delay.addAttribute("stamp", dateFormat.format(creationDate));
195 196 197
                messages.add(message);
            }
            rs.close();
198 199 200
            // Check if the offline messages loaded should be deleted, and that there are
            // messages to delete.
            if (delete && !messages.isEmpty()) {
201 202 203 204 205 206 207 208 209 210
                pstmt.close();

                pstmt = con.prepareStatement(DELETE_OFFLINE);
                pstmt.setString(1, username);
                pstmt.executeUpdate();
                
                removeUsernameFromSizeCache(username);
            }
        }
        catch (Exception e) {
Gaston Dombiak's avatar
Gaston Dombiak committed
211
            Log.error("Error retrieving offline messages of username: " + username, e);
212 213 214
        }
        finally {
            // Return the sax reader to the pool
215 216 217 218
            if (xmlReader != null) {
                xmlReaders.add(xmlReader);
            }
            DbConnectionManager.closeConnection(pstmt, con);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        }
        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;
235
        ResultSet rs = null;
236 237 238 239 240 241 242 243
        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));
244
            rs = pstmt.executeQuery();
245 246
            while (rs.next()) {
                String msgXML = rs.getString(1);
247 248
                message = new OfflineMessage(creationDate,
                        xmlReader.read(new StringReader(msgXML)).getRootElement());
249 250 251
                // Add a delayed delivery (JEP-0091) element to the message.
                Element delay = message.addChildElement("x", "jabber:x:delay");
                delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getName());
252
                delay.addAttribute("stamp", dateFormat.format(creationDate));
253 254 255
            }
        }
        catch (Exception e) {
Gaston Dombiak's avatar
Gaston Dombiak committed
256 257
            Log.error("Error retrieving offline messages of username: " + username +
                    " creationDate: " + creationDate, e);
258 259 260
        }
        finally {
            // Return the sax reader to the pool
261 262 263 264
            if (xmlReader != null) {
                xmlReaders.add(xmlReader);
            }
            DbConnectionManager.closeConnection(rs, pstmt, con);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        }
        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
286
            Log.error("Error deleting offline messages of username: " + username, e);
287 288
        }
        finally {
289
            DbConnectionManager.closeConnection(pstmt, con);
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
        }
    }

    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();
            
317 318 319
            // Force a refresh for next call to getSize(username),
            // it's easier than loading the message to be deleted just
            // to update the cache.
320 321 322
            removeUsernameFromSizeCache(username);
        }
        catch (Exception e) {
Gaston Dombiak's avatar
Gaston Dombiak committed
323 324
            Log.error("Error deleting offline messages of username: " + username +
                    " creationDate: " + creationDate, e);
325 326
        }
        finally {
327
            DbConnectionManager.closeConnection(pstmt, con);
328 329 330 331 332 333 334 335 336 337 338 339 340
        }
    }

    /**
     * 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
341
            return sizeCache.get(username);
342 343 344 345
        }
        int size = 0;
        Connection con = null;
        PreparedStatement pstmt = null;
346
        ResultSet rs = null;
347 348 349 350
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(SELECT_SIZE_OFFLINE);
            pstmt.setString(1, username);
351
            rs = pstmt.executeQuery();
352 353 354 355 356 357 358 359 360 361
            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 {
362
            DbConnectionManager.closeConnection(rs, pstmt, con);
363 364 365 366 367 368 369 370 371 372 373 374 375 376
        }
        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;
377
        ResultSet rs = null;
378 379 380
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(SELECT_SIZE_ALL_OFFLINE);
381
            rs = pstmt.executeQuery();
382 383 384 385 386 387 388 389
            if (rs.next()) {
                size = rs.getInt(1);
            }
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        finally {
390
            DbConnectionManager.closeConnection(rs, pstmt, con);
391 392 393 394
        }
        return size;
    }

395 396 397 398 399 400 401 402 403 404 405 406 407
    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
    }

408 409 410 411
    public void start() throws IllegalStateException {
        super.start();
        // Initialize the pool of sax readers
        for (int i=0; i<10; i++) {
412 413 414
            SAXReader xmlReader = new SAXReader();
            xmlReader.setEncoding("UTF-8");
            xmlReaders.add(xmlReader);
415
        }
416 417 418
        // Add this module as a user event listener so we can delete
        // all offline messages when a user is deleted
        UserEventDispatcher.addListener(this);
419 420 421 422 423 424
    }

    public void stop() {
        super.stop();
        // Clean up the pool of sax readers
        xmlReaders.clear();
425 426
        // Remove this module as a user event listener
        UserEventDispatcher.removeListener(this);
427 428
    }
}