User.java 23 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 1321 $
 * $Date: 2005-05-05 15:31:03 -0300 (Thu, 05 May 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.user;
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

40
import org.jivesoftware.database.DbConnectionManager;
41 42 43 44
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.event.UserEventDispatcher;
import org.jivesoftware.openfire.roster.Roster;
45
import org.jivesoftware.util.StringUtils;
46 47
import org.jivesoftware.util.cache.CacheSizes;
import org.jivesoftware.util.cache.Cacheable;
48
import org.jivesoftware.util.cache.ExternalizableUtil;
49 50
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
51
import org.xmpp.resultsetmanagement.Result;
52 53 54 55

/**
 * Encapsulates information about a user. New users are created using
 * {@link UserManager#createUser(String, String, String, String)}. All user
56
 * properties are loaded on demand and are read from the <tt>ofUserProp</tt>
57 58 59 60 61 62
 * database table. The currently-installed {@link UserProvider} is used for
 * setting all other user data and some operations may not be supported
 * depending on the capabilities of the {@link UserProvider}.
 *
 * @author Matt Tucker
 */
63
public class User implements Cacheable, Externalizable, Result {
64

65 66
	private static final Logger Log = LoggerFactory.getLogger(User.class);

67
    private static final String LOAD_PROPERTIES =
68
        "SELECT name, propValue FROM ofUserProp WHERE username=?";
69
    private static final String LOAD_PROPERTY =
70
        "SELECT propValue FROM ofUserProp WHERE username=? AND name=?";
71
    private static final String DELETE_PROPERTY =
72
        "DELETE FROM ofUserProp WHERE username=? AND name=?";
73
    private static final String UPDATE_PROPERTY =
74
        "UPDATE ofUserProp SET propValue=? WHERE name=? AND username=?";
75
    private static final String INSERT_PROPERTY =
76
        "INSERT INTO ofUserProp (username, name, propValue) VALUES (?, ?, ?)";
77

78 79 80 81 82
    // The name of the name visible property
    private static final String NAME_VISIBLE_PROPERTY = "name.visible";
    // The name of the email visible property
    private static final String EMAIL_VISIBLE_PROPERTY = "email.visible";

83 84 85 86 87 88 89 90
    private String username;
    private String name;
    private String email;
    private Date creationDate;
    private Date modificationDate;

    private Map<String,String> properties = null;

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    /**
     * Returns the value of the specified property for the given username. This method is
     * an optimization to avoid loading a user to get a specific property.
     *
     * @param username the username of the user to get a specific property value.
     * @param propertyName the name of the property to return its value.
     * @return the value of the specified property for the given username.
     */
    public static String getPropertyValue(String username, String propertyName) {
        String propertyValue = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PROPERTY);
            pstmt.setString(1, username);
            pstmt.setString(2, propertyName);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                propertyValue = rs.getString(1);
            }
            rs.close();
        }
        catch (SQLException sqle) {
115
            Log.error(sqle.getMessage(), sqle);
116 117 118
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
119
            catch (Exception e) { Log.error(e.getMessage(), e); }
120
            try { if (con != null) con.close(); }
121
            catch (Exception e) { Log.error(e.getMessage(), e); }
122 123 124 125
        }
        return propertyValue;
    }

126 127 128 129 130 131
    /**
     * Constructor added for Externalizable. Do not use this constructor.
     */
    public User() {
    }

132
    /**
133 134 135
     * Constructs a new user. Normally, all arguments can be <tt>null</tt> except the username.
     * However, a UserProvider -may- require a name or email address.  In those cases, the
     * isNameRequired or isEmailRequired UserProvider tests indicate whether <tt>null</tt> is allowed.
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
     * Typically, User objects should not be constructed by end-users of the API.
     * Instead, user objects should be retrieved using {@link UserManager#getUser(String)}.
     *
     * @param username the username.
     * @param name the name.
     * @param email the email address.
     * @param creationDate the date the user was created.
     * @param modificationDate the date the user was last modified.
     */
    public User(String username, String name, String email, Date creationDate,
            Date modificationDate)
    {
        if (username == null) {
            throw new NullPointerException("Username cannot be null");
        }
        this.username = username;
152
        if (UserManager.getUserProvider().isNameRequired() && (name == null || "".equals(name.trim()))) {
153 154
            throw new IllegalArgumentException("Invalid or empty name specified with provider that requires name");
        }
155
        this.name = name;
156 157
        if (UserManager.getUserProvider().isEmailRequired() && (email == null || "".equals(email.trim()))) {
            throw new IllegalArgumentException("Empty email address specified with provider that requires email address. User: "
158
                                                + username + " Email: " + email);
159
        }
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        this.email = email;
        this.creationDate = creationDate;
        this.modificationDate = modificationDate;
    }

    /**
     * Returns this user's username.
     *
     * @return the username..
     */
    public String getUsername() {
        return username;
    }

    /**
     * Sets a new password for this user.
     *
     * @param password the new password for the user.
178
     * @throws UnsupportedOperationException exception
179
     */
180
    public void setPassword(String password) throws UnsupportedOperationException {
181 182 183 184 185
        if (UserManager.getUserProvider().isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }

        try {
186
            AuthFactory.getAuthProvider().setPassword(username, password);
187 188

            // Fire event.
189
            Map<String,Object> params = new HashMap<String,Object>();
190 191 192 193 194
            params.put("type", "passwordModified");
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
195
            Log.error(unfe.getMessage(), unfe);
196 197 198 199 200 201 202 203 204 205 206 207
        }
    }

    public String getName() {
        return name == null ? "" : name;
    }

    public void setName(String name) {
        if (UserManager.getUserProvider().isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }

208 209 210 211 212
        if (name != null && name.matches("\\s*")) {
        	name = null;
        }
        
        if (name == null && UserManager.getUserProvider().isNameRequired()) {
213 214
            throw new IllegalArgumentException("User provider requires name.");
        }
215
        
216 217 218 219 220 221
        try {
            String originalName = this.name;
            UserManager.getUserProvider().setName(username, name);
            this.name = name;

            // Fire event.
222
            Map<String,Object> params = new HashMap<String,Object>();
223 224 225 226 227 228
            params.put("type", "nameModified");
            params.put("originalValue", originalName);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
229
            Log.error(unfe.getMessage(), unfe);
230 231 232
        }
    }

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    /**
     * Returns true if name is visible to everyone or not.
     *
     * @return true if name is visible to everyone, false if not.
     */
    public boolean isNameVisible() {
        return !getProperties().containsKey(NAME_VISIBLE_PROPERTY) || Boolean.valueOf(getProperties().get(NAME_VISIBLE_PROPERTY));
    }

    /**
     * Sets if name is visible to everyone or not.
     *
     * @param visible true if name is visible, false if not.
     */
    public void setNameVisible(boolean visible) {
        getProperties().put(NAME_VISIBLE_PROPERTY, String.valueOf(visible));
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
251 252 253
    /**
     * Returns the email address of the user or <tt>null</tt> if none is defined.
     *
254
     * @return the email address of the user or null if none is defined.
Gaston Dombiak's avatar
Gaston Dombiak committed
255
     */
256
    public String getEmail() {
Gaston Dombiak's avatar
Gaston Dombiak committed
257
        return email;
258 259 260 261 262 263
    }

    public void setEmail(String email) {
        if (UserManager.getUserProvider().isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }
264 265 266 267
        
        if (email != null && email.matches("\\s*")) {
        	email = null;
        }
268

269 270 271 272
        if (UserManager.getUserProvider().isEmailRequired() && !StringUtils.isValidEmailAddress(email)) {
            throw new IllegalArgumentException("User provider requires email address.");
        }

273 274 275 276 277
        try {
            String originalEmail= this.email;
            UserManager.getUserProvider().setEmail(username, email);
            this.email = email;
            // Fire event.
278
            Map<String,Object> params = new HashMap<String,Object>();
279 280 281 282 283 284
            params.put("type", "emailModified");
            params.put("originalValue", originalEmail);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
285
            Log.error(unfe.getMessage(), unfe);
286 287 288
        }
    }

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    /**
     * Returns true if email is visible to everyone or not.
     *
     * @return true if email is visible to everyone, false if not.
     */
    public boolean isEmailVisible() {
        return !getProperties().containsKey(EMAIL_VISIBLE_PROPERTY) || Boolean.valueOf(getProperties().get(EMAIL_VISIBLE_PROPERTY));
    }

    /**
     * Sets if the email is visible to everyone or not.
     *
     * @param visible true if the email is visible, false if not.
     */
    public void setEmailVisible(boolean visible) {
        getProperties().put(EMAIL_VISIBLE_PROPERTY, String.valueOf(visible));
    }

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        if (UserManager.getUserProvider().isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }

        try {
            Date originalCreationDate = this.creationDate;
            UserManager.getUserProvider().setCreationDate(username, creationDate);
            this.creationDate = creationDate;

            // Fire event.
322
            Map<String,Object> params = new HashMap<String,Object>();
323 324 325 326 327 328
            params.put("type", "creationDateModified");
            params.put("originalValue", originalCreationDate);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
329
            Log.error(unfe.getMessage(), unfe);
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
        }
    }

    public Date getModificationDate() {
        return modificationDate;
    }

    public void setModificationDate(Date modificationDate) {
        if (UserManager.getUserProvider().isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }

        try {
            Date originalModificationDate = this.modificationDate;
            UserManager.getUserProvider().setCreationDate(username, modificationDate);
            this.modificationDate = modificationDate;

            // Fire event.
348
            Map<String,Object> params = new HashMap<String,Object>();
349 350 351 352 353 354
            params.put("type", "nameModified");
            params.put("originalValue", originalModificationDate);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
355
            Log.error(unfe.getMessage(), unfe);
356 357 358 359
        }
    }

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
360
     * Returns all extended properties of the user. Users have an arbitrary
Gaston Dombiak's avatar
Gaston Dombiak committed
361 362
     * number of extended properties. The returned collection can be modified
     * to add new properties or remove existing ones.
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
     *
     * @return the extended properties.
     */
    public Map<String,String> getProperties() {
        synchronized (this) {
            if (properties == null) {
                properties = new ConcurrentHashMap<String, String>();
                loadProperties();
            }
        }
        // Return a wrapper that will intercept add and remove commands.
        return new PropertiesMap();
    }

    /**
     * Returns the user's roster. A roster is a list of users that the user wishes to know
     * if they are online. Rosters are similar to buddy groups in popular IM clients.
     *
     * @return the user's roster.
     */
    public Roster getRoster() {
        try {
            return XMPPServer.getInstance().getRosterManager().getRoster(username);
        }
        catch (UserNotFoundException unfe) {
388
            Log.error(unfe.getMessage(), unfe);
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 422 423 424 425 426 427 428 429 430 431 432
            return null;
        }
    }

    public int getCachedSize() {
        // Approximate the size of the object in bytes by calculating the size
        // of each field.
        int size = 0;
        size += CacheSizes.sizeOfObject();              // overhead of object
        size += CacheSizes.sizeOfLong();                // id
        size += CacheSizes.sizeOfString(username);      // username
        size += CacheSizes.sizeOfString(name);          // name
        size += CacheSizes.sizeOfString(email);         // email
        size += CacheSizes.sizeOfDate() * 2;            // creationDate and modificationDate
        size += CacheSizes.sizeOfMap(properties);       // properties
        return size;
    }

    public String toString() {
        return username;
    }

    public int hashCode() {
        return username.hashCode();
    }

    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (object != null && object instanceof User) {
            return username.equals(((User)object).getUsername());
        }
        else {
            return false;
        }
    }

    /**
     * Map implementation that updates the database when properties are modified.
     */
    private class PropertiesMap extends AbstractMap {

        public Object put(Object key, Object value) {
433
            Map<String,Object> eventParams = new HashMap<String,Object>();
434 435 436
            Object answer;
            String keyString = (String) key;
            synchronized (keyString.intern()) {
437 438
                if (properties.containsKey(keyString)) {
                    String originalValue = properties.get(keyString);
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
                    answer = properties.put(keyString, (String)value);
                    updateProperty(keyString, (String)value);
                    // Configure event.
                    eventParams.put("type", "propertyModified");
                    eventParams.put("propertyKey", key);
                    eventParams.put("originalValue", originalValue);
                }
                else {
                    answer = properties.put(keyString, (String)value);
                    insertProperty(keyString, (String)value);
                    // Configure event.
                    eventParams.put("type", "propertyAdded");
                    eventParams.put("propertyKey", key);
                }
            }
            // Fire event.
            UserEventDispatcher.dispatchEvent(User.this,
                    UserEventDispatcher.EventType.user_modified, eventParams);
            return answer;
        }

        public Set<Entry> entrySet() {
            return new PropertiesEntrySet();
        }
    }

    /**
     * Set implementation that updates the database when properties are deleted.
     */
    private class PropertiesEntrySet extends AbstractSet {

        public int size() {
            return properties.entrySet().size();
        }

        public Iterator iterator() {
            return new Iterator() {

                Iterator iter = properties.entrySet().iterator();
                Map.Entry current = null;

                public boolean hasNext() {
                    return iter.hasNext();
                }

                public Object next() {
                    current = (Map.Entry)iter.next();
                    return current;
                }

                public void remove() {
                    if (current == null) {
                        throw new IllegalStateException();
                    }
                    String key = (String)current.getKey();
                    deleteProperty(key);
                    iter.remove();
                    // Fire event.
497
                    Map<String,Object> params = new HashMap<String,Object>();
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
                    params.put("type", "propertyDeleted");
                    params.put("propertyKey", key);
                    UserEventDispatcher.dispatchEvent(User.this,
                        UserEventDispatcher.EventType.user_modified, params);
                }
            };
        }
    }

    private void loadProperties() {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PROPERTIES);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                properties.put(rs.getString(1), rs.getString(2));
            }
            rs.close();
        }
        catch (SQLException sqle) {
521
            Log.error(sqle.getMessage(), sqle);
522 523 524
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
525
            catch (Exception e) { Log.error(e.getMessage(), e); }
526
            try { if (con != null) con.close(); }
527
            catch (Exception e) { Log.error(e.getMessage(), e); }
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        }
    }

    private void insertProperty(String propName, String propValue) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(INSERT_PROPERTY);
            pstmt.setString(1, username);
            pstmt.setString(2, propName);
            pstmt.setString(3, propValue);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
543
            Log.error(e.getMessage(), e);
544 545 546
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
547
            catch (Exception e) { Log.error(e.getMessage(), e); }
548
            try { if (con != null) con.close(); }
549
            catch (Exception e) { Log.error(e.getMessage(), e); }
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        }
    }

    private void updateProperty(String propName, String propValue) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(UPDATE_PROPERTY);
            pstmt.setString(1, propValue);
            pstmt.setString(2, propName);
            pstmt.setString(3, username);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
565
            Log.error(e.getMessage(), e);
566 567 568
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
569
            catch (Exception e) { Log.error(e.getMessage(), e); }
570
            try { if (con != null) con.close(); }
571
            catch (Exception e) { Log.error(e.getMessage(), e); }
572 573 574 575 576 577 578 579 580 581 582 583 584 585
        }
    }

    private void deleteProperty(String propName) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_PROPERTY);
            pstmt.setString(1, username);
            pstmt.setString(2, propName);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
586
            Log.error(e.getMessage(), e);
587 588 589
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
590
            catch (Exception e) { Log.error(e.getMessage(), e); }
591
            try { if (con != null) con.close(); }
592
            catch (Exception e) { Log.error(e.getMessage(), e); }
593 594
        }
    }
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615

    public void writeExternal(ObjectOutput out) throws IOException {
        ExternalizableUtil.getInstance().writeSafeUTF(out, username);
        ExternalizableUtil.getInstance().writeSafeUTF(out, getName());
        ExternalizableUtil.getInstance().writeBoolean(out, email != null);
        if (email != null) {
            ExternalizableUtil.getInstance().writeSafeUTF(out, email);
        }
        ExternalizableUtil.getInstance().writeLong(out, creationDate.getTime());
        ExternalizableUtil.getInstance().writeLong(out, modificationDate.getTime());
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        username = ExternalizableUtil.getInstance().readSafeUTF(in);
        name = ExternalizableUtil.getInstance().readSafeUTF(in);
        if (ExternalizableUtil.getInstance().readBoolean(in)) {
            email = ExternalizableUtil.getInstance().readSafeUTF(in);
        }
        creationDate = new Date(ExternalizableUtil.getInstance().readLong(in));
        modificationDate = new Date(ExternalizableUtil.getInstance().readLong(in));
    }
616 617 618 619 620 621 622 623 624
    
    /*
     * (non-Javadoc)
     * @see org.jivesoftware.util.resultsetmanager.Result#getUID()
     */
	public String getUID()
	{
		return username;
	}    
625
}