User.java 22.6 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
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.AuthFactory;
43 44
import org.jivesoftware.openfire.auth.ConnectionException;
import org.jivesoftware.openfire.auth.InternalUnauthenticatedException;
45 46
import org.jivesoftware.openfire.event.UserEventDispatcher;
import org.jivesoftware.openfire.roster.Roster;
47
import org.jivesoftware.util.StringUtils;
48 49
import org.jivesoftware.util.cache.CacheSizes;
import org.jivesoftware.util.cache.Cacheable;
50
import org.jivesoftware.util.cache.CannotCalculateSizeException;
51
import org.jivesoftware.util.cache.ExternalizableUtil;
52 53
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
54
import org.xmpp.resultsetmanagement.Result;
55 56 57 58

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

68 69
	private static final Logger Log = LoggerFactory.getLogger(User.class);

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

81 82 83 84 85
    // 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";

86 87 88 89 90 91 92 93
    private String username;
    private String name;
    private String email;
    private Date creationDate;
    private Date modificationDate;

    private Map<String,String> properties = null;

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

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

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

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

212 213 214
        if (name != null && name.matches("\\s*")) {
        	name = null;
        }
215

216
        if (name == null && UserManager.getUserProvider().isNameRequired()) {
217 218
            throw new IllegalArgumentException("User provider requires name.");
        }
219

220 221 222 223 224 225
        try {
            String originalName = this.name;
            UserManager.getUserProvider().setName(username, name);
            this.name = name;

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

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

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

269 270 271
        if (email != null && email.matches("\\s*")) {
        	email = null;
        }
272

273 274 275 276
        if (UserManager.getUserProvider().isEmailRequired() && !StringUtils.isValidEmailAddress(email)) {
            throw new IllegalArgumentException("User provider requires email address.");
        }

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

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    /**
     * 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));
    }

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

    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.
352
            Map<String,Object> params = new HashMap<String,Object>();
353 354 355 356 357 358
            params.put("type", "nameModified");
            params.put("originalValue", originalModificationDate);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
359
            Log.error(unfe.getMessage(), unfe);
360 361 362 363
        }
    }

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

397 398
    public int getCachedSize()
            throws CannotCalculateSizeException {
399 400 401 402 403 404 405 406 407 408 409 410 411
        // 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;
    }

412 413
    @Override
	public String toString() {
414 415 416
        return username;
    }

417 418
    @Override
	public int hashCode() {
419 420 421
        return username.hashCode();
    }

422 423
    @Override
	public boolean equals(Object object) {
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
        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 {

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

469 470
        @Override
		public Set<Entry> entrySet() {
471 472 473 474 475 476 477 478 479
            return new PropertiesEntrySet();
        }
    }

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

480 481
        @Override
		public int size() {
482 483 484
            return properties.entrySet().size();
        }

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

    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) {
552
            Log.error(e.getMessage(), e);
553 554
        }
        finally {
555
            DbConnectionManager.closeConnection(pstmt, con);
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
        }
    }

    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) {
571
            Log.error(e.getMessage(), e);
572 573
        }
        finally {
574
            DbConnectionManager.closeConnection(pstmt, con);
575 576 577 578 579 580 581 582 583 584 585 586 587 588
        }
    }

    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) {
589
            Log.error(e.getMessage(), e);
590 591
        }
        finally {
592
            DbConnectionManager.closeConnection(pstmt, con);
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
    /*
     * (non-Javadoc)
     * @see org.jivesoftware.util.resultsetmanager.Result#getUID()
     */
	public String getUID()
	{
		return username;
624
	}
625
}