User.java 22.3 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.CannotCalculateSizeException;
49
import org.jivesoftware.util.cache.ExternalizableUtil;
50 51
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
52
import org.xmpp.resultsetmanagement.Result;
53 54 55 56

/**
 * Encapsulates information about a user. New users are created using
 * {@link UserManager#createUser(String, String, String, String)}. All user
57
 * properties are loaded on demand and are read from the <tt>ofUserProp</tt>
58 59 60 61 62 63
 * 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
 */
64
public class User implements Cacheable, Externalizable, Result {
65

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

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

79 80 81 82 83
    // 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";

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

    private Map<String,String> properties = null;

92 93 94 95 96 97 98 99 100 101 102 103
    /**
     * 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;
104
        ResultSet rs = null;
105 106 107 108 109
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PROPERTY);
            pstmt.setString(1, username);
            pstmt.setString(2, propertyName);
110
            rs = pstmt.executeQuery();
111 112 113 114 115
            while (rs.next()) {
                propertyValue = rs.getString(1);
            }
        }
        catch (SQLException sqle) {
116
            Log.error(sqle.getMessage(), sqle);
117 118
        }
        finally {
119
            DbConnectionManager.closeConnection(rs, pstmt, con);
120 121 122 123
        }
        return propertyValue;
    }

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

130
    /**
131 132 133
     * 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.
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
     * 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;
150
        if (UserManager.getUserProvider().isNameRequired() && (name == null || "".equals(name.trim()))) {
151 152
            throw new IllegalArgumentException("Invalid or empty name specified with provider that requires name");
        }
153
        this.name = name;
154 155
        if (UserManager.getUserProvider().isEmailRequired() && (email == null || "".equals(email.trim()))) {
            throw new IllegalArgumentException("Empty email address specified with provider that requires email address. User: "
156
                                                + username + " Email: " + email);
157
        }
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        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.
176
     * @throws UnsupportedOperationException exception
177
     */
178
    public void setPassword(String password) throws UnsupportedOperationException {
179 180 181 182 183
        if (UserManager.getUserProvider().isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }

        try {
184
            AuthFactory.getAuthProvider().setPassword(username, password);
185 186

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

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

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

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

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

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    /**
     * 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
249 250 251
    /**
     * Returns the email address of the user or <tt>null</tt> if none is defined.
     *
252
     * @return the email address of the user or null if none is defined.
Gaston Dombiak's avatar
Gaston Dombiak committed
253
     */
254
    public String getEmail() {
Gaston Dombiak's avatar
Gaston Dombiak committed
255
        return email;
256 257 258 259 260 261
    }

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

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

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

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    /**
     * 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));
    }

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    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.
320
            Map<String,Object> params = new HashMap<String,Object>();
321 322 323 324 325 326
            params.put("type", "creationDateModified");
            params.put("originalValue", originalCreationDate);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
327
            Log.error(unfe.getMessage(), unfe);
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        }
    }

    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.
346
            Map<String,Object> params = new HashMap<String,Object>();
347 348 349 350 351 352
            params.put("type", "nameModified");
            params.put("originalValue", originalModificationDate);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
353
            Log.error(unfe.getMessage(), unfe);
354 355 356 357
        }
    }

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
358
     * Returns all extended properties of the user. Users have an arbitrary
Gaston Dombiak's avatar
Gaston Dombiak committed
359 360
     * number of extended properties. The returned collection can be modified
     * to add new properties or remove existing ones.
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
     *
     * @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) {
386
            Log.error(unfe.getMessage(), unfe);
387 388 389 390
            return null;
        }
    }

391 392
    public int getCachedSize()
            throws CannotCalculateSizeException {
393 394 395 396 397 398 399 400 401 402 403 404 405
        // 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;
    }

406 407
    @Override
	public String toString() {
408 409 410
        return username;
    }

411 412
    @Override
	public int hashCode() {
413 414 415
        return username.hashCode();
    }

416 417
    @Override
	public boolean equals(Object object) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
        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 {

434 435
        @Override
		public Object put(Object key, Object value) {
436
            Map<String,Object> eventParams = new HashMap<String,Object>();
437 438 439
            Object answer;
            String keyString = (String) key;
            synchronized (keyString.intern()) {
440 441
                if (properties.containsKey(keyString)) {
                    String originalValue = properties.get(keyString);
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
                    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;
        }

463 464
        @Override
		public Set<Entry> entrySet() {
465 466 467 468 469 470 471 472 473
            return new PropertiesEntrySet();
        }
    }

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

474 475
        @Override
		public int size() {
476 477 478
            return properties.entrySet().size();
        }

479 480
        @Override
		public Iterator iterator() {
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
            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.
503
                    Map<String,Object> params = new HashMap<String,Object>();
504 505 506 507 508 509 510 511 512 513 514 515
                    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;
516
        ResultSet rs = null;
517 518 519 520
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PROPERTIES);
            pstmt.setString(1, username);
521
            rs = pstmt.executeQuery();
522 523 524 525 526
            while (rs.next()) {
                properties.put(rs.getString(1), rs.getString(2));
            }
        }
        catch (SQLException sqle) {
527
            Log.error(sqle.getMessage(), sqle);
528 529
        }
        finally {
530
            DbConnectionManager.closeConnection(rs, pstmt, con);
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        }
    }

    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) {
546
            Log.error(e.getMessage(), e);
547 548
        }
        finally {
549
            DbConnectionManager.closeConnection(pstmt, con);
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
        }
        finally {
568
            DbConnectionManager.closeConnection(pstmt, con);
569 570 571 572 573 574 575 576 577 578 579 580 581 582
        }
    }

    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) {
583
            Log.error(e.getMessage(), e);
584 585
        }
        finally {
586
            DbConnectionManager.closeConnection(pstmt, con);
587 588
        }
    }
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

    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));
    }
610 611 612 613 614 615 616 617
    
    /*
     * (non-Javadoc)
     * @see org.jivesoftware.util.resultsetmanager.Result#getUID()
     */
	public String getUID()
	{
		return username;
618
	}
619
}