VCardManager.java 11.6 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 1651 $
 * $Date: 2005-07-20 00:20:39 -0300 (Wed, 20 Jul 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.vcard;
14 15

import org.dom4j.Element;
16 17 18 19 20 21
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.container.BasicModule;
import org.jivesoftware.openfire.disco.ServerFeaturesProvider;
import org.jivesoftware.openfire.event.UserEventAdapter;
import org.jivesoftware.openfire.event.UserEventDispatcher;
import org.jivesoftware.openfire.user.User;
22 23 24
import org.jivesoftware.util.*;
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;
25

26 27 28 29
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
30 31 32 33 34 35

/**
 * Manages VCard information for users.
 *
 * @author Matt Tucker
 */
36
public class VCardManager extends BasicModule implements ServerFeaturesProvider {
37

38 39
    private VCardProvider provider;
    private static VCardManager instance;
40

41
    private EventHandler eventHandler;
42

43
    private Cache<String, Element> vcardCache;
44 45 46 47 48 49 50 51 52 53 54 55 56
    public static VCardManager getInstance() {
        return instance;
    }

    /**
     * Returns the currently-installed VCardProvider. <b>Warning:</b> in virtually all
     * cases the vcard provider should not be used directly. Instead, the appropriate
     * methods in VCardManager should be called. Direct access to the vcard provider is
     * only provided for special-case logic.
     *
     * @return the current VCardProvider.
     */
    public static VCardProvider getProvider() {
57
        return instance.provider;
58 59
    }

60 61
    public VCardManager() {
        super("VCard Manager");
62
        String cacheName = "VCard";
63
        vcardCache = CacheFactory.createCache(cacheName);
64
        this.eventHandler = new EventHandler();
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

        // Keeps the cache updated in case the vCard action was not performed by VCardManager
        VCardEventDispatcher.addListener(new VCardListener() {
            public void vCardCreated(String username, Element vCard) {
                // Since the vCard could be created by the provider, add it to the cache.
                vcardCache.put(username, vCard);
            }

            public void vCardUpdated(String username, Element vCard) {
                // Since the vCard could be updated by the provider, update it to the cache.
                vcardCache.put(username, vCard);
            }

            public void vCardDeleted(String username, Element vCard) {
                // Since the vCard could be delated by the provider, remove it to the cache.
                vcardCache.remove(username);
            }
        });
83 84 85 86 87 88 89 90 91 92 93 94 95 96 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 126 127 128 129 130 131 132 133
    }

    /**
     * Returns the user's vCard information for a given vcard property name. If the property
     * has no defined text then an empty string will be returned. However, if the property
     * does not exist then a <tt>null</tt> value will be answered. Advanced user systems can
     * use vCard information to link to user directory information or store other relevant
     * user information.</p>
     * Note that many elements in the vCard may have the same path so the returned value in that
     * case will be the first found element. For instance, "ADR:STREET" may be present in
     * many addresses of the user. Use {@link #getVCard(String)} to get the whole vCard of
     * the user.
     *
     * @param username The username of the user to return his vCard property.
     * @param name     The name of the vcard property to retrieve encoded with ':' to denote
     *                 the path.
     * @return The vCard value found
     */
    public String getVCardProperty(String username, String name) {
        String answer = null;
        Element vCardElement = getOrLoadVCard(username);
        if (vCardElement != null) {
            // A vCard was found for this user so now look for the correct element
            Element subElement = null;
            StringTokenizer tokenizer = new StringTokenizer(name, ":");
            while (tokenizer.hasMoreTokens()) {
                String tok = tokenizer.nextToken();
                if (subElement == null) {
                    subElement = vCardElement.element(tok);
                }
                else {
                    subElement = subElement.element(tok);
                }
                if (subElement == null) {
                    break;
                }
            }
            if (subElement != null) {
                answer = subElement.getTextTrim();
            }
        }
        return answer;
    }

    /**
     * Sets the user's vCard information. The new vCard information will be persistent. Advanced
     * user systems can use vCard information to link to user directory information or store
     * other relevant user information.
     *
     * @param username     The username of the user to set his new vCard.
     * @param vCardElement The DOM element sent by the user as his new vcard.
134
     * @throws Exception if an error occured while storing the new vCard.
135
     */
136 137 138 139
    public void setVCard(String username, Element vCardElement) throws Exception {
        boolean created = false;
        boolean updated = false;

140 141 142
        if (provider.isReadOnly()) {
            throw new UnsupportedOperationException("VCard provider is read-only.");
        }
143
        Element oldVCard = getOrLoadVCard(username);
144
        Element newvCard = null;
145 146 147 148 149
        // See if we need to update the vCard or insert a new one.
        if (oldVCard != null) {
            // Only update the vCard in the database if the vCard has changed.
            if (!oldVCard.equals(vCardElement)) {
                try {
150
                    newvCard = provider.updateVCard(username, vCardElement);
151
                    vcardCache.put(username, newvCard);
152 153 154 155
                    updated = true;
                }
                catch (NotFoundException e) {
                    Log.warn("Tried to update a vCard that does not exist", e);
156
                    newvCard = provider.createVCard(username, vCardElement);
157
                    vcardCache.put(username, newvCard);
158 159 160 161 162 163
                    created = true;
                }
            }
        }
        else {
            try {
164
                newvCard = provider.createVCard(username, vCardElement);
165
                vcardCache.put(username, newvCard);
166 167 168 169
                created = true;
            }
            catch (AlreadyExistsException e) {
                Log.warn("Tried to create a vCard when one already exist", e);
170
                newvCard = provider.updateVCard(username, vCardElement);
171
                vcardCache.put(username, newvCard);
172 173 174 175 176 177
                updated = true;
            }
        }
        // Dispatch vCard events
        if (created) {
            // Alert listeners that a new vCard has been created
178
            VCardEventDispatcher.dispatchVCardCreated(username, newvCard);
179 180
        } else if (updated) {
            // Alert listeners that a vCard has been updated
181
            VCardEventDispatcher.dispatchVCardUpdated(username, newvCard);
182
        }
183 184 185 186 187 188
    }

    /**
     * Deletes the user's vCard from the user account.
     *
     * @param username The username of the user to delete his vCard.
189 190
     * @throws UnsupportedOperationException If the provider is read-only and the data
     *         cannot be deleted, this exception is thrown
191 192 193 194 195
     */
    public void deleteVCard(String username) {
        if (provider.isReadOnly()) {
            throw new UnsupportedOperationException("VCard provider is read-only.");
        }
196 197 198 199 200
        Element oldVCard = getOrLoadVCard(username);
        if (oldVCard != null) {
            vcardCache.remove(username);
            // Delete the property from the DB if it was present in memory
            provider.deleteVCard(username);
201
            // Alert listeners that a vCard has been deleted
202
            VCardEventDispatcher.dispatchVCardDeleted(username, oldVCard);
203 204 205 206 207 208 209 210
        }
    }

    /**
     * Returns the vCard of a given user or null if none was defined before. Changes to the
     * returned vCard will not be stored in the database. Use the returned vCard as a
     * read-only vCard.
     *
211
     * @param username Username (not full JID) whose vCard to retrieve.
212 213 214 215 216 217 218 219
     * @return the vCard of a given user.
     */
    public Element getVCard(String username) {
        Element vCardElement = getOrLoadVCard(username);
        return vCardElement == null ? null : vCardElement.createCopy();
    }

    private Element getOrLoadVCard(String username) {
220 221 222 223 224
        Element vCardElement = vcardCache.get(username);
        if (vCardElement == null) {
            vCardElement = provider.loadVCard(username);
            if (vCardElement != null) {
                vcardCache.put(username, vCardElement);
225 226
            }
        }
227
        return vCardElement;
228
    }
229 230 231 232

    public void initialize(XMPPServer server) {
        instance = this;

233 234 235
        // Convert XML based provider setup to Database based
        JiveGlobals.migrateProperty("provider.vcard.className");

236
        // Load a VCard provider.
237
        String className = JiveGlobals.getProperty("provider.vcard.className",
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                DefaultVCardProvider.class.getName());
        try {
            Class c = ClassUtils.forName(className);
            provider = (VCardProvider) c.newInstance();
        }
        catch (Exception e) {
            Log.error("Error loading vcard provider: " + className, e);
            provider = new DefaultVCardProvider();
        }
    }

    public void start() {
        // Add this module as a user event listener so we can delete
        // all user properties when a user is deleted
        if (!provider.isReadOnly()) {
            UserEventDispatcher.addListener(eventHandler);
        }
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

        // Detect when a new vcard provider class is set
        PropertyEventListener propListener = new PropertyEventListener() {
            public void propertySet(String property, Map params) {
                if ("provider.vcard.className".equals(property)) {
                    initialize(XMPPServer.getInstance());
                }
            }

            public void propertyDeleted(String property, Map params) {
                //Ignore
            }

            public void xmlPropertySet(String property, Map params) {
                //Ignore
            }

            public void xmlPropertyDeleted(String property, Map params) {
                //Ignore
            }
        };
        PropertyEventDispatcher.addListener(propListener);
277 278 279 280 281 282 283
    }

    public void stop() {
        // Remove this module as a user event listener
        UserEventDispatcher.removeListener(eventHandler);
    }

284 285 286 287 288 289 290
    /**
     * Resets the manager state. The cache where loaded vCards are stored will be flushed.
     */
    public void reset() {
        vcardCache.clear();
    }

291 292 293 294 295 296
    public Iterator<String> getFeatures() {
        ArrayList<String> features = new ArrayList<String>();
        features.add("vcard-temp");
        return features.iterator();
    }

297 298 299 300 301 302 303
    private class EventHandler extends UserEventAdapter {
        public void userDeleting(User user, Map params) {
            try {
                deleteVCard(user.getUsername());
            } catch (UnsupportedOperationException ue) { /* Do Nothing */ }
        }
    }
304
}