User.java 22.4 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
import org.jivesoftware.database.DbConnectionManager;
24 25 26 27
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.event.UserEventDispatcher;
import org.jivesoftware.openfire.roster.Roster;
Gaston Dombiak's avatar
Gaston Dombiak committed
28
import org.jivesoftware.util.Log;
29
import org.jivesoftware.util.StringUtils;
30 31
import org.jivesoftware.util.cache.CacheSizes;
import org.jivesoftware.util.cache.Cacheable;
32
import org.jivesoftware.util.cache.ExternalizableUtil;
33
import org.xmpp.resultsetmanagement.Result;
34

35 36 37 38
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
39 40 41 42
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
43 44
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
45 46 47 48

/**
 * Encapsulates information about a user. New users are created using
 * {@link UserManager#createUser(String, String, String, String)}. All user
49
 * properties are loaded on demand and are read from the <tt>ofUserProp</tt>
50 51 52 53 54 55
 * 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
 */
56
public class User implements Cacheable, Externalizable, Result {
57 58

    private static final String LOAD_PROPERTIES =
59
        "SELECT name, propValue FROM ofUserProp WHERE username=?";
60
    private static final String LOAD_PROPERTY =
61
        "SELECT propValue FROM ofUserProp WHERE username=? AND name=?";
62
    private static final String DELETE_PROPERTY =
63
        "DELETE FROM ofUserProp WHERE username=? AND name=?";
64
    private static final String UPDATE_PROPERTY =
65
        "UPDATE ofUserProp SET propValue=? WHERE name=? AND username=?";
66
    private static final String INSERT_PROPERTY =
67
        "INSERT INTO ofUserProp (username, name, propValue) VALUES (?, ?, ?)";
68

69 70 71 72 73
    // 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";

74 75 76 77 78 79 80 81
    private String username;
    private String name;
    private String email;
    private Date creationDate;
    private Date modificationDate;

    private Map<String,String> properties = null;

82 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
    /**
     * 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) {
            Log.error(sqle);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
        return propertyValue;
    }

117 118 119 120 121 122
    /**
     * Constructor added for Externalizable. Do not use this constructor.
     */
    public User() {
    }

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

        try {
177
            AuthFactory.getAuthProvider().setPassword(username, password);
178 179

            // Fire event.
180
            Map<String,Object> params = new HashMap<String,Object>();
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
            params.put("type", "passwordModified");
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
            Log.error(unfe);
        }
    }

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

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

199 200 201 202 203
        if (name != null && name.matches("\\s*")) {
        	name = null;
        }
        
        if (name == null && UserManager.getUserProvider().isNameRequired()) {
204 205
            throw new IllegalArgumentException("User provider requires name.");
        }
206
        
207 208 209 210 211 212
        try {
            String originalName = this.name;
            UserManager.getUserProvider().setName(username, name);
            this.name = name;

            // Fire event.
213
            Map<String,Object> params = new HashMap<String,Object>();
214 215 216 217 218 219 220 221 222 223
            params.put("type", "nameModified");
            params.put("originalValue", originalName);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
            Log.error(unfe);
        }
    }

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

    public void setEmail(String email) {
        if (UserManager.getUserProvider().isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }
255 256 257 258
        
        if (email != null && email.matches("\\s*")) {
        	email = null;
        }
259

260 261 262 263
        if (UserManager.getUserProvider().isEmailRequired() && !StringUtils.isValidEmailAddress(email)) {
            throw new IllegalArgumentException("User provider requires email address.");
        }

264 265 266 267 268
        try {
            String originalEmail= this.email;
            UserManager.getUserProvider().setEmail(username, email);
            this.email = email;
            // Fire event.
269
            Map<String,Object> params = new HashMap<String,Object>();
270 271 272 273 274 275 276 277 278 279
            params.put("type", "emailModified");
            params.put("originalValue", originalEmail);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
            Log.error(unfe);
        }
    }

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    /**
     * 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));
    }

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

    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.
339
            Map<String,Object> params = new HashMap<String,Object>();
340 341 342 343 344 345 346 347 348 349 350
            params.put("type", "nameModified");
            params.put("originalValue", originalModificationDate);
            UserEventDispatcher.dispatchEvent(this, UserEventDispatcher.EventType.user_modified,
                    params);
        }
        catch (UserNotFoundException unfe) {
            Log.error(unfe);
        }
    }

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
351
     * Returns all extended properties of the user. Users have an arbitrary
Gaston Dombiak's avatar
Gaston Dombiak committed
352 353
     * number of extended properties. The returned collection can be modified
     * to add new properties or remove existing ones.
354 355 356 357 358 359 360 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 386 387 388 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
     *
     * @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) {
            Log.error(unfe);
            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) {
424
            Map<String,Object> eventParams = new HashMap<String,Object>();
425 426 427
            Object answer;
            String keyString = (String) key;
            synchronized (keyString.intern()) {
428 429
                if (properties.containsKey(keyString)) {
                    String originalValue = properties.get(keyString);
430 431 432 433 434 435 436 437 438 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
                    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.
488
                    Map<String,Object> params = new HashMap<String,Object>();
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
                    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) {
            Log.error(sqle);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }

    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) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }

    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) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }

    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) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

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