Commit 6d384581 authored by Matt Tucker's avatar Matt Tucker Committed by matt

Refactoring to remove userID.


git-svn-id: http://svn.igniterealtime.org/svn/repos/messenger/trunk@268 b35dd754-fafc-0310-a699-88a17e54d16e
parent 86fb6e82
...@@ -3,12 +3,10 @@ ...@@ -3,12 +3,10 @@
-- $Date$ -- $Date$
CREATE TABLE jiveUser ( CREATE TABLE jiveUser (
userID INTEGER NOT NULL, username VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL, password VARCHAR(32) NOT NULL,
name VARCHAR(100), name VARCHAR(100),
nameVisible INTEGER NOT NULL,
email VARCHAR(100), email VARCHAR(100),
emailVisible INTEGER NOT NULL,
creationDate CHAR(15) NOT NULL, creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL, modificationDate CHAR(15) NOT NULL,
CONSTRAINT jiveUser_pk PRIMARY KEY (userID) CONSTRAINT jiveUser_pk PRIMARY KEY (userID)
...@@ -17,7 +15,7 @@ CREATE INDEX jiveUsr_cDate_idx ON jiveUser (creationDate ASC); ...@@ -17,7 +15,7 @@ CREATE INDEX jiveUsr_cDate_idx ON jiveUser (creationDate ASC);
CREATE TABLE jiveUserProp ( CREATE TABLE jiveUserProp (
userID INTEGER NOT NULL, username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
propValue VARCHAR(2000) NOT NULL, propValue VARCHAR(2000) NOT NULL,
CONSTRAINT jiveUsrProp_pk PRIMARY KEY (userID, name) CONSTRAINT jiveUsrProp_pk PRIMARY KEY (userID, name)
...@@ -25,7 +23,7 @@ CREATE TABLE jiveUserProp ( ...@@ -25,7 +23,7 @@ CREATE TABLE jiveUserProp (
CREATE TABLE jivePrivate ( CREATE TABLE jivePrivate (
userID INTEGER NOT NULL, username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
namespace VARCHAR(200) NOT NULL, namespace VARCHAR(200) NOT NULL,
value LONG VARCHAR NOT NULL, value LONG VARCHAR NOT NULL,
...@@ -34,7 +32,7 @@ CREATE TABLE jivePrivate ( ...@@ -34,7 +32,7 @@ CREATE TABLE jivePrivate (
CREATE TABLE jiveOffline ( CREATE TABLE jiveOffline (
userID INTEGER NOT NULL, username VARCHAR(32) NOT NULL,
messageID INTEGER NOT NULL, messageID INTEGER NOT NULL,
creationDate CHAR(15) NOT NULL, creationDate CHAR(15) NOT NULL,
messageSize INTEGER NOT NULL, messageSize INTEGER NOT NULL,
...@@ -45,7 +43,7 @@ CREATE TABLE jiveOffline ( ...@@ -45,7 +43,7 @@ CREATE TABLE jiveOffline (
CREATE TABLE jiveRoster ( CREATE TABLE jiveRoster (
rosterID INTEGER NOT NULL, rosterID INTEGER NOT NULL,
userID INTEGER NOT NULL, username VARCHAR(32) NOT NULL,
jid VARCHAR(2000) NOT NULL, jid VARCHAR(2000) NOT NULL,
sub INTEGER NOT NULL, sub INTEGER NOT NULL,
ask INTEGER NOT NULL, ask INTEGER NOT NULL,
...@@ -66,23 +64,13 @@ CREATE INDEX jiveRoGrps_rid_idx ON jiveRosterGroups (rosterID ASC); ...@@ -66,23 +64,13 @@ CREATE INDEX jiveRoGrps_rid_idx ON jiveRosterGroups (rosterID ASC);
CREATE TABLE jiveVCard ( CREATE TABLE jiveVCard (
userID INTEGER NOT NULL, username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
propValue VARCHAR(2000) NOT NULL, propValue VARCHAR(2000) NOT NULL,
CONSTRAINT JiveVCard_pk PRIMARY KEY (userID, name) CONSTRAINT JiveVCard_pk PRIMARY KEY (userID, name)
); );
CREATE TABLE jiveDomain (
domainID INTEGER NOT NULL,
name VARCHAR(100) UNIQUE NOT NULL,
description VARCHAR(255),
creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL,
CONSTRAINT jiveDomain_pk PRIMARY KEY (domainID)
);
CREATE TABLE jiveChatbot ( CREATE TABLE jiveChatbot (
chatbotID INTEGER NOT NULL, chatbotID INTEGER NOT NULL,
description VARCHAR(255), description VARCHAR(255),
...@@ -92,16 +80,6 @@ CREATE TABLE jiveChatbot ( ...@@ -92,16 +80,6 @@ CREATE TABLE jiveChatbot (
); );
CREATE TABLE jiveUserID (
username VARCHAR(30) UNIQUE NOT NULL,
domainID INTEGER NOT NULL,
objectType INTEGER NOT NULL,
objectID INTEGER NOT NULL,
CONSTRAINT jiveUserID_pk PRIMARY KEY (username, domainID)
);
CREATE INDEX jiveUsrID_obj_idx ON jiveUserID (objectType, objectID);
CREATE TABLE jiveGroup ( CREATE TABLE jiveGroup (
groupID INTEGER NOT NULL, groupID INTEGER NOT NULL,
name VARCHAR(50) NOT NULL, name VARCHAR(50) NOT NULL,
......
...@@ -3,49 +3,47 @@ ...@@ -3,49 +3,47 @@
// $Date$ // $Date$
CREATE TABLE jiveUser ( CREATE TABLE jiveUser (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL, password VARCHAR(32) NOT NULL,
name VARCHAR(100), name VARCHAR(100),
nameVisible INTEGER NOT NULL,
email VARCHAR(100), email VARCHAR(100),
emailVisible INTEGER NOT NULL,
creationDate VARCHAR(15) NOT NULL, creationDate VARCHAR(15) NOT NULL,
modificationDate VARCHAR(15) NOT NULL, modificationDate VARCHAR(15) NOT NULL,
CONSTRAINT jiveUser_pk PRIMARY KEY (userID) CONSTRAINT jiveUser_pk PRIMARY KEY (username)
); );
CREATE INDEX jiveUser_cDate_idx ON jiveUser (creationDate); CREATE INDEX jiveUser_cDate_idx ON jiveUser (creationDate);
CREATE TABLE jiveUserProp ( CREATE TABLE jiveUserProp (
userID BIGINT NOT NULL, username VARHCAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
propValue VARCHAR(4000) NOT NULL, propValue VARCHAR(4000) NOT NULL,
CONSTRAINT jiveUserProp_pk PRIMARY KEY (userID, name) CONSTRAINT jiveUserProp_pk PRIMARY KEY (username, name)
); );
CREATE TABLE jivePrivate ( CREATE TABLE jivePrivate (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
namespace VARCHAR(200) NOT NULL, namespace VARCHAR(200) NOT NULL,
value LONGVARCHAR NOT NULL, value LONGVARCHAR NOT NULL,
CONSTRAINT jivePrivate_pk PRIMARY KEY (userID, name, namespace) CONSTRAINT jivePrivate_pk PRIMARY KEY (username, name, namespace)
); );
CREATE TABLE jiveOffline ( CREATE TABLE jiveOffline (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
messageID BIGINT NOT NULL, messageID BIGINT NOT NULL,
creationDate VARCHAR(15) NOT NULL, creationDate VARCHAR(15) NOT NULL,
messageSize INTEGER NOT NULL, messageSize INTEGER NOT NULL,
message LONGVARCHAR NOT NULL, message LONGVARCHAR NOT NULL,
CONSTRAINT jiveOffline_pk PRIMARY KEY (userID, messageID) CONSTRAINT jiveOffline_pk PRIMARY KEY (username, messageID)
); );
CREATE TABLE jiveRoster ( CREATE TABLE jiveRoster (
rosterID BIGINT NOT NULL, rosterID BIGINT NOT NULL,
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
jid VARCHAR(3071) NOT NULL, jid VARCHAR(3071) NOT NULL,
sub INTEGER NOT NULL, sub INTEGER NOT NULL,
ask INTEGER NOT NULL, ask INTEGER NOT NULL,
...@@ -53,7 +51,7 @@ CREATE TABLE jiveRoster ( ...@@ -53,7 +51,7 @@ CREATE TABLE jiveRoster (
nick VARCHAR(255), nick VARCHAR(255),
CONSTRAINT jiveRoster_pk PRIMARY KEY (rosterID) CONSTRAINT jiveRoster_pk PRIMARY KEY (rosterID)
); );
CREATE INDEX jiveRoster_userid_idx ON jiveRoster (userID); CREATE INDEX jiveRoster_username_idx ON jiveRoster (username);
CREATE TABLE jiveRosterGroups ( CREATE TABLE jiveRosterGroups (
...@@ -66,10 +64,10 @@ CREATE INDEX jiveRosterGroup_rosterid_idx ON jiveRosterGroups (rosterID); ...@@ -66,10 +64,10 @@ CREATE INDEX jiveRosterGroup_rosterid_idx ON jiveRosterGroups (rosterID);
CREATE TABLE jiveVCard ( CREATE TABLE jiveVCard (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
propValue VARCHAR(4000) NOT NULL, propValue VARCHAR(4000) NOT NULL,
CONSTRAINT jiveVCard_pk PRIMARY KEY (userID, name) CONSTRAINT jiveVCard_pk PRIMARY KEY (username, name)
); );
...@@ -84,26 +82,6 @@ CREATE TABLE jiveDomain ( ...@@ -84,26 +82,6 @@ CREATE TABLE jiveDomain (
); );
CREATE TABLE jiveChatbot (
chatbotID BIGINT NOT NULL,
description VARCHAR(255),
creationDate VARCHAR(15) NOT NULL,
modificationDate VARCHAR(15) NOT NULL,
CONSTRAINT jiveChatbot_pk PRIMARY KEY (chatbotID)
);
CREATE TABLE jiveUserID (
username VARCHAR(30) NOT NULL,
domainID BIGINT NOT NULL,
objectType INTEGER NOT NULL,
objectID BIGINT NOT NULL,
CONSTRAINT jiveUserID_pk PRIMARY KEY (username, domainID),
CONSTRAINT jiveUserID_username UNIQUE (username)
);
CREATE INDEX jiveUserID_object_idx ON jiveUserID (objectType, objectID);
CREATE TABLE jiveGroup ( CREATE TABLE jiveGroup (
groupID BIGINT NOT NULL, groupID BIGINT NOT NULL,
name VARCHAR(50) NOT NULL, name VARCHAR(50) NOT NULL,
...@@ -126,9 +104,9 @@ CREATE TABLE jiveGroupProp ( ...@@ -126,9 +104,9 @@ CREATE TABLE jiveGroupProp (
CREATE TABLE jiveGroupUser ( CREATE TABLE jiveGroupUser (
groupID BIGINT NOT NULL, groupID BIGINT NOT NULL,
userID BIGINT NOT NULL, username BIGINT NOT NULL,
administrator INTEGER NOT NULL, administrator INTEGER NOT NULL,
CONSTRAINT jiveGroupUser_pk PRIMARY KEY (groupID, userID, administrator) CONSTRAINT jiveGroupUser_pk PRIMARY KEY (groupID, username, administrator)
); );
...@@ -211,11 +189,5 @@ INSERT INTO jiveID (idType, id) VALUES (19, 1); ...@@ -211,11 +189,5 @@ INSERT INTO jiveID (idType, id) VALUES (19, 1);
INSERT INTO jiveID (idType, id) VALUES (23, 1); INSERT INTO jiveID (idType, id) VALUES (23, 1);
// Entry for admin user -- password is "admin" // Entry for admin user -- password is "admin"
INSERT INTO jiveUserID (username, domainID, objectType, objectID) VALUES ('admin', 1, 0, 1); INSERT INTO jiveUser (username, password, name, email, creationDate, modificationDate)
INSERT INTO jiveUser (userID, name, password, email, emailVisible, nameVisible, creationDate, modificationDate) VALUES ('admin', 'admin', 'Administrator', 'admin@example.com', '0', '0');
VALUES (1, 'Administrator', 'admin', 'admin@example.com', 1, 1, '0', '0'); \ No newline at end of file
// Make the administrator an admin member of the Administrators group
INSERT INTO jiveGroup (groupID, name, description, creationDate, modificationDate)
VALUES (1, 'Administrators', 'Messenger Server administrators', '0', '0');
INSERT INTO jiveGroupUser (groupID, userID, administrator) VALUES (1, 1, 1);
...@@ -3,53 +3,75 @@ ...@@ -3,53 +3,75 @@
# $Date$ # $Date$
CREATE TABLE jiveUser ( CREATE TABLE jiveUser (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL, password VARCHAR(32) NOT NULL,
name VARCHAR(100), name VARCHAR(100),
nameVisible TINYINT NOT NULL,
email VARCHAR(100), email VARCHAR(100),
emailVisible TINYINT NOT NULL,
creationDate CHAR(15) NOT NULL, creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL, modificationDate CHAR(15) NOT NULL,
PRIMARY KEY (userID), PRIMARY KEY (username),
INDEX jiveUser_cDate_idx (creationDate) INDEX jiveUser_cDate_idx (creationDate)
); );
CREATE TABLE jiveUserProp ( CREATE TABLE jiveUserProp (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
propValue TEXT NOT NULL, propValue TEXT NOT NULL,
PRIMARY KEY (userID, name) PRIMARY KEY (username, name)
); );
CREATE TABLE jiveGroup (
groupID BIGINT NOT NULL,
name VARCHAR(50) NOT NULL,
description VARCHAR(255),
creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL,
PRIMARY KEY (groupID),
INDEX jiveGroup_cDate_idx (creationDate),
INDEX jiveGroup_name_idx (name(10))
);
CREATE TABLE jivePrivate ( CREATE TABLE jiveGroupProp (
groupID BIGINT NOT NULL,
name VARCHAR(100) NOT NULL,
propValue TEXT NOT NULL,
PRIMARY KEY (groupID, name)
);
CREATE TABLE jiveGroupUser (
groupID BIGINT NOT NULL,
userID BIGINT NOT NULL, userID BIGINT NOT NULL,
administrator TINYINT NOT NULL,
PRIMARY KEY (groupID, userID, administrator)
);
CREATE TABLE jivePrivate (
username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
namespace VARCHAR(200) NOT NULL, namespace VARCHAR(200) NOT NULL,
value TEXT NOT NULL, value TEXT NOT NULL,
PRIMARY KEY (userID, name, namespace) PRIMARY KEY (username, name, namespace)
); );
CREATE TABLE jiveOffline ( CREATE TABLE jiveOffline (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
messageID BIGINT NOT NULL, messageID BIGINT NOT NULL,
creationDate CHAR(15) NOT NULL, creationDate CHAR(15) NOT NULL,
messageSize INTEGER NOT NULL, messageSize INTEGER NOT NULL,
message TEXT NOT NULL, message TEXT NOT NULL,
PRIMARY KEY (userID, messageID) PRIMARY KEY (username, messageID)
); );
CREATE TABLE jiveRoster ( CREATE TABLE jiveRoster (
rosterID BIGINT NOT NULL, rosterID BIGINT NOT NULL,
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
jid TEXT NOT NULL, jid TEXT NOT NULL,
sub TINYINT NOT NULL, sub TINYINT NOT NULL,
ask TINYINT NOT NULL, ask TINYINT NOT NULL,
recv TINYINT NOT NULL, recv TINYINT NOT NULL,
nick VARCHAR(255), nick VARCHAR(255),
PRIMARY KEY (rosterID), PRIMARY KEY (rosterID),
INDEX jiveRoster_userid_idx (userID) INDEX jiveRoster_unameid_idx (username)
); );
CREATE TABLE jiveRosterGroups ( CREATE TABLE jiveRosterGroups (
...@@ -61,19 +83,10 @@ CREATE TABLE jiveRosterGroups ( ...@@ -61,19 +83,10 @@ CREATE TABLE jiveRosterGroups (
); );
CREATE TABLE jiveVCard ( CREATE TABLE jiveVCard (
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
propValue TEXT NOT NULL, propValue TEXT NOT NULL,
PRIMARY KEY (userID, name) PRIMARY KEY (username, name)
);
CREATE TABLE jiveDomain (
domainID BIGINT NOT NULL,
name VARCHAR(100) UNIQUE NOT NULL,
description VARCHAR(255),
creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL,
PRIMARY KEY (domainID)
); );
CREATE TABLE jiveChatbot ( CREATE TABLE jiveChatbot (
...@@ -84,40 +97,6 @@ CREATE TABLE jiveChatbot ( ...@@ -84,40 +97,6 @@ CREATE TABLE jiveChatbot (
PRIMARY KEY (chatbotID) PRIMARY KEY (chatbotID)
); );
CREATE TABLE jiveUserID (
username VARCHAR(30) UNIQUE NOT NULL,
domainID BIGINT NOT NULL,
objectType INTEGER NOT NULL,
objectID BIGINT NOT NULL,
PRIMARY KEY (username, domainID),
INDEX jiveUser_object_idx (objectType, objectID)
);
CREATE TABLE jiveGroup (
groupID BIGINT NOT NULL,
name VARCHAR(50) NOT NULL,
description VARCHAR(255),
creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL,
PRIMARY KEY (groupID),
INDEX jiveGroup_cDate_idx (creationDate),
INDEX jiveGroup_name_idx (name(10))
);
CREATE TABLE jiveGroupProp (
groupID BIGINT NOT NULL,
name VARCHAR(100) NOT NULL,
propValue TEXT NOT NULL,
PRIMARY KEY (groupID, name)
);
CREATE TABLE jiveGroupUser (
groupID BIGINT NOT NULL,
userID BIGINT NOT NULL,
administrator TINYINT NOT NULL,
PRIMARY KEY (groupID, userID, administrator)
);
CREATE TABLE jiveID ( CREATE TABLE jiveID (
idType INTEGER NOT NULL, idType INTEGER NOT NULL,
id BIGINT NOT NULL, id BIGINT NOT NULL,
...@@ -198,18 +177,12 @@ INSERT INTO jiveID (idType, id) VALUES (23, 1); ...@@ -198,18 +177,12 @@ INSERT INTO jiveID (idType, id) VALUES (23, 1);
CREATE TABLE jiveUserPerm ( CREATE TABLE jiveUserPerm (
objectType INTEGER NOT NULL, objectType INTEGER NOT NULL,
objectID BIGINT NOT NULL, objectID BIGINT NOT NULL,
userID BIGINT NOT NULL, username VARCHAR(32) NOT NULL,
permission INTEGER NOT NULL, permission INTEGER NOT NULL,
INDEX jiveUserPerm_object_idx (objectType, objectID), INDEX jiveUserPerm_object_idx (objectType, objectID),
INDEX jiveUserPerm_userID_idx (userID) INDEX jiveUserPerm_uname_idx (username)
); );
# Entry for admin user -- password is "admin" # Entry for admin user -- password is "admin"
INSERT INTO jiveUserID (username, domainID, objectType, objectID) VALUES ('admin', 1, 0, 1); INSERT INTO jiveUser (username, password, name, email, creationDate, modificationDate)
INSERT INTO jiveUser (userID, name, password, email, emailVisible, nameVisible, creationDate, modificationDate) VALUES ('admin', 'admin', 'Administrator', 'admin@example.com', '0', '0');
VALUES (1, 'Administrator', 'admin', 'admin@example.com', 1, 1, '0', '0'); \ No newline at end of file
# Make the administrator an admin member of the Administrators group
INSERT INTO jiveGroup (groupID, name, description, creationDate, modificationDate)
VALUES (1, 'Administrators', 'Messenger Server administrators', '0', '0');
INSERT INTO jiveGroupUser (groupID, userID, administrator) VALUES (1, 1, 1);
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger;
/**
* <p>A generic entity on the system identified by a unique ID and username.</p>
* <p/>
* <p>Entities include Chatbots and Users and can reserve messenger 'entity
* resources' such as groups, permissions, private storage, etc. From an
* API standpoint, the Entity provides a common base interface for these
* items when being sent and returned from generic resource services.</p>
*
* @author Iain Shigeoka
*/
public interface Entity {
/**
* <p>Returns the entity's id.</p>
* <p/>
* <p>All ids must be unique in the system across all Chatbots and Users.</p>
*
* @return the entity's id.
*/
long getID();
/**
* <p>Returns the entity's username.</p>
* <p/>
* <p>All usernames must be unique in the system.</p>
*
* @return the username of the entity.
*/
String getUsername();
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger;
import org.jivesoftware.messenger.user.UserNotFoundException;
/**
* <p>Provides a generic interface to the known names and unique long IDs on the server.</p>
* <p/>
* <p>Several types of entities can be addressed in Messenger using a username-id combination
* including users and chatbots. Usernames are used to create unique XMPP addresses of the form
* username@server.com and the long ID provides a key used to associate all related resources
* (private storage, rosters, etc) to that username. In many cases it is desirable to distinguish between
* users, chatbots, etc and the appropriate *Manager classes allow this specialized access (e.g.
* Users are found with the UserManager, Chatbots with the ChatbotManager). The NameIDManager is the
* generic interface to all names and ids on the system without distinguishing what particular
* type of username-id owner it belongs to.</p>
*/
public interface NameIDManager {
/**
* <p>Obtain the username associated with the given ID.</p>
*
* @param id The id used for lookup
* @return The username corresponding to the ID
* @throws UserNotFoundException If the id doesn't correspond to a known username-id combination on the server
*/
String getUsername(long id) throws UserNotFoundException;
/**
* <p>Obtain the ID associated with the given username.</p>
*
* @param username The username used for lookup
* @return The ID corresponding to the username
* @throws UserNotFoundException If the id doesn't correspond to a known username-id combination on the server
*/
long getID(String username) throws UserNotFoundException;
}
...@@ -44,37 +44,17 @@ public interface OfflineMessageStore { ...@@ -44,37 +44,17 @@ public interface OfflineMessageStore {
* messages stay in the message store and will be available to other * messages stay in the message store and will be available to other
* users of getMessages().</p> * users of getMessages().</p>
* *
* @param userName The user name of the user who's messages you'd like to receive * @param username the username of the user who's messages you'd like to receive
* @return An iterator of packets containing all offline messages * @return An iterator of packets containing all offline messages
* @throws UnauthorizedException If the user is not allowed to retrieve messages * @throws UnauthorizedException If the user is not allowed to retrieve messages
*/ */
Iterator getMessages(String userName) throws UnauthorizedException, UserNotFoundException; Iterator getMessages(String username) throws UnauthorizedException, UserNotFoundException;
/**
* <p>Obtain all messages in the store for a user.</p>
* <p>Remove messages using the iterator.remove() method. Otherwise
* messages stay in the message store and will be available to other
* users of getMessages().</p>
*
* @param userID The user ID of the user who's messages you'd like to receive
* @return An iterator of packets containing all offline messages
* @throws UnauthorizedException If the user is not allowed to retrieve messages
*/
Iterator getMessages(long userID) throws UnauthorizedException;
/** /**
* <p>Obtain the approximate size of the XML messages stored for a particular user.</p> * <p>Obtain the approximate size of the XML messages stored for a particular user.</p>
* *
* @param userID The user ID of the user who's messages you'd like to receive * @param username the username of the user who's messages you'd like to receive
* @return The approximate size of messages stored in bytes
*/
int getSize(long userID) throws UnauthorizedException;
/**
* Obtain the approximate size of the XML messages stored for a particular user.
*
* @param userName The user name of the user who's messages you'd like to receive
* @return The approximate size of messages stored in bytes * @return The approximate size of messages stored in bytes
*/ */
int getSize(String userName) throws UnauthorizedException, UserNotFoundException; int getSize(String username) throws UnauthorizedException;
} }
\ No newline at end of file
...@@ -142,7 +142,7 @@ public interface Presence extends XMPPPacket { ...@@ -142,7 +142,7 @@ public interface Presence extends XMPPPacket {
* *
* @return the presence owner. * @return the presence owner.
*/ */
public long getUserID(); public String getUsername();
/** /**
* Return the time when the presence was created. * Return the time when the presence was created.
...@@ -210,4 +210,4 @@ public interface Presence extends XMPPPacket { ...@@ -210,4 +210,4 @@ public interface Presence extends XMPPPacket {
* @throws UnauthorizedException If the caller doesn't have the appropriate authorization * @throws UnauthorizedException If the caller doesn't have the appropriate authorization
*/ */
public void setPriority(int priority) throws UnauthorizedException; public void setPriority(int priority) throws UnauthorizedException;
} }
\ No newline at end of file
...@@ -14,6 +14,7 @@ package org.jivesoftware.messenger; ...@@ -14,6 +14,7 @@ package org.jivesoftware.messenger;
import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.User; import org.jivesoftware.messenger.user.User;
import java.util.Iterator; import java.util.Iterator;
import java.util.Collection;
/** /**
* The presence manager tracks on a global basis who's online. The presence * The presence manager tracks on a global basis who's online. The presence
...@@ -43,14 +44,6 @@ public interface PresenceManager { ...@@ -43,14 +44,6 @@ public interface PresenceManager {
*/ */
public boolean isAvailable(User user) throws UnauthorizedException; public boolean isAvailable(User user) throws UnauthorizedException;
/**
* Returns the number of users who are currently online. Online users with a
* presence status set to invisible will not be included.
*
* @return the number of online users.
*/
public int getOnlineUserCount();
/** /**
* Returns the number of guests who are currently online. Guests with a * Returns the number of guests who are currently online. Guests with a
* presence status other that online or idle will not be included. * presence status other that online or idle will not be included.
...@@ -60,33 +53,33 @@ public interface PresenceManager { ...@@ -60,33 +53,33 @@ public interface PresenceManager {
public int getOnlineGuestCount(); public int getOnlineGuestCount();
/** /**
* Returns an iterator of users who are currently online. Online users with a * Returns a Collection of users who are currently online. Online users with a
* presence status other that online or idle will not be included. * presence status other that online or idle will not be included.
* *
* @return an iterator of online users. * @return a Collection of online users.
*/ */
public Iterator getOnlineUsers(); public Collection<User> getOnlineUsers();
/** /**
* Returns an iterator of users sorted in the manner requested who are currently online. * Returns a Collection of users sorted in the manner requested who are currently online.
* Online users with a presence status other that online or idle will not be included. * Online users with a presence status other that online or idle will not be included.
* *
* @param ascending sort ascending if true, descending if false. * @param ascending sort ascending if true, descending if false.
* @param sortField a valid sort field from the PresenceManager interface. * @param sortField a valid sort field from the PresenceManager interface.
* @return an iterator of online users. * @return a Collection of online users.
*/ */
public Iterator getOnlineUsers(boolean ascending, int sortField); public Collection<User> getOnlineUsers(boolean ascending, int sortField);
/** /**
* Returns an iterator of users who are currently online matching the criteria given. * Returns a Collection of users who are currently online matching the criteria given.
* Online users with a presence status other than online or idle will not be included. * Online users with a presence status other than online or idle will not be included.
* *
* @param ascending sort ascending if true, descending if false. * @param ascending sort ascending if true, descending if false.
* @param sortField a valid sort field from the PresenceManager interface. * @param sortField a valid sort field from the PresenceManager interface.
* @param numResults - the number of results to return. * @param numResults - the number of results to return.
* @return an iterator of online users matching the given criteria. * @return an Collection of online users matching the given criteria.
*/ */
public Iterator getOnlineUsers(boolean ascending, int sortField, int numResults); public Collection<User> getOnlineUsers(boolean ascending, int sortField, int numResults);
/** /**
* Create a presence for a user. Creating a presence will automatically set the user to be * Create a presence for a user. Creating a presence will automatically set the user to be
...@@ -133,4 +126,4 @@ public interface PresenceManager { ...@@ -133,4 +126,4 @@ public interface PresenceManager {
* @param probee The XMPPAddress whos presence we would like sent have have probed * @param probee The XMPPAddress whos presence we would like sent have have probed
*/ */
public void probePresence(XMPPAddress prober, XMPPAddress probee) throws UnauthorizedException; public void probePresence(XMPPAddress prober, XMPPAddress probee) throws UnauthorizedException;
} }
\ No newline at end of file
...@@ -46,11 +46,11 @@ public interface PrivateStore { ...@@ -46,11 +46,11 @@ public interface PrivateStore {
* <p>If the name and namespace of the element matches another * <p>If the name and namespace of the element matches another
* stored private data XML document, then replace it with the new one.</p> * stored private data XML document, then replace it with the new one.</p>
* *
* @param data The data to store (XML element) * @param data the data to store (XML element)
* @param userID The user ID of account where private data is being stored * @param username the username of the account where private data is being stored
* @throws UnauthorizedException If there are insufficient permissions to access the data * @throws UnauthorizedException If there are insufficient permissions to access the data
*/ */
void add(long userID, Element data) throws UnauthorizedException; void add(String username, Element data) throws UnauthorizedException;
/** /**
* <p>Retrieve the data stored under a key corresponding to the name and namespace of * <p>Retrieve the data stored under a key corresponding to the name and namespace of
...@@ -62,9 +62,9 @@ public interface PrivateStore { ...@@ -62,9 +62,9 @@ public interface PrivateStore {
* <p>If no data is currently stored under the given key, return the query.</p> * <p>If no data is currently stored under the given key, return the query.</p>
* *
* @param data An XML document who's element name and namespace is used to match previously stored private data * @param data An XML document who's element name and namespace is used to match previously stored private data
* @param userID The user ID of account where private data is being stored * @param username the username of the account where private data is being stored
* @return The data stored under the given key or the data element * @return The data stored under the given key or the data element
* @throws UnauthorizedException If there are insufficient permissions to access the data * @throws UnauthorizedException If there are insufficient permissions to access the data
*/ */
Element get(long userID, Element data) throws UnauthorizedException; Element get(String username, Element data) throws UnauthorizedException;
} }
\ No newline at end of file
...@@ -60,9 +60,7 @@ public class ServerSession implements Session { ...@@ -60,9 +60,7 @@ public class ServerSession implements Session {
return null; return null;
} }
public void setAuthToken(AuthToken auth, public void setAuthToken(AuthToken auth, UserManager userManager, String resource) {
UserManager userManager,
String resource) {
} }
public void setAnonymousAuth() throws UnauthorizedException { public void setAnonymousAuth() throws UnauthorizedException {
...@@ -77,8 +75,8 @@ public class ServerSession implements Session { ...@@ -77,8 +75,8 @@ public class ServerSession implements Session {
return streamID; return streamID;
} }
public long getUserID() throws UserNotFoundException, UnauthorizedException { public String getUsername() throws UserNotFoundException, UnauthorizedException {
return 0; return null;
} }
public String getServerName() { public String getServerName() {
......
...@@ -144,15 +144,15 @@ public interface Session extends RoutableChannelHandler { ...@@ -144,15 +144,15 @@ public interface Session extends RoutableChannelHandler {
public StreamID getStreamID(); public StreamID getStreamID();
/** /**
* <p>Obtain the user ID associated with this session.</p> * Returns the username associated with this session. Use this information
* <p>Use this information with the user manager to obtain the * with the user manager to obtain the user based on username.
* user based on ID.</p>
* *
* @return The user ID associated with this session * @return the username associated with this session
* @throws UserNotFoundException if a user is not associated with a session (the session has not authenticated yet) * @throws UserNotFoundException if a user is not associated with a session
* @throws UnauthorizedException If caller doesn't have permission to access this information * (the session has not authenticated yet)
* @throws UnauthorizedException If caller doesn't have permission to access this information.
*/ */
public long getUserID() throws UserNotFoundException, UnauthorizedException; public String getUsername() throws UserNotFoundException, UnauthorizedException;
/** /**
* Obtain the name of the server this session belongs to. * Obtain the name of the server this session belongs to.
......
...@@ -46,19 +46,6 @@ public class SessionResultFilter { ...@@ -46,19 +46,6 @@ public class SessionResultFilter {
*/ */
public static final int ASCENDING = 1; public static final int ASCENDING = 1;
// ############################################################
// User search criteria
// ############################################################
/**
* <p>Represents an anonymous user id that matches all anonymous users.</p>
*/
public static final int ANONYMOUS_USER_ID = -1;
/**
* <p>Represents a user id that matches any/all users.</p>
*/
public static final int ALL_USER_ID = -2;
// ############################################################ // ############################################################
// Result limit search criteria // Result limit search criteria
// ############################################################ // ############################################################
...@@ -101,6 +88,8 @@ public class SessionResultFilter { ...@@ -101,6 +88,8 @@ public class SessionResultFilter {
private long serverPacketRangeMin = NO_PACKET_LIMIT; private long serverPacketRangeMin = NO_PACKET_LIMIT;
private long serverPacketRangeMax = NO_PACKET_LIMIT; private long serverPacketRangeMax = NO_PACKET_LIMIT;
private String username = null;
/** /**
* The starting index for results. Default is 0. * The starting index for results. Default is 0.
*/ */
...@@ -112,32 +101,29 @@ public class SessionResultFilter { ...@@ -112,32 +101,29 @@ public class SessionResultFilter {
*/ */
private int numResults = NO_RESULT_LIMIT; private int numResults = NO_RESULT_LIMIT;
private long userID = ALL_USER_ID;
private Date creationDateRangeMin = null; private Date creationDateRangeMin = null;
private Date creationDateRangeMax = null; private Date creationDateRangeMax = null;
private Date lastActivityDateRangeMin = null; private Date lastActivityDateRangeMin = null;
private Date lastActivityDateRangeMax = null; private Date lastActivityDateRangeMax = null;
/** /**
* Returns the userID that results will be filtered on. The method will * Returns the username that results will be filtered on. The method will
* return ALL_USER_ID if no user to filter on has been specified. The method * return <tt>null</tt> if no user to filter on has been specified.
* will return ANONYMOUS_USER_ID if filtering is to take place on all "anonymous" users.
* *
* @return the userID that results will be filtered on. * @return the username that results will be filtered on.
*/ */
public long getUserID() { public String getUsername() {
return userID; return username;
} }
/** /**
* Sets the userID that results will be filtered on. If you'd like to filter * Sets the username that results will be filtered on. By default, no filtering on
* on "anonymous" users, pass in an id of ANONYMOUS_USER_ID. By default, no filtering on * username will take place. To avoid filtering on username pass in <tt>null</tt>.
* userID's will take place. To avoid filtering on userID pass ALL_USER_ID.
* *
* @param userID the user ID to filter on. * @param username the user ID to filter on.
*/ */
public void setUserID(long userID) { public void setUsername(String username) {
this.userID = userID; this.username = username;
} }
/** /**
...@@ -145,8 +131,7 @@ public class SessionResultFilter { ...@@ -145,8 +131,7 @@ public class SessionResultFilter {
* sessions to be filtered on. If this value has not been set, the method * sessions to be filtered on. If this value has not been set, the method
* will return null. * will return null.
* *
* @return a Date representing the lower bound for creation dates to filter * @return a Date representing the lower bound for creation dates to filter on.
* on.
*/ */
public Date getCreationDateRangeMin() { public Date getCreationDateRangeMin() {
return creationDateRangeMin; return creationDateRangeMin;
...@@ -575,7 +560,7 @@ public class SessionResultFilter { ...@@ -575,7 +560,7 @@ public class SessionResultFilter {
clonedFilter.setSortField(getSortField()); clonedFilter.setSortField(getSortField());
clonedFilter.setSortOrder(getSortOrder()); clonedFilter.setSortOrder(getSortOrder());
clonedFilter.setStartIndex(getStartIndex()); clonedFilter.setStartIndex(getStartIndex());
clonedFilter.setUserID(getUserID()); clonedFilter.setUsername(getUsername());
return clonedFilter; return clonedFilter;
} }
...@@ -590,7 +575,7 @@ public class SessionResultFilter { ...@@ -590,7 +575,7 @@ public class SessionResultFilter {
sortOrder == o.sortOrder && sortOrder == o.sortOrder &&
startIndex == o.startIndex && startIndex == o.startIndex &&
numResults == o.numResults && numResults == o.numResults &&
userID == o.userID && username == o.username &&
((creationDateRangeMin == null && o.creationDateRangeMin == null) || ((creationDateRangeMin == null && o.creationDateRangeMin == null) ||
creationDateRangeMin.equals(o.creationDateRangeMin)) && creationDateRangeMin.equals(o.creationDateRangeMin)) &&
((creationDateRangeMax == null && o.creationDateRangeMax == null) || ((creationDateRangeMax == null && o.creationDateRangeMax == null) ||
......
...@@ -17,7 +17,6 @@ import org.jivesoftware.messenger.disco.IQDiscoItemsHandler; ...@@ -17,7 +17,6 @@ import org.jivesoftware.messenger.disco.IQDiscoItemsHandler;
import org.jivesoftware.messenger.muc.spi.MultiUserChatServerImpl; import org.jivesoftware.messenger.muc.spi.MultiUserChatServerImpl;
import org.jivesoftware.messenger.audit.spi.AuditManagerImpl; import org.jivesoftware.messenger.audit.spi.AuditManagerImpl;
import org.jivesoftware.messenger.auth.spi.GroupManagerImpl; import org.jivesoftware.messenger.auth.spi.GroupManagerImpl;
import org.jivesoftware.messenger.chatbot.spi.ChatbotManagerImpl;
import org.jivesoftware.messenger.handler.*; import org.jivesoftware.messenger.handler.*;
import org.jivesoftware.messenger.spi.*; import org.jivesoftware.messenger.spi.*;
import org.jivesoftware.messenger.transport.TransportHandler; import org.jivesoftware.messenger.transport.TransportHandler;
...@@ -41,9 +40,7 @@ public class XMPPBootContainer extends BootstrapContainer { ...@@ -41,9 +40,7 @@ public class XMPPBootContainer extends BootstrapContainer {
return new String[]{ return new String[]{
BasicServer.class.getName(), BasicServer.class.getName(),
RoutingTableImpl.class.getName(), RoutingTableImpl.class.getName(),
NameIDManagerImpl.class.getName(),
AuditManagerImpl.class.getName(), AuditManagerImpl.class.getName(),
ChatbotManagerImpl.class.getName(),
UserManagerImpl.class.getName(), UserManagerImpl.class.getName(),
RosterManagerImpl.class.getName(), RosterManagerImpl.class.getName(),
DbPrivateStore.class.getName()}; DbPrivateStore.class.getName()};
......
...@@ -15,9 +15,6 @@ import org.jivesoftware.util.LocaleUtils; ...@@ -15,9 +15,6 @@ import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log; import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils; import org.jivesoftware.util.StringUtils;
import org.jivesoftware.messenger.auth.spi.AuthTokenImpl; import org.jivesoftware.messenger.auth.spi.AuthTokenImpl;
import org.jivesoftware.messenger.user.UserIDProvider;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.UserProviderFactory;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
...@@ -50,7 +47,6 @@ public abstract class AuthFactory { ...@@ -50,7 +47,6 @@ public abstract class AuthFactory {
*/ */
public static final String SESSION_AUTHORIZATION = "jive.authToken"; public static final String SESSION_AUTHORIZATION = "jive.authToken";
private static UserIDProvider userIDProvider = null;
private static AuthProvider authProvider = null; private static AuthProvider authProvider = null;
private static MessageDigest sha; private static MessageDigest sha;
...@@ -62,8 +58,6 @@ public abstract class AuthFactory { ...@@ -62,8 +58,6 @@ public abstract class AuthFactory {
*/ */
static { static {
authProvider = AuthProviderFactory.getAuthProvider(); authProvider = AuthProviderFactory.getAuthProvider();
userIDProvider = UserProviderFactory.getUserIDProvider();
try { try {
sha = MessageDigest.getInstance("SHA"); sha = MessageDigest.getInstance("SHA");
} }
...@@ -119,14 +113,10 @@ public abstract class AuthFactory { ...@@ -119,14 +113,10 @@ public abstract class AuthFactory {
* @throws UnauthorizedException if the username and password do not match any existing user. * @throws UnauthorizedException if the username and password do not match any existing user.
*/ */
public static AuthToken getAuthToken(String username, String password) public static AuthToken getAuthToken(String username, String password)
throws UnauthorizedException { throws UnauthorizedException
{
authProvider.authenticate(username, password); authProvider.authenticate(username, password);
try { return new AuthTokenImpl(username);
return new AuthTokenImpl(userIDProvider.getUserID(username));
}
catch (UserNotFoundException e) {
throw new UnauthorizedException("User " + username + " authenticated but no ID found", e);
}
} }
/** /**
...@@ -144,19 +134,13 @@ public abstract class AuthFactory { ...@@ -144,19 +134,13 @@ public abstract class AuthFactory {
public static AuthToken getAuthToken(String username, String token, String digest) public static AuthToken getAuthToken(String username, String token, String digest)
throws UnauthorizedException { throws UnauthorizedException {
authProvider.authenticate(username, token, digest); authProvider.authenticate(username, token, digest);
try { return new AuthTokenImpl(username);
return new AuthTokenImpl(userIDProvider.getUserID(username));
}
catch (UserNotFoundException e) {
throw new UnauthorizedException("User " + username + " digest authenticated but no ID found", e);
}
} }
/** /**
* The same token can be used for all anonymous users, so cache it. * The same token can be used for all anonymous users, so cache it.
*/ */
private static final AuthToken anonymousAuth = new AuthTokenImpl(-1); private static final AuthToken anonymousAuth = new AuthTokenImpl(null);
/** /**
* Returns an anonymous user AuthToken. * Returns an anonymous user AuthToken.
......
...@@ -28,11 +28,11 @@ package org.jivesoftware.messenger.auth; ...@@ -28,11 +28,11 @@ package org.jivesoftware.messenger.auth;
public interface AuthToken { public interface AuthToken {
/** /**
* Returns the userID associated with this AuthToken. * Returns the username associated with this AuthToken.
* *
* @return the userID associated with this AuthToken. * @return the username associated with this AuthToken.
*/ */
public long getUserID(); public String getUsername();
/** /**
* Returns true if this AuthToken is the Anonymous auth token. * Returns true if this AuthToken is the Anonymous auth token.
......
...@@ -11,8 +11,9 @@ ...@@ -11,8 +11,9 @@
package org.jivesoftware.messenger.auth; package org.jivesoftware.messenger.auth;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.user.UserAlreadyExistsException; import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.User;
import java.util.Date; import java.util.Date;
import java.util.Iterator; import java.util.Iterator;
...@@ -30,8 +31,6 @@ import java.util.Iterator; ...@@ -30,8 +31,6 @@ import java.util.Iterator;
* Security for Group objects is provide by GroupProxy protection proxy objects. * Security for Group objects is provide by GroupProxy protection proxy objects.
* *
* @author Iain Shigeoka * @author Iain Shigeoka
*
* @see Entity
*/ */
public interface Group { public interface Group {
...@@ -156,52 +155,52 @@ public interface Group { ...@@ -156,52 +155,52 @@ public interface Group {
* Grants administrator privileges of the group to a user. This * Grants administrator privileges of the group to a user. This
* method is restricted to those with group administration permission. * method is restricted to those with group administration permission.
* *
* @param entity the User to grant adminstrative privileges to. * @param user the User to grant adminstrative privileges to.
* @throws UnauthorizedException if does not have group administrator permissions. * @throws UnauthorizedException if does not have group administrator permissions.
*/ */
public void addAdministrator(Entity entity) throws UnauthorizedException, UserAlreadyExistsException; public void addAdministrator(User user) throws UnauthorizedException, UserAlreadyExistsException;
/** /**
* Revokes administrator privileges of the group to a user. * Revokes administrator privileges of the group to a user.
* This method is restricted to those with group administration permission. * This method is restricted to those with group administration permission.
* *
* @param entity the User to grant adminstrative privileges to. * @param user the User to grant adminstrative privileges to.
* @throws UnauthorizedException if does not have group administrator permissions. * @throws UnauthorizedException if does not have group administrator permissions.
*/ */
public void removeAdministrator(Entity entity) throws UnauthorizedException; public void removeAdministrator(User user) throws UnauthorizedException;
/** /**
* Adds a member to the group. This method is restricted to * Adds a member to the group. This method is restricted to
* those with group administration permission. * those with group administration permission.
* *
* @param entity the User to add to the group. * @param user the User to add to the group.
* @throws UnauthorizedException if does not have group administrator permissions. * @throws UnauthorizedException if does not have group administrator permissions.
*/ */
public void addMember(Entity entity) throws UnauthorizedException, UserAlreadyExistsException; public void addMember(User user) throws UnauthorizedException, UserAlreadyExistsException;
/** /**
* Removes a member from the group. If the User is not * Removes a member from the group. If the User is not
* in the group, this method does nothing. This method * in the group, this method does nothing. This method
* is restricted to those with group administration permission. * is restricted to those with group administration permission.
* *
* @param entity the User to remove from the group. * @param user the User to remove from the group.
* @throws UnauthorizedException if does not have group administrator permissions. * @throws UnauthorizedException if does not have group administrator permissions.
*/ */
public void removeMember(Entity entity) throws UnauthorizedException; public void removeMember(User user) throws UnauthorizedException;
/** /**
* Returns true if the User has group administrator permissions. * Returns true if the User has group administrator permissions.
* *
* @return true if the User is an administrator of the group. * @return true if the User is an administrator of the group.
*/ */
public boolean isAdministrator(Entity entity); public boolean isAdministrator(User user);
/** /**
* Returns true if if the User is a member of the group. * Returns true if if the User is a member of the group.
* *
* @return true if the User is a member of the group. * @return true if the User is a member of the group.
*/ */
public boolean isMember(Entity entity); public boolean isMember(User user);
/** /**
* Returns the number of group administrators. * Returns the number of group administrators.
......
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
package org.jivesoftware.messenger.auth; package org.jivesoftware.messenger.auth;
import org.jivesoftware.util.BasicResultFilter; import org.jivesoftware.util.BasicResultFilter;
import org.jivesoftware.messenger.Entity; import org.jivesoftware.messenger.user.User;
import java.util.Iterator; import java.util.Iterator;
/** /**
...@@ -105,8 +106,8 @@ public interface GroupManager { ...@@ -105,8 +106,8 @@ public interface GroupManager {
/** /**
* Returns an iterator for all groups that a user is a member of. * Returns an iterator for all groups that a user is a member of.
* *
* @param entity the user to get a list of groups for. * @param user the user to get a list of groups for.
* @return all groups that a user belongs to. * @return all groups that a user belongs to.
*/ */
public Iterator getGroups(Entity entity); public Iterator getGroups(User user);
} }
\ No newline at end of file
...@@ -116,17 +116,17 @@ public interface GroupProvider { ...@@ -116,17 +116,17 @@ public interface GroupProvider {
* <p>Obtain an list of all Group IDs known by the provider * <p>Obtain an list of all Group IDs known by the provider
* that a given entity belongs to.</p> * that a given entity belongs to.</p>
* *
* @param entityID The ID of the entity to find groups for * @param username the username.
* @return The list of IDs of the groups that the entity belongs to * @return The list of IDs of the groups that the entity belongs to
*/ */
LongList getGroups(long entityID); LongList getGroups(String username);
/** /**
* <p>Creates a membership relationship between the * <p>Creates a membership relationship between the
* group and the entity (optional operation).</p> * group and the entity (optional operation).</p>
* *
* @param groupID The group to add the member to * @param groupID the group to add the member to
* @param entityID The entity to add * @param username the username to add
* @param administrator True if the member is an administrator of the group * @param administrator True if the member is an administrator of the group
* @throws UnauthorizedException If the password is invalid or * @throws UnauthorizedException If the password is invalid or
* the caller does not have permission to make the change * the caller does not have permission to make the change
...@@ -135,7 +135,7 @@ public interface GroupProvider { ...@@ -135,7 +135,7 @@ public interface GroupProvider {
* @throws UserAlreadyExistsException If the given entity is already a member * @throws UserAlreadyExistsException If the given entity is already a member
* of the group * of the group
*/ */
void createMember(long groupID, long entityID, boolean administrator) void createMember(long groupID, String username, boolean administrator)
throws UnauthorizedException, throws UnauthorizedException,
UserAlreadyExistsException, UserAlreadyExistsException,
UnsupportedOperationException; UnsupportedOperationException;
...@@ -145,28 +145,26 @@ public interface GroupProvider { ...@@ -145,28 +145,26 @@ public interface GroupProvider {
* group and the entity (optional operation).</p> * group and the entity (optional operation).</p>
* *
* @param groupID The group to add the member to * @param groupID The group to add the member to
* @param entityID The entity to add * @param username the username
* @param administrator True if the member is an administrator of the group * @param administrator True if the member is an administrator of the group
* @throws UnauthorizedException If the password is invalid or * @throws UnauthorizedException If the password is invalid or
* the caller does not have permission to make the change * the caller does not have permission to make the change
* @throws UnsupportedOperationException If the provider does not * @throws UnsupportedOperationException If the provider does not
* support the operation (this is an optional operation) * support the operation (this is an optional operation)
*/ */
void updateMember(long groupID, long entityID, boolean administrator) void updateMember(long groupID, String username, boolean administrator)
throws UnauthorizedException, UnsupportedOperationException; throws UnauthorizedException, UnsupportedOperationException;
/** /**
* <p>Deletes a membership relationship between the * Deletes a membership relationship between the group and the user (optional operation).
* group and the entity (optional operation).</p>
* *
* @param groupID The group to add the member to * @param groupID the group.
* @param entityID The entity to add * @param username the username.
* @throws UnauthorizedException If the password is invalid or * @throws UnauthorizedException if does not have permission to make the change.
* the caller does not have permission to make the change * @throws UnsupportedOperationException if the provider does not
* @throws UnsupportedOperationException If the provider does not * support the operation (this is an optional operation).
* support the operation (this is an optional operation)
*/ */
void deleteMember(long groupID, long entityID) void deleteMember(long groupID, String username)
throws UnauthorizedException, UnsupportedOperationException; throws UnauthorizedException, UnsupportedOperationException;
/** /**
...@@ -185,7 +183,7 @@ public interface GroupProvider { ...@@ -185,7 +183,7 @@ public interface GroupProvider {
* @param adminsOnly True if the results should be restricted to administrators only * @param adminsOnly True if the results should be restricted to administrators only
* @return The list of IDs of the entities that belongs to the group * @return The list of IDs of the entities that belongs to the group
*/ */
LongList getMembers(long groupID, boolean adminsOnly); String [] getMembers(long groupID, boolean adminsOnly);
/** /**
* <p>Obtain a list of all entity ID's of members of the given group * <p>Obtain a list of all entity ID's of members of the given group
...@@ -196,17 +194,17 @@ public interface GroupProvider { ...@@ -196,17 +194,17 @@ public interface GroupProvider {
* @param adminsOnly True if the results should be restricted to administrators only * @param adminsOnly True if the results should be restricted to administrators only
* @return The list of IDs of the entities that belongs to the group * @return The list of IDs of the entities that belongs to the group
*/ */
LongList getMembers(long groupID, BasicResultFilter filter, boolean adminsOnly); String [] getMembers(long groupID, BasicResultFilter filter, boolean adminsOnly);
/** /**
* <p>Determine if a given entity is a member of a group.</p> * <p>Determine if a given entity is a member of a group.</p>
* *
* @param groupID The ID of the group * @param groupID The ID of the group
* @param entityID The ID of the entity being checked for membership in the group * @param username the username.
* @param adminsOnly True if the entity must be an administrator of the group * @param adminsOnly True if the entity must be an administrator of the group
* @return True if the entity is a member of the group * @return True if the entity is a member of the group
*/ */
boolean isMember(long groupID, long entityID, boolean adminsOnly); boolean isMember(long groupID, String username, boolean adminsOnly);
/** /**
* <p>Creates a property on a group (optional operation).</p> * <p>Creates a property on a group (optional operation).</p>
...@@ -225,9 +223,9 @@ public interface GroupProvider { ...@@ -225,9 +223,9 @@ public interface GroupProvider {
/** /**
* <p>Updates a property on a group (optional operation).</p> * <p>Updates a property on a group (optional operation).</p>
* *
* @param groupID The ID of the group * @param groupID the ID of the group.
* @param name The name of the property * @param name the name of the property.
* @param value The value of the property * @param value the value of the property.
* @throws UnauthorizedException If the password is invalid or * @throws UnauthorizedException If the password is invalid or
* the caller does not have permission to make the change * the caller does not have permission to make the change
* @throws UnsupportedOperationException If the provider does not * @throws UnsupportedOperationException If the provider does not
...@@ -248,4 +246,4 @@ public interface GroupProvider { ...@@ -248,4 +246,4 @@ public interface GroupProvider {
*/ */
void deleteProperty(long groupID, String name) void deleteProperty(long groupID, String name)
throws UnauthorizedException, UnsupportedOperationException; throws UnauthorizedException, UnsupportedOperationException;
} }
\ No newline at end of file
...@@ -23,24 +23,24 @@ public final class AuthTokenImpl implements AuthToken, Serializable { ...@@ -23,24 +23,24 @@ public final class AuthTokenImpl implements AuthToken, Serializable {
private static final long serialVersionUID = 01L; private static final long serialVersionUID = 01L;
private long userID; private String username;
/** /**
* Constucts a new DbAuthToken with the specified userID. * Constucts a new AuthTokenImpl with the specified username.
* *
* @param userID the userID to create an authToken token with. * @param username the username to create an authToken token with.
*/ */
public AuthTokenImpl(long userID) { public AuthTokenImpl(String username) {
this.userID = userID; this.username = username;
} }
// AuthToken Interface // AuthToken Interface
public long getUserID() { public String getUsername() {
return userID; return username;
} }
public boolean isAnonymous() { public boolean isAnonymous() {
return userID == -1; return username != null;
} }
} }
\ No newline at end of file
...@@ -18,8 +18,6 @@ import org.jivesoftware.messenger.auth.AuthFactory; ...@@ -18,8 +18,6 @@ import org.jivesoftware.messenger.auth.AuthFactory;
import org.jivesoftware.messenger.auth.AuthProvider; import org.jivesoftware.messenger.auth.AuthProvider;
import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserNotFoundException; import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.spi.DbUserIDProvider;
import org.jivesoftware.database.DbConnectionManager;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
...@@ -53,21 +51,12 @@ import java.sql.SQLException; ...@@ -53,21 +51,12 @@ import java.sql.SQLException;
*/ */
public class DbAuthProvider implements AuthProvider { public class DbAuthProvider implements AuthProvider {
/**
* DATABASE QUERIES *
*/
private static final String AUTHORIZE = private static final String AUTHORIZE =
"SELECT userID FROM jiveUser WHERE userID=? AND password=?"; "SELECT username FROM jiveUser WHERE username=? AND password=?";
private static final String SELECT_PASSWORD = private static final String SELECT_PASSWORD =
"SELECT password FROM jiveUser WHERE userID=?"; "SELECT password FROM jiveUser WHERE username=?";
private static final String UPDATE_PASSWORD = private static final String UPDATE_PASSWORD =
"UPDATE jiveUser set password=? WHERE userID=?"; "UPDATE jiveUser set password=? WHERE username=?";
/**
* <p>Used to map usernames to ids.</p>
*/
private DbUserIDProvider idProvider = new DbUserIDProvider();
/** /**
* <p>Implementation requires the password to be stored in the user table in plain text.</p> * <p>Implementation requires the password to be stored in the user table in plain text.</p>
...@@ -84,14 +73,12 @@ public class DbAuthProvider implements AuthProvider { ...@@ -84,14 +73,12 @@ public class DbAuthProvider implements AuthProvider {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
username = NodePrep.prep(username); username = NodePrep.prep(username);
long userID = 0;
Connection con = null; Connection con = null;
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try { try {
userID = idProvider.getUserID(username);
con = DbConnectionManager.getConnection(); con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(AUTHORIZE); pstmt = con.prepareStatement(AUTHORIZE);
pstmt.setLong(1, userID); pstmt.setString(1, username);
pstmt.setString(2, password); pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
...@@ -101,14 +88,12 @@ public class DbAuthProvider implements AuthProvider { ...@@ -101,14 +88,12 @@ public class DbAuthProvider implements AuthProvider {
if (!rs.next()) { if (!rs.next()) {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
rs.close();
} }
catch (SQLException e) { catch (SQLException e) {
Log.error("Exception in DbAuthProvider", e); Log.error("Exception in DbAuthProvider", e);
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
catch (UserNotFoundException e) {
throw new UnauthorizedException();
}
finally { finally {
try { if (pstmt != null) pstmt.close(); } try { if (pstmt != null) pstmt.close(); }
catch (Exception e) { Log.error(e); } catch (Exception e) { Log.error(e); }
...@@ -135,14 +120,12 @@ public class DbAuthProvider implements AuthProvider { ...@@ -135,14 +120,12 @@ public class DbAuthProvider implements AuthProvider {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
username = NodePrep.prep(username); username = NodePrep.prep(username);
long userID = 0;
Connection con = null; Connection con = null;
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try { try {
userID = idProvider.getUserID(username);
con = DbConnectionManager.getConnection(); con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(SELECT_PASSWORD); pstmt = con.prepareStatement(SELECT_PASSWORD);
pstmt.setLong(1, userID); pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
...@@ -156,27 +139,17 @@ public class DbAuthProvider implements AuthProvider { ...@@ -156,27 +139,17 @@ public class DbAuthProvider implements AuthProvider {
if (!digest.equalsIgnoreCase(anticipatedDigest)) { if (!digest.equalsIgnoreCase(anticipatedDigest)) {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
rs.close();
} }
catch (SQLException e) { catch (SQLException e) {
Log.error("Exception in DbAuthProvider", e); Log.error("Exception in DbAuthProvider", e);
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
catch (UserNotFoundException e) {
throw new UnauthorizedException();
}
finally { finally {
try { try { if (pstmt != null) pstmt.close(); }
if (pstmt != null) pstmt.close(); catch (Exception e) { Log.error(e); }
} try { if (con != null) con.close(); }
catch (Exception e) { catch (Exception e) { Log.error(e); }
Log.error(e);
}
try {
if (con != null) con.close();
}
catch (Exception e) {
Log.error(e);
}
} }
// Got this far, so the user must be authorized. // Got this far, so the user must be authorized.
} }
...@@ -195,16 +168,13 @@ public class DbAuthProvider implements AuthProvider { ...@@ -195,16 +168,13 @@ public class DbAuthProvider implements AuthProvider {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
username = NodePrep.prep(username); username = NodePrep.prep(username);
long userID = 0;
Connection con = null; Connection con = null;
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try { try {
userID = idProvider.getUserID(username);
con = DbConnectionManager.getConnection(); con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(UPDATE_PASSWORD); pstmt = con.prepareStatement(UPDATE_PASSWORD);
pstmt.setString(1, password); pstmt.setString(1, password);
pstmt.setLong(2, userID); pstmt.setString(2, username);
pstmt.executeUpdate(); pstmt.executeUpdate();
} }
catch (SQLException e) { catch (SQLException e) {
...@@ -212,18 +182,10 @@ public class DbAuthProvider implements AuthProvider { ...@@ -212,18 +182,10 @@ public class DbAuthProvider implements AuthProvider {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
finally { finally {
try { try { if (pstmt != null) pstmt.close(); }
if (pstmt != null) pstmt.close(); catch (Exception e) { Log.error(e); }
} try { if (con != null) con.close(); }
catch (Exception e) { catch (Exception e) { Log.error(e); }
Log.error(e);
}
try {
if (con != null) con.close();
}
catch (Exception e) {
Log.error(e);
}
} }
} }
......
...@@ -15,9 +15,9 @@ import org.jivesoftware.util.CacheManager; ...@@ -15,9 +15,9 @@ import org.jivesoftware.util.CacheManager;
import org.jivesoftware.util.CacheSizes; import org.jivesoftware.util.CacheSizes;
import org.jivesoftware.util.Cache; import org.jivesoftware.util.Cache;
import org.jivesoftware.util.*; import org.jivesoftware.util.*;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.*; import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.UserAlreadyExistsException; import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.spi.UserIterator; import org.jivesoftware.messenger.user.spi.UserIterator;
import java.util.*; import java.util.*;
...@@ -39,8 +39,8 @@ public class GroupImpl implements Group, Cacheable { ...@@ -39,8 +39,8 @@ public class GroupImpl implements Group, Cacheable {
private Date creationDate; private Date creationDate;
private Date modificationDate; private Date modificationDate;
private Map properties; private Map properties;
private long[] memberList; private String[] memberList;
private long[] adminList; private String[] adminList;
private Cache groupCache; private Cache groupCache;
private Cache groupMemberCache; private Cache groupMemberCache;
...@@ -53,11 +53,9 @@ public class GroupImpl implements Group, Cacheable { ...@@ -53,11 +53,9 @@ public class GroupImpl implements Group, Cacheable {
* @param created The date-time the group was created * @param created The date-time the group was created
* @param modified The date-time the group was last modified * @param modified The date-time the group was last modified
*/ */
GroupImpl(long id, GroupImpl(long id, String groupName, String groupDescription, Date created,
String groupName, Date modified)
String groupDescription, {
Date created,
Date modified) {
groupID = id; groupID = id;
name = groupName; name = groupName;
description = groupDescription; description = groupDescription;
...@@ -181,16 +179,15 @@ public class GroupImpl implements Group, Cacheable { ...@@ -181,16 +179,15 @@ public class GroupImpl implements Group, Cacheable {
return Collections.unmodifiableSet(properties.keySet()).iterator(); return Collections.unmodifiableSet(properties.keySet()).iterator();
} }
public void addAdministrator(Entity entity) public void addAdministrator(User user)
throws UnauthorizedException, UserAlreadyExistsException { throws UnauthorizedException, UserAlreadyExistsException {
// If the user is already an administrator, do nothing. // If the user is already an administrator, do nothing.
if (isAdministrator(entity)) { if (isAdministrator(user)) {
throw new UserAlreadyExistsException("User " + entity.getUsername() + "with ID " + entity.getID() + throw new UserAlreadyExistsException("User " + user.getUsername() +
" already is a member of the group"); " already is a member of the group");
} }
String username = user.getUsername();
long userID = entity.getID(); provider.createMember(groupID, username, true);
provider.createMember(groupID, userID, true);
try { try {
provider.updateGroup(this); provider.updateGroup(this);
} }
...@@ -201,22 +198,22 @@ public class GroupImpl implements Group, Cacheable { ...@@ -201,22 +198,22 @@ public class GroupImpl implements Group, Cacheable {
// Changed admins, so reset admin list // Changed admins, so reset admin list
adminList = null; adminList = null;
groupCache.put(new Long(groupID), this); groupCache.put(new Long(groupID), this);
groupMemberCache.put(groupID + ",admin," + entity.getID(), Boolean.TRUE); groupMemberCache.put(groupID + ",admin," + username, Boolean.TRUE);
// Now, clear the permissions cache. // Now, clear the permissions cache.
// This is handled via a listener for the GroupEvent.GROUP_ADMINISTRATOR_ADD event // This is handled via a listener for the GroupEvent.GROUP_ADMINISTRATOR_ADD event
// fire off an event // fire off an event
Map params = new HashMap(); Map params = new HashMap();
params.put("Administrator", entity); params.put("Administrator", user);
} }
public void removeAdministrator(Entity entity) throws UnauthorizedException { public void removeAdministrator(User user) throws UnauthorizedException {
// If the user is not an administrator, do nothing. // If the user is not an administrator, do nothing.
if (isAdministrator(entity)) { if (isAdministrator(user)) {
long userID = entity.getID(); String username = user.getUsername();
provider.deleteMember(groupID, userID); provider.deleteMember(groupID, username);
try { try {
provider.updateGroup(this); provider.updateGroup(this);
} }
...@@ -229,23 +226,23 @@ public class GroupImpl implements Group, Cacheable { ...@@ -229,23 +226,23 @@ public class GroupImpl implements Group, Cacheable {
groupCache.put(new Long(groupID), this); groupCache.put(new Long(groupID), this);
// Remove user from admin cache // Remove user from admin cache
groupMemberCache.remove(groupID + ",admin," + userID); groupMemberCache.remove(groupID + ",admin," + username);
// Now, clear the permissions cache. // Now, clear the permissions cache.
// This is handled via a listener for the GroupEvent.GROUP_ADMINISTRATOR_DELETE event // This is handled via a listener for the GroupEvent.GROUP_ADMINISTRATOR_DELETE event
} }
} }
public void addMember(Entity entity) public void addMember(User user)
throws UnauthorizedException, UserAlreadyExistsException { throws UnauthorizedException, UserAlreadyExistsException {
// Don't do anything if the user is already a member of the group. // Don't do anything if the user is already a member of the group.
if (isMember(entity)) { if (isMember(user)) {
throw new UserAlreadyExistsException("User " + entity.getUsername() + "with ID " + entity.getID() + throw new UserAlreadyExistsException("User " + user.getUsername() +
" already is a member of the group"); " is already a member of the group");
} }
String username = user.getUsername();
long userID = entity.getID(); provider.createMember(groupID, username, false);
provider.createMember(groupID, userID, false);
try { try {
provider.updateGroup(this); provider.updateGroup(this);
} }
...@@ -258,59 +255,59 @@ public class GroupImpl implements Group, Cacheable { ...@@ -258,59 +255,59 @@ public class GroupImpl implements Group, Cacheable {
groupCache.put(new Long(groupID), this); groupCache.put(new Long(groupID), this);
// Remove user from member cache // Remove user from member cache
groupMemberCache.remove(groupID + ",member," + userID); groupMemberCache.remove(groupID + ",member," + username);
// Remove the user's entry for groups they belong in. // Remove the user's entry for groups they belong in.
groupMemberCache.remove("userGroups-" + userID); groupMemberCache.remove("userGroups-" + username);
// Now, clear the permissions cache. // Now, clear the permissions cache.
// This is handled via a listener for the GroupEvent.GROUP_USER_ADD event // This is handled via a listener for the GroupEvent.GROUP_USER_ADD event
} }
public void removeMember(Entity entity) throws UnauthorizedException { public void removeMember(User user) throws UnauthorizedException {
// Don't do anything if the user isn't a member of the group. // Don't do anything if the user isn't a member of the group.
if (!isMember(entity)) { if (!isMember(user)) {
return; return;
} }
long userID = entity.getID(); String username = user.getUsername();
provider.deleteMember(groupID, userID); provider.deleteMember(groupID, username);
// Changed membership, so reset member list // Changed membership, so reset member list
memberList = null; memberList = null;
groupCache.put(new Long(groupID), this); groupCache.put(new Long(groupID), this);
// Remove user from member cache // Remove user from member cache
groupMemberCache.remove(groupID + ",member," + userID); groupMemberCache.remove(groupID + ",member," + username);
// Remove the user's entry for groups they belong in. // Remove the user's entry for groups they belong in.
groupMemberCache.remove("userGroups-" + userID); groupMemberCache.remove("userGroups-" + username);
// Now, clear the permissions cache. // Now, clear the permissions cache.
// This is handled via a listener for the GroupEvent.GROUP_USER_DELETE event // This is handled via a listener for the GroupEvent.GROUP_USER_DELETE event
} }
public boolean isAdministrator(Entity entity) { public boolean isAdministrator(User user) {
long userID = entity.getID(); String username = user.getUsername();
Boolean bool = null; Boolean bool = null;
bool = (Boolean)groupMemberCache.get(groupID + ",admin," + userID); bool = (Boolean)groupMemberCache.get(groupID + ",admin," + username);
if (bool == null) { if (bool == null) {
bool = new Boolean(provider.isMember(groupID, userID, true)); bool = new Boolean(provider.isMember(groupID, username, true));
// Add to cache // Add to cache
groupMemberCache.put(groupID + ",admin," + userID, bool); groupMemberCache.put(groupID + ",admin," + username, bool);
} }
return bool.booleanValue(); return bool.booleanValue();
} }
public boolean isMember(Entity entity) { public boolean isMember(User user) {
long userID = entity.getID(); String username = user.getUsername();
Boolean bool = null; Boolean bool = null;
bool = (Boolean)groupMemberCache.get(groupID + ",member," + userID); bool = (Boolean)groupMemberCache.get(groupID + ",member," + username);
if (bool == null) { if (bool == null) {
bool = new Boolean(provider.isMember(groupID, userID, false)); bool = new Boolean(provider.isMember(groupID, username, false));
// Add to cache // Add to cache
groupMemberCache.put(groupID + ",member," + userID, bool); groupMemberCache.put(groupID + ",member," + username, bool);
} }
return bool.booleanValue(); return bool.booleanValue();
} }
...@@ -333,7 +330,7 @@ public class GroupImpl implements Group, Cacheable { ...@@ -333,7 +330,7 @@ public class GroupImpl implements Group, Cacheable {
public Iterator members() { public Iterator members() {
if (memberList == null) { if (memberList == null) {
memberList = provider.getMembers(groupID, false).toArray(); memberList = provider.getMembers(groupID, false);
// Re-add group to cache. // Re-add group to cache.
groupCache.put(new Long(groupID), this); groupCache.put(new Long(groupID), this);
} }
...@@ -349,7 +346,7 @@ public class GroupImpl implements Group, Cacheable { ...@@ -349,7 +346,7 @@ public class GroupImpl implements Group, Cacheable {
public Iterator administrators() { public Iterator administrators() {
if (adminList == null) { if (adminList == null) {
adminList = provider.getMembers(groupID, true).toArray(); adminList = provider.getMembers(groupID, true);
// Re-add group to cache. // Re-add group to cache.
groupCache.put(new Long(groupID), this); groupCache.put(new Long(groupID), this);
} }
...@@ -364,15 +361,15 @@ public class GroupImpl implements Group, Cacheable { ...@@ -364,15 +361,15 @@ public class GroupImpl implements Group, Cacheable {
} }
public Permissions getPermissions(AuthToken auth) { public Permissions getPermissions(AuthToken auth) {
long userID = auth.getUserID(); String username = auth.getUsername();
try { try {
Boolean bool = null; Boolean bool = null;
bool = (Boolean)groupMemberCache.get(groupID + ",admin," + userID); bool = (Boolean)groupMemberCache.get(groupID + ",admin," + username);
if (bool == null) { if (bool == null) {
bool = new Boolean(provider.isMember(groupID, userID, true)); bool = new Boolean(provider.isMember(groupID, username, true));
// Add to cache // Add to cache
groupMemberCache.put(groupID + ",admin," + userID, bool); groupMemberCache.put(groupID + ",admin," + username, bool);
} }
if (bool.booleanValue()) { if (bool.booleanValue()) {
......
...@@ -16,7 +16,6 @@ import org.jivesoftware.messenger.container.BasicModule; ...@@ -16,7 +16,6 @@ import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.messenger.container.Container; import org.jivesoftware.messenger.container.Container;
import org.jivesoftware.util.Cache; import org.jivesoftware.util.Cache;
import org.jivesoftware.util.*; import org.jivesoftware.util.*;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.*; import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.User; import org.jivesoftware.messenger.user.User;
import java.util.Iterator; import java.util.Iterator;
...@@ -87,12 +86,12 @@ public class GroupManagerImpl extends BasicModule implements GroupManager { ...@@ -87,12 +86,12 @@ public class GroupManagerImpl extends BasicModule implements GroupManager {
public void deleteGroup(Group group) throws UnauthorizedException { public void deleteGroup(Group group) throws UnauthorizedException {
long groupID = group.getID(); long groupID = group.getID();
long[] members = new long[group.getMemberCount()]; String[] members = new String[group.getMemberCount()];
Iterator iter = group.members(); Iterator iter = group.members();
for (int i = 0; i < members.length; i++) { for (int i = 0; i < members.length; i++) {
User user = (User)iter.next(); User user = (User)iter.next();
members[i] = user.getID(); members[i] = user.getUsername();
} }
provider.deleteGroup(group.getID()); provider.deleteGroup(group.getID());
...@@ -122,14 +121,14 @@ public class GroupManagerImpl extends BasicModule implements GroupManager { ...@@ -122,14 +121,14 @@ public class GroupManagerImpl extends BasicModule implements GroupManager {
return new GroupIterator(this, groups.toArray()); return new GroupIterator(this, groups.toArray());
} }
public Iterator getGroups(Entity entity) { public Iterator getGroups(User user) {
long userID = entity.getID(); String username = user.getUsername();
String key = "userGroups-" + userID; String key = "userGroups-" + username;
// Look in the group membership cache for the value. // Look in the group membership cache for the value.
long[] groups = (long[])groupMemberCache.get(key); long[] groups = (long[])groupMemberCache.get(key);
if (groups == null) { if (groups == null) {
groups = provider.getGroups(entity.getID()).toArray(); groups = provider.getGroups(username).toArray();
} }
return new GroupIterator(this, groups); return new GroupIterator(this, groups);
} }
......
...@@ -13,9 +13,10 @@ package org.jivesoftware.messenger.auth.spi; ...@@ -13,9 +13,10 @@ package org.jivesoftware.messenger.auth.spi;
import org.jivesoftware.util.BasicResultFilter; import org.jivesoftware.util.BasicResultFilter;
import org.jivesoftware.util.JiveConstants; import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.*; import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.spi.UserGroupIteratorProxy; import org.jivesoftware.messenger.user.spi.UserGroupIteratorProxy;
import org.jivesoftware.messenger.user.User;
import java.util.Iterator; import java.util.Iterator;
/** /**
...@@ -90,8 +91,8 @@ public class GroupManagerProxy implements GroupManager { ...@@ -90,8 +91,8 @@ public class GroupManagerProxy implements GroupManager {
return new UserGroupIteratorProxy(JiveConstants.GROUP, iterator, auth, permissions); return new UserGroupIteratorProxy(JiveConstants.GROUP, iterator, auth, permissions);
} }
public Iterator getGroups(Entity entity) { public Iterator getGroups(User user) {
Iterator iterator = groupManager.getGroups(entity); Iterator iterator = groupManager.getGroups(user);
return new UserGroupIteratorProxy(JiveConstants.GROUP, iterator, auth, permissions); return new UserGroupIteratorProxy(JiveConstants.GROUP, iterator, auth, permissions);
} }
} }
...@@ -11,12 +11,12 @@ ...@@ -11,12 +11,12 @@
package org.jivesoftware.messenger.auth.spi; package org.jivesoftware.messenger.auth.spi;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.AuthToken; import org.jivesoftware.messenger.auth.AuthToken;
import org.jivesoftware.messenger.auth.Group; import org.jivesoftware.messenger.auth.Group;
import org.jivesoftware.messenger.auth.Permissions; import org.jivesoftware.messenger.auth.Permissions;
import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserAlreadyExistsException; import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.spi.UserIteratorProxy; import org.jivesoftware.messenger.user.spi.UserIteratorProxy;
import java.util.Date; import java.util.Date;
import java.util.Iterator; import java.util.Iterator;
...@@ -126,54 +126,54 @@ public class GroupProxy implements Group { ...@@ -126,54 +126,54 @@ public class GroupProxy implements Group {
return group.getPropertyNames(); return group.getPropertyNames();
} }
public void addAdministrator(Entity entity) public void addAdministrator(User user)
throws UnauthorizedException, UserAlreadyExistsException { throws UnauthorizedException, UserAlreadyExistsException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) { | Permissions.GROUP_ADMIN)) {
group.addAdministrator(entity); group.addAdministrator(user);
} }
else { else {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
} }
public void removeAdministrator(Entity entity) throws UnauthorizedException { public void removeAdministrator(User user) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) { | Permissions.GROUP_ADMIN)) {
group.removeAdministrator(entity); group.removeAdministrator(user);
} }
else { else {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
} }
public void addMember(Entity entity) public void addMember(User user)
throws UnauthorizedException, UserAlreadyExistsException { throws UnauthorizedException, UserAlreadyExistsException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) { | Permissions.GROUP_ADMIN)) {
group.addMember(entity); group.addMember(user);
} }
else { else {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
} }
public void removeMember(Entity entity) throws UnauthorizedException { public void removeMember(User user) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) { | Permissions.GROUP_ADMIN)) {
group.removeMember(entity); group.removeMember(user);
} }
else { else {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
} }
public boolean isAdministrator(Entity entity) { public boolean isAdministrator(User user) {
return group.isAdministrator(entity); return group.isAdministrator(user);
} }
public boolean isMember(Entity entity) { public boolean isMember(User user) {
return group.isMember(entity); return group.isMember(user);
} }
public int getAdministratorCount() { public int getAdministratorCount() {
...@@ -199,4 +199,4 @@ public class GroupProxy implements Group { ...@@ -199,4 +199,4 @@ public class GroupProxy implements Group {
public boolean isAuthorized(long type) { public boolean isAuthorized(long type) {
return permissions.hasPermission(type); return permissions.hasPermission(type);
} }
} }
\ No newline at end of file
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.ChannelHandler;
/**
* <p>Represents any server-side plug-in that act as a user on the system.</p>
* <p/>
* <p>As a normal user on the system, chatbots have all the account resources of a
* user but no need to authenticate. They must have unique chatbot IDs that do not
* clash with user IDs since chatbots and users share the same resources (e.g.
* private storage) and are unique identified to these resources by ID.</p>
*
* @author Iain Shigeoka
*/
public interface Chatbot extends Entity, ChannelHandler {
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
/**
* <p>Defines the provider methods required for creating and deleting chatbot username reservations.</p>
* <p/>
* <p>Creating and deleting chatbot username reservations can be complex and highly dependent on a provider's
* unique mix of custom and Jive providers. Implementing this interfaces provides the
* opportunity to customize the behavior of Messenger when creating and deleting
* chatbot username reservations.</p>
*
* @author Iain Shigeoka
*/
public interface ChatbotAccountProvider {
/**
* <p>Called to create a new chatbot username reservations (optional operation).</p>
* <p/>
* <p>After a call to this method is made, all other provider methods should be valid.
* For example, if your user info provider only uses JDBC updates, then this method
* must insert the initial user info so the updates will occur normally. See the
* documentation for the providers you are using to determine what needs to be done
* to satisfy their setup needs. In particular, if you are using Jive default providers,
* you should examine the jive default UserAccountProvider implementation to make sure
* you have setup the jive tables you will be using properly.</p>
*
* @param username The username for the user to be created
* @return The user ID for the new user
* @throws org.jivesoftware.messenger.auth.UnauthorizedException
* If users can't be created because of caller permissions (no new account created)
* @throws org.jivesoftware.messenger.user.UserAlreadyExistsException
* If the user already exists (no new account created)
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
long createChatbot(String username)
throws UnauthorizedException, UserAlreadyExistsException, UnsupportedOperationException;
/**
* <p>Called to delete an existing chatbot username reservations (optional operation).</p>
* <p/>
* <p>Use this method to remove a user from the system and clean up any resources
* devoted to that user. If a user account for the id doesn't exist, the method should return
* without any exceptions.</p>
*
* @param id The user ID for the user to delete
* @throws UnauthorizedException If users can't be deleted with this provider (no accounts affected)
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
void deleteChatbot(long id) throws UnauthorizedException, UnsupportedOperationException;
}
\ No newline at end of file
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot;
import org.jivesoftware.util.LongList;
import org.jivesoftware.messenger.user.UserNotFoundException;
/**
* <p>The essential interface to implement when creating a chatbot management service plug-in.</p>
* <p/>
* <p>All Messenger systems dealing with a user are keyed on a long user ID value. However, external
* systems and XMPP addressing must be able to map between user IDs and usernames and back again.
* The default provider of the user ID provider maintains a simple table of the username and it's
* corresponding long ID. If you replace the default authentication system, you will need to make sure
* to create your own UserIDProvider to correctly maintain a mapping between user names and IDs.
* Alternatively, you can simply update the Jive default userID table when the information changes
* in your other backend systems.</p>
* <p/>
* <p>Messenger will cache much of the information it obtains from calling this provider. If you will be modifying
* the underlying data outside of Messenger, please consult with Jive for information on maintaining a valid
* cache.</p>
*
* @author Iain Shigeoka
*/
public interface ChatbotIDProvider {
/**
* <p>Obtain the user's username from their ID.</p>
*
* @param id The id of the user
* @return The user's username
* @throws UserNotFoundException If a user with the given ID couldn't be found
*/
String getUsername(long id) throws UserNotFoundException;
/**
* <p>Obtain the user's username from their ID.</p>
*
* @param username The user's username
* @return The ID for the user
* @throws UserNotFoundException If a user with the given ID couldn't be found
*/
long getChatbotID(String username) throws UserNotFoundException;
/**
* <p>Obtain the total number of users on the system.</p>
* <p/>
* <p>If the provider doesn't support user listings, return a 0 (zero).</p>
*
* @return The number of users on the system
*/
int getChatbotCount();
/**
* <p>Obtain a list all user IDs on the system.</p>
* <p>If the provider doesn't support user listings, return an empty list.</p>
*
* @return The number of users on the system
*/
LongList getChatbotIDs();
/**
* <p>Obtain a restricted list all user IDs on the system.</p>
* <p/>
* <p>Assuming your system has a natural listing of users, this
* interface will be used to present users in pages rather than
* loading all the users on a single. In large user databases
* this method may be critical to reducing the amount of memory
* this call consumes.</p>
* <p>If the provider doesn't support user listings, return an empty list.</p>
*
* @param startIndex The number of users to skip before
* @param numResults The number of users to include in the list
* @return The number of users on the system
*/
LongList getChatbotIDs(int startIndex, int numResults);
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import java.util.Date;
/**
* <p>The ChatbotInfo interface provides information about and services for users of the system.</p>
* <p/>
* <p>The name and email field will normally be required fields when creating user accounts for most
* implementations. However, some users may wish to keep that information private. Therefore, there
* are two flags to set if the name and email fields should be made visible to other users. If
* the flags are set to deny access, getName() and getEmail() will throw UnauthorizedExceptions to
* users that don't have administrator permissions.</p>
* <p/>
* <p>Security for UserInfo objects is provide by UserInfoProxy protection proxy objects.</p>
*
* @author Iain Shigeoka
*/
public interface ChatbotInfo {
/**
* <p>Obtain the long ID of the user that owns this info.</p>
*
* @return The ID of the user that owns this info
*/
long getId();
/**
* Returns the user's description.
*
* @return the name of the user.
*/
String getDescription();
/**
* Sets the user's description.
*
* @param description new description for the user.
* @throws UnauthorizedException if does not have administrator permissions.
*/
void setDescription(String description) throws UnauthorizedException;
/**
* Returns the date that the user was created.
*
* @return the date the user was created.
*/
Date getCreationDate();
/**
* Sets the creation date of the user. In most cases, the creation date will default to when the
* user was entered into the system. However, the date needs to be set manually when importing
* data. In other words, skin authors should ignore this method since it only intended for
* system maintenance.
*
* @param creationDate the date the user was created.
* @throws UnauthorizedException if does not have administrator permissions.
*/
void setCreationDate(Date creationDate) throws UnauthorizedException;
/**
* Returns the date that the user was last modified.
*
* @return the date the user record was last modified.
*/
Date getModificationDate();
/**
* Sets the date the user was last modified. Skin authors should ignore this method since it
* only intended for system maintenance.
*
* @param modificationDate the date the user was modified.
* @throws UnauthorizedException if does not have administrator permissions.
*/
void setModificationDate(Date modificationDate) throws UnauthorizedException;
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserNotFoundException;
/**
* <p>A common interface to implement when creating a user management service plug-in.</p>
* <p/>
* <p>Provide meta-information about a user that's useful in server behavior. Implementation
* of this provider is optional and systems where user information is stored and managed in
* other systems may want to provide partial implementations or use the Jive dummy implementation
* that returns no values.</p>
* <p/>
* <p>Messenger will cache much of the information it obtains from calling this provider. If you will be modifying
* the underlying data outside of Messenger, please consult with Jive for information on maintaining a valid
* cache.</p>
*
* @author Iain Shigeoka
*/
public interface ChatbotInfoProvider {
/**
* <p>Obtain the UserInfo of a user.</p>
* <p>If your implementation doesn't support user info, simply return a UserInfo object filled with default
* values.</p>
*
* @param id The id of the user
* @return The user's info
* @throws org.jivesoftware.messenger.user.UserNotFoundException
* If a user with the given ID couldn't be found
*/
ChatbotInfo getInfo(long id) throws UserNotFoundException;
/**
* <p>Sets the user's info (optional operation).</p>
*
* @param id The ID of the user
* @param info The user's new info
* @throws UserNotFoundException If a user with the given ID couldn't be found
* @throws org.jivesoftware.messenger.auth.UnauthorizedException
* If this operation is not allowed for the caller's permissions
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
void updateInfo(long id, ChatbotInfo info)
throws UserNotFoundException, UnauthorizedException, UnsupportedOperationException;
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot;
import org.jivesoftware.util.LongList;
import org.jivesoftware.messenger.XMPPAddress;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.UserNotFoundException;
/**
* <p>Manages chatbots on the server.</p>
* <p/>
* <p>Chatbots are now first class user entities without some/all of the standard user resoucres.
* The chatbot manager acts like the user manager to organize chatbot activities. Note that
* Chatbot management only pertains to a chatbot's persistent resources such as private storage,
* username reservation (ensuring a unique username and userID on the server), etc. Creating a
* chatbot does not automatically make them available for routing (does not register entries in
* the routing table), does not automatically store offline messages, etc. It is up to the chatbot
* service to act as the active entity in the server (by registering with the routing table and
* correctly handling packets).</p>
*
* @author Iain Shigeoka
*/
public interface ChatbotManager {
/**
* <p>Factory method for creating a new Chatbot by reserving a username and ID for the chatbot (optional operation).</p>
* <p/>
* <p>Although specific chatbot services MUST reserve chatbot names through this method,
* it is also useful for admins to reserve certain usernames as chatbots without
* creating a chatbot to act on behalf of that name. This prevents
* anyone from creating user accounts with the given username. (Creating 'dummy' accounts
* for this purpose creates the potential potential that the dummy account can be logged
* into and used. In addition usernames reserved for chatbots will not show up in user
* reports and statistics).
* For example, swear/racist/slang words, company trademark names, names that imply
* associations with the company, etc. should all be reserved as unused chatbot names.</p>
*
* @param username the new and unique username to reserve for a chatbot.
* @return the chatbot ID reserved for that name.
* @throws UserAlreadyExistsException if the username already exists in the system.
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public long createChatbot(String username)
throws UserAlreadyExistsException, UnauthorizedException, UnsupportedOperationException;
/**
* <p>Deletes a Chatbot username reservation (optional operation).</p>
* <p>Note: it is dangerous to delete username reservations for chatbots you did not create
* through this interface. E.g. if you created chatbots strictly to reserve their names,
* then it's ok to delete them, but if a chatbot name was reserved for a Live Assistant
* workgroup chatbot by the Live Assistante WorkgroupManager and it is deleted outside of
* the WorkgroupManager, another user or chatbot could 'steal' its username.</p>
*
* @param chatbotID the ID of the Chatbot to delete.
* @throws UnauthorizedException
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public void deleteChatbot(long chatbotID) throws UnauthorizedException, UserNotFoundException, UnsupportedOperationException;
/**
* Returns a Chatbot specified by their ID.
*
* @param chatbotID the id of the Chatbot to lookup.
* @return the Chatbot's username.
* @throws UserNotFoundException if the Chatbot does not exist.
*/
public String getChatbotUsername(long chatbotID) throws UserNotFoundException;
/**
* Returns the ChatbotID specified by the username.
*
* @param username the username of the user.
* @return the ChatbotID that matches username.
* <p/>
*
* @throws UserNotFoundException if the Chatbot does not exist.
*/
public long getChatbotID(String username) throws UserNotFoundException;
/**
* <p>Determines if the given address is a chatbot on the server.</p>
*
* @param address The address to check for chatbot-ness
* @return True if the address corresponds to a chatbot on the server
*/
boolean isChatbot(XMPPAddress address);
/**
* <p>Obtain supplemental information about a chatbot (optional operation).</p>
* <p/>
* <p>Primarily for use in admin interfaces.</p>
*
* @param chatbotID The id of the chatbot to obtain information
* @return An information object about the chatbot
* @throws UserNotFoundException
* @throws UnsupportedOperationException
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*
*/
public ChatbotInfo getChatbotInfo(long chatbotID) throws UserNotFoundException, UnsupportedOperationException;
/**
* <p>Sets supplemental information about a chatbot (optional operation).</p>
* <p/>
* <p>Primarily for use in admin interfaces.</p>
*
* @param chatbotID The id of the chatbot to obtain information
* @param info An information object about the chatbot
* @throws UserNotFoundException
* @throws UnsupportedOperationException
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public void setChatbotInfo(long chatbotID, ChatbotInfo info) throws UserNotFoundException, UnsupportedOperationException, UnauthorizedException;
/**
* Returns the number of Chatbots in the system.
*
* @return the total number of Chatbots.
*/
public int getChatbotCount();
/**
* Returns a list of the IDs of all Chatbots in the system.
*
* @return a list of all chat IDs (longs) in the system
*/
public LongList chatbots();
/**
* Returns an list of all the IDs of all Chatbots starting at <tt>startIndex</tt> with the given number of
* results. This is useful to support pagination in a GUI where you may only want to display a
* certain number of results per page. It is possible that the number of results returned will
* be less than that specified by numResults if numResults is greater than the number of records
* left in the system to display.
*
* @param startIndex the beginning index to start the results at.
* @param numResults the total number of results to return.
* @return a list of all chat IDs (longs) in the system
*/
public LongList chatbots(int startIndex, int numResults);
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot;
import org.jivesoftware.messenger.chatbot.spi.DbChatbotAccountProvider;
import org.jivesoftware.messenger.chatbot.spi.DbChatbotIDProvider;
import org.jivesoftware.messenger.chatbot.spi.DbChatbotInfoProvider;
public class ChatbotProviderFactory {
private static ChatbotIDProvider idProvider = new DbChatbotIDProvider();
private static ChatbotAccountProvider accountProvider = new DbChatbotAccountProvider();
private static ChatbotInfoProvider infoProvider = new DbChatbotInfoProvider();
public static ChatbotIDProvider getChatbotIDProvider() {
return idProvider;
}
public static ChatbotAccountProvider getChatbotAccountProvider() {
return accountProvider;
}
public static ChatbotInfoProvider getChatbotInfoProvider() {
return infoProvider;
}
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot.spi;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotInfo;
import java.util.Date;
public class BasicChatbotInfo implements ChatbotInfo {
private long id;
private String description;
private Date creationDate;
private Date modificationDate;
public BasicChatbotInfo(long id) {
this.id = id;
description = "None";
creationDate = new Date();
modificationDate = creationDate;
}
public BasicChatbotInfo(long id,
String description,
Date creationDate,
Date modificationDate) {
this.id = id;
this.description = description;
this.creationDate = creationDate;
this.modificationDate = modificationDate;
}
public long getId() {
return id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) throws UnauthorizedException {
modificationDate = new Date();
this.description = description;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) throws UnauthorizedException {
modificationDate = new Date();
this.creationDate = creationDate;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) throws UnauthorizedException {
this.modificationDate = modificationDate;
}
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot.spi;
import org.jivesoftware.database.DatabaseObjectFactory;
import org.jivesoftware.messenger.chatbot.ChatbotManager;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An class that defines the logic to iterate through an array of long unique ID's of Jive objects.
* <p/>
* <p/>
* One feature of the class is the ability to recover from underlying modifications to the dataset
* in some cases. Consider the following sequence of events:
* <ul>
* <li> Time 00: An Iterator for users in a group is obtained.
* <li> Time 01: 3 of the 8 users in the group are deleted.
* <li> Time 02: Iteration of users begins.
* </ul>
* <p/>
* In the above example, the underlying users in the group were changed after the initial
* iterator was obtained. The logic in this class will attempt to automatically compensate for
* these changes by skipping over items that cannot be loaded. In the above example, that would
* translate to the iterator returning 5 users instead of 8.
*
* @author Iain Shigeoka
*/
public class ChatbotIterator implements Iterator {
// TODO: copy of user iterator, refactor to share common base class
private long[] elements;
private int currentIndex = -1;
private Object nextElement = null;
private DatabaseObjectFactory objectFactory;
/**
* Creates a new UserIterator.
*/
public ChatbotIterator(ChatbotManager chatbotManager, long[] elements) {
this.elements = elements;
// Create an objectFactory to load users.
this.objectFactory = new ChatbotDOFactory(chatbotManager);
}
private class ChatbotDOFactory implements DatabaseObjectFactory {
private ChatbotManager manager;
public ChatbotDOFactory(ChatbotManager manager) {
this.manager = manager;
}
public Object loadObject(long id) {
/*
try {
Chatbot user = manager.getChatbotUsername(id);
return user;
}
catch (UserNotFoundException e) {
// ignore
}
*/
return null;
}
}
/**
* Returns true if there are more elements in the iteration.
*
* @return true if the iterator has more elements.
*/
public boolean hasNext() {
// If we are at the end of the list, there can't be any more elements
// to iterate through.
if (currentIndex + 1 >= elements.length && nextElement == null) {
return false;
}
// Otherwise, see if nextElement is null. If so, try to load the next
// element to make sure it exists.
if (nextElement == null) {
nextElement = getNextElement();
if (nextElement == null) {
return false;
}
}
return true;
}
/**
* Returns the next element.
*
* @return the next element.
* @throws NoSuchElementException if there are no more elements.
*/
public Object next() throws NoSuchElementException {
Object element = null;
if (nextElement != null) {
element = nextElement;
nextElement = null;
}
else {
element = getNextElement();
if (element == null) {
throw new NoSuchElementException();
}
}
return element;
}
/**
* Not supported for security reasons.
*/
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Returns the next available element, or null if there are no more elements to return.
*
* @return the next available element.
*/
public Object getNextElement() {
while (currentIndex + 1 < elements.length) {
currentIndex++;
Object element = objectFactory.loadObject(elements[currentIndex]);
if (element != null) {
return element;
}
}
return null;
}
}
\ No newline at end of file
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot.spi;
import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.LongList;
import org.jivesoftware.messenger.XMPPAddress;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.*;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.UserNotFoundException;
import java.util.*;
public class ChatbotManagerImpl extends BasicModule implements ChatbotManager {
private ChatbotAccountProvider accountProvider = ChatbotProviderFactory.getChatbotAccountProvider();
private ChatbotIDProvider idProvider = ChatbotProviderFactory.getChatbotIDProvider();
private ChatbotInfoProvider infoProvider = ChatbotProviderFactory.getChatbotInfoProvider();
private Map id2botname = new HashMap<Integer,Object>();
private Map id2botinfo = new HashMap<Integer,Object>();
private Hashtable botname2id = new Hashtable();
/**
* Create a chatbot manager.
*/
public ChatbotManagerImpl() {
super("Chatbot Manager");
LongList bots = idProvider.getChatbotIDs();
for (int i = 0; i < bots.size(); i++) {
try {
long botID = bots.get(i);
id2botname.put(botID, idProvider.getUsername(botID));
botname2id.put(id2botname.get(botID), new Long(botID));
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
public long createChatbot(String username) throws UserAlreadyExistsException, UnauthorizedException {
long botID = accountProvider.createChatbot(username);
id2botname.put(botID, username);
botname2id.put(username, new Long(botID));
return botID;
}
public String getChatbotUsername(long chatbotID) throws UserNotFoundException {
return (String)id2botname.get(chatbotID);
}
public long getChatbotID(String username) throws UserNotFoundException {
Long id = (Long)botname2id.get(username);
if (id == null) {
throw new UserNotFoundException(username);
}
return id.longValue();
}
public boolean isChatbot(XMPPAddress address) {
return botname2id.containsKey(address.getNamePrep());
}
public ChatbotInfo getChatbotInfo(long chatbotID) throws UserNotFoundException, UnsupportedOperationException {
if (!id2botinfo.containsKey(chatbotID)) {
id2botinfo.put(chatbotID, infoProvider.getInfo(chatbotID));
}
return (ChatbotInfo)id2botinfo.get(chatbotID);
}
public void setChatbotInfo(long chatbotID, ChatbotInfo info) throws UserNotFoundException, UnsupportedOperationException, UnauthorizedException {
infoProvider.updateInfo(chatbotID, info);
id2botinfo.put(chatbotID, info);
}
public void deleteChatbot(long chatbotID) throws UnauthorizedException, UserNotFoundException {
accountProvider.deleteChatbot(chatbotID);
id2botinfo.remove(chatbotID);
botname2id.remove(id2botname.get(chatbotID));
id2botname.remove(chatbotID);
}
public int getChatbotCount() {
return id2botname.size();
}
public LongList chatbots() {
return idProvider.getChatbotIDs();
}
public LongList chatbots(int startIndex, int numResults) {
return idProvider.getChatbotIDs(startIndex, numResults);
}
}
\ No newline at end of file
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot.spi;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotAccountProvider;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.spi.DbUserIDProvider;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
// TODO: this class is a copy of user id provider except for objecttype. Need to create a base
// class and just parameterize the object type.
public class DbChatbotAccountProvider implements ChatbotAccountProvider {
private static final String INSERT_CHATBOT_ID =
"INSERT INTO jiveUserID (username,domainID,objectType,objectID) VALUES (?,?,?,?)";
private static final String INSERT_CHATBOT_INFO =
"INSERT INTO jiveChatbot (chatbotID,description,creationDate,modificationDate) VALUES (?,?,?,?)";
public long createChatbot(String username)
throws UnauthorizedException, UserAlreadyExistsException {
long id = -1;
Connection con = null;
PreparedStatement pstmt = null;
try {
Date now = new Date();
// Reserve the name in the jiveUserID
id = SequenceManager.nextID(JiveConstants.USER);
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(INSERT_CHATBOT_ID);
pstmt.setString(1, username);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
pstmt.setLong(3, DbUserIDProvider.CHATBOT_TYPE);
pstmt.setLong(4, id);
pstmt.executeUpdate();
pstmt = con.prepareStatement(INSERT_CHATBOT_INFO);
pstmt.setLong(1, id);
pstmt.setString(2, "None");
pstmt.setString(3, StringUtils.dateToMillis(now));
pstmt.setString(4, StringUtils.dateToMillis(now));
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.error(LocaleUtils.getLocalizedString("admin.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);
}
}
return id;
}
private static final String DELETE_CHATBOT_ID =
"DELETE FROM jiveUserID WHERE objectID=? AND objectType=? and domainID=?";
private static final String DELETE_CHATBOT_INFO =
"DELETE FROM jiveChatbot WHERE chatbotID=?";
public void deleteChatbot(long userID) throws UnauthorizedException {
Connection con = null;
PreparedStatement pstmt = null;
boolean abortTransaction = false;
try {
con = DbConnectionManager.getTransactionConnection();
// Delete the actual chatbot info entry
pstmt = con.prepareStatement(DELETE_CHATBOT_INFO);
pstmt.setLong(1, userID);
pstmt.executeUpdate();
// Delete the actual user ID entry
pstmt = con.prepareStatement(DELETE_CHATBOT_ID);
pstmt.setLong(1, userID);
pstmt.setInt(2, DbUserIDProvider.CHATBOT_TYPE);
pstmt.setLong(3, DbUserIDProvider.DEFAULT_DOMAIN);
pstmt.executeUpdate();
}
catch (Exception e) {
Log.error(e);
abortTransaction = true;
}
finally {
try {
if (pstmt != null) {
pstmt.close();
}
}
catch (Exception e) {
Log.error(e);
}
DbConnectionManager.closeTransactionConnection(con, abortTransaction);
}
}
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot.spi;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.LongList;
import org.jivesoftware.messenger.chatbot.ChatbotIDProvider;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.spi.DbUserIDProvider;
import org.jivesoftware.database.DbConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
// TODO: this class is a copy of user id provider except for objecttype. Need to create a base
// class and just parameterize the object type.
public class DbChatbotIDProvider implements ChatbotIDProvider {
private static final String GET_USERID = "SELECT objectID FROM jiveUserID WHERE username=? AND domainID=? AND objectType=?";
private static final String GET_USERNAME = "SELECT username FROM jiveUserID WHERE objectID=? AND domainID=? AND objectType=?";
public String getUsername(long id) throws UserNotFoundException {
String name = null;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(GET_USERNAME);
pstmt.setLong(1, id);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
pstmt.setLong(3, DbUserIDProvider.CHATBOT_TYPE);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
name = rs.getString(1);
}
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.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);
}
}
if (name == null) {
throw new UserNotFoundException();
}
return name;
}
public long getChatbotID(String username) throws UserNotFoundException {
long id = -1;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(GET_USERID);
pstmt.setString(1, username);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
pstmt.setLong(3, DbUserIDProvider.CHATBOT_TYPE);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
id = rs.getLong(1);
}
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.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);
}
}
if (id == -1) {
throw new UserNotFoundException();
}
return id;
}
private static final String USER_COUNT = "SELECT count(*) FROM jiveUserID WHERE objectType=? AND domainID=?";
public int getChatbotCount() {
int count = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(USER_COUNT);
pstmt.setInt(1, DbUserIDProvider.CHATBOT_TYPE);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
}
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);
}
}
return count;
}
private static final String ALL_USERS =
"SELECT objectID from jiveUserID WHERE objectType=? AND domainID=?";
public LongList getChatbotIDs() {
LongList users = new LongList(500);
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
pstmt.setInt(1, DbUserIDProvider.CHATBOT_TYPE);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
ResultSet rs = pstmt.executeQuery();
// Set the fetch size. This will prevent some JDBC drivers from trying
// to load the entire result set into memory.
DbConnectionManager.setFetchSize(rs, 500);
while (rs.next()) {
users.add(rs.getLong(1));
}
}
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);
}
}
return users;
}
public LongList getChatbotIDs(int startIndex, int numResults) {
LongList users = new LongList();
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
pstmt.setInt(1, DbUserIDProvider.CHATBOT_TYPE);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
ResultSet rs = pstmt.executeQuery();
DbConnectionManager.setFetchSize(rs, startIndex + numResults);
// Move to start of index
for (int i = 0; i < startIndex; i++) {
rs.next();
}
// Now read in desired number of results (or stop if we run out of results).
for (int i = 0; i < numResults; i++) {
if (rs.next()) {
users.add(rs.getLong(1));
}
else {
break;
}
}
}
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);
}
}
return users;
}
}
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.chatbot.spi;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotInfo;
import org.jivesoftware.messenger.chatbot.ChatbotInfoProvider;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.database.DbConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DbChatbotInfoProvider implements ChatbotInfoProvider {
public DbChatbotInfoProvider() {
}
private static final String LOAD_CHATBOT_BY_ID =
"SELECT description, creationDate, modificationDate FROM jiveChatbot WHERE chatbotID=?";
public ChatbotInfo getInfo(long id) throws UserNotFoundException {
BasicChatbotInfo userInfo = null;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_CHATBOT_BY_ID);
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) {
throw new UserNotFoundException();
}
// We trim() the dates before trying to parse them because some
// databases pad with extra characters when returning the data.
userInfo = new BasicChatbotInfo(id,
rs.getString(1), // description
new java.util.Date(Long.parseLong(rs.getString(2).trim())), // creation date
new java.util.Date(Long.parseLong(rs.getString(3).trim()))); // modification date
}
catch (SQLException e) {
throw new UserNotFoundException("Failed to read user " + id + " from database.", e);
}
catch (NumberFormatException nfe) {
Log.error("WARNING: There was an error parsing the dates " +
"returned from the database. Ensure that they're being stored " +
"correctly.");
throw new UserNotFoundException("User with id "
+ id + " could not be loaded from the database.");
}
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 userInfo;
}
private static final String UPDATE_CHATBOT =
"UPDATE jiveChatbot SET description=?, creationDate=?, modificationDate=? WHERE chatbotID=?";
public void updateInfo(long id, ChatbotInfo info) throws UserNotFoundException, UnauthorizedException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(UPDATE_CHATBOT);
pstmt.setString(1, info.getDescription());
pstmt.setString(2, StringUtils.dateToMillis(info.getCreationDate()));
pstmt.setString(3, StringUtils.dateToMillis(info.getModificationDate()));
pstmt.setLong(4, id);
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
throw new UnauthorizedException();
}
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);
}
}
}
}
...@@ -64,11 +64,11 @@ public class IQPrivateHandler extends IQHandler implements ServerFeaturesProvide ...@@ -64,11 +64,11 @@ public class IQPrivateHandler extends IQHandler implements ServerFeaturesProvide
if (IQ.GET.equals(packet.getType())) { if (IQ.GET.equals(packet.getType())) {
replyPacket = packet.createResult(); replyPacket = packet.createResult();
PayloadFragment frag = new PayloadFragment("jabber:iq:private", "query"); PayloadFragment frag = new PayloadFragment("jabber:iq:private", "query");
frag.addFragment(new XMPPDOMFragment(privateStore.get(packet.getOriginatingSession().getUserID(), dataElement))); frag.addFragment(new XMPPDOMFragment(privateStore.get(packet.getOriginatingSession().getUsername(), dataElement)));
replyPacket.setChildFragment(frag); replyPacket.setChildFragment(frag);
} }
else { else {
privateStore.add(packet.getOriginatingSession().getUserID(), dataElement); privateStore.add(packet.getOriginatingSession().getUsername(), dataElement);
replyPacket = packet.createResult(); replyPacket = packet.createResult();
} }
} }
......
...@@ -177,7 +177,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid ...@@ -177,7 +177,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
reply = packet.createResult(); reply = packet.createResult();
if (session.getStatus() == Session.STATUS_AUTHENTICATED) { if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
try { try {
User user = userManager.getUser(session.getUserID()); User user = userManager.getUser(session.getUsername());
MetaDataFragment currentRegistration = (MetaDataFragment) probeResult MetaDataFragment currentRegistration = (MetaDataFragment) probeResult
.createDeepCopy(); .createDeepCopy();
currentRegistration.setProperty("query.registered", null); currentRegistration.setProperty("query.registered", null);
...@@ -191,15 +191,6 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid ...@@ -191,15 +191,6 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
form.getField("username").addValue(user.getUsername()); form.getField("username").addValue(user.getUsername());
form.getField("name").addValue(user.getInfo().getName()); form.getField("name").addValue(user.getInfo().getName());
form.getField("email").addValue(user.getInfo().getEmail()); form.getField("email").addValue(user.getInfo().getEmail());
// Clear default value and set new value
FormField field = form.getField("x-nameVisible");
field.clearValues();
field.addValue((user.getInfo().isNameVisible() ? "1" : "0"));
// Clear default value and set new value
field = form.getField("x-emailVisible");
field.clearValues();
field.addValue((user.getInfo().isEmailVisible() ? "1" : "0"));
reply.setChildFragment(currentRegistration); reply.setChildFragment(currentRegistration);
} }
catch (UserNotFoundException e) { catch (UserNotFoundException e) {
...@@ -228,7 +219,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid ...@@ -228,7 +219,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
presence.setSender(packet.getSender()); presence.setSender(packet.getSender());
presenceHandler.process(presence); presenceHandler.process(presence);
// Delete the user // Delete the user
userManager.deleteUser(session.getUserID()); userManager.deleteUser(userManager.getUser(session.getUsername()));
reply = packet.createResult(); reply = packet.createResult();
session.getConnection().deliver(reply); session.getConnection().deliver(reply);
// Close the user's connection // Close the user's connection
...@@ -290,7 +281,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid ...@@ -290,7 +281,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
} }
if (session.getStatus() == Session.STATUS_AUTHENTICATED) { if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
User user = userManager.getUser(session.getUserID()); User user = userManager.getUser(session.getUsername());
if (user != null) { if (user != null) {
if (user.getUsername().equalsIgnoreCase(username)) { if (user.getUsername().equalsIgnoreCase(username)) {
user.setPassword(password); user.setPassword(password);
...@@ -324,17 +315,6 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid ...@@ -324,17 +315,6 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
String name = (values.hasNext() ? values.next() : " "); String name = (values.hasNext() ? values.next() : " ");
newUser.getInfo().setName(name); newUser.getInfo().setName(name);
} }
// Get the name visible flag sent in the form
values = registrationForm.getField("x-nameVisible").getValues();
String visible = (values.hasNext() ? values.next() : "1");
boolean nameVisible = ("1".equals(visible) ? true : false);
// Get the email visible flag sent in the form
values = registrationForm.getField("x-emailVisible").getValues();
visible = (values.hasNext() ? values.next() : "0");
boolean emailVisible = ("1".equals(visible) ? true : false);
// Save the extra user info
newUser.getInfo().setNameVisible(nameVisible);
newUser.getInfo().setEmailVisible(emailVisible);
newUser.saveInfo(); newUser.saveInfo();
} }
......
...@@ -17,7 +17,6 @@ import org.jivesoftware.util.LocaleUtils; ...@@ -17,7 +17,6 @@ import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log; import org.jivesoftware.util.Log;
import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.Chatbot;
import org.jivesoftware.messenger.user.*; import org.jivesoftware.messenger.user.*;
import org.jivesoftware.messenger.user.spi.IQRosterItemImpl; import org.jivesoftware.messenger.user.spi.IQRosterItemImpl;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -151,7 +150,7 @@ public class IQRosterHandler extends IQHandler implements ServerFeaturesProvider ...@@ -151,7 +150,7 @@ public class IQRosterHandler extends IQHandler implements ServerFeaturesProvider
XMPPPacket.Type type = packet.getType(); XMPPPacket.Type type = packet.getType();
try { try {
User sessionUser = userManager.getUser(session.getUserID()); User sessionUser = userManager.getUser(session.getUsername());
CachedRoster cachedRoster = (CachedRoster)sessionUser.getRoster(); CachedRoster cachedRoster = (CachedRoster)sessionUser.getRoster();
if (IQ.GET == type) { if (IQ.GET == type) {
returnPacket = cachedRoster.getReset(); returnPacket = cachedRoster.getReset();
...@@ -226,15 +225,6 @@ public class IQRosterHandler extends IQHandler implements ServerFeaturesProvider ...@@ -226,15 +225,6 @@ public class IQRosterHandler extends IQHandler implements ServerFeaturesProvider
recipientRoster.deleteRosterItem(sender); recipientRoster.deleteRosterItem(sender);
} }
catch (UserNotFoundException e) { catch (UserNotFoundException e) {
try {
ChannelHandler route = routingTable.getRoute(recipient);
if (route instanceof Chatbot) {
route.process(packet);
}
}
catch (NoSuchRouteException e1) {
throw new UserNotFoundException();
}
} }
} }
else { // Recipient is remote so we just forward the packet to them else { // Recipient is remote so we just forward the packet to them
......
...@@ -71,7 +71,7 @@ public class IQvCardHandler extends IQHandler { ...@@ -71,7 +71,7 @@ public class IQvCardHandler extends IQHandler {
XMPPAddress recipient = packet.getRecipient(); XMPPAddress recipient = packet.getRecipient();
XMPPPacket.Type type = packet.getType(); XMPPPacket.Type type = packet.getType();
if (type.equals(IQ.SET)) { if (type.equals(IQ.SET)) {
User user = userManager.getUser(packet.getOriginatingSession().getUserID()); User user = userManager.getUser(packet.getOriginatingSession().getUsername());
// Proper format // Proper format
Element vcard = ((XMPPDOMFragment)packet.getChildFragment()).getRootElement(); Element vcard = ((XMPPDOMFragment)packet.getChildFragment()).getRootElement();
if (vcard != null) { if (vcard != null) {
......
...@@ -18,7 +18,6 @@ import org.jivesoftware.util.LocaleUtils; ...@@ -18,7 +18,6 @@ import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log; import org.jivesoftware.util.Log;
import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotManager;
import org.jivesoftware.messenger.user.*; import org.jivesoftware.messenger.user.*;
import org.jivesoftware.messenger.user.spi.CachedRosterImpl; import org.jivesoftware.messenger.user.spi.CachedRosterImpl;
import java.util.Hashtable; import java.util.Hashtable;
...@@ -88,22 +87,16 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand ...@@ -88,22 +87,16 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand
if (roster != null) { if (roster != null) {
manageSub(senderJID, false, type, roster); manageSub(senderJID, false, type, roster);
} }
if (chatbotManager.isChatbot(recipientJID)) { try {
RoutableChannelHandler route = routingTable.getRoute(recipientJID); // Try to obtain a handler for the packet based on the routes. If the handler is
route.process((XMPPPacket)presence.createDeepCopy()); // a module, the module will be able to handle the packet. If the handler is a
// Session the packet will be routed to the client. If a route cannot be found
// then the packet will be delivered based on its recipient and sender.
ChannelHandler handler = routingTable.getRoute(recipientJID);
handler.process((XMPPPacket)presence.createDeepCopy());
} }
else { catch (NoSuchRouteException e) {
try { deliverer.deliver((XMPPPacket)presence.createDeepCopy());
// Try to obtain a handler for the packet based on the routes. If the handler is
// a module, the module will be able to handle the packet. If the handler is a
// Session the packet will be routed to the client. If a route cannot be found
// then the packet will be delivered based on its recipient and sender.
ChannelHandler handler = routingTable.getRoute(recipientJID);
handler.process((XMPPPacket)presence.createDeepCopy());
}
catch (NoSuchRouteException e) {
deliverer.deliver((XMPPPacket)presence.createDeepCopy());
}
} }
} }
catch (Exception e) { catch (Exception e) {
...@@ -118,41 +111,21 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand ...@@ -118,41 +111,21 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand
* @return The roster or null if the address is not managed on the server * @return The roster or null if the address is not managed on the server
*/ */
private Roster getRoster(XMPPAddress address) { private Roster getRoster(XMPPAddress address) {
Long userID = null; String username = null;
Roster roster = null; Roster roster = null;
if (localServer.isLocal(address) && !"".equals(address.getName())) { if (localServer.isLocal(address) && !"".equals(address.getName())) {
try { username = address.getNamePrep();
if (chatbotManager != null) { // Check for a cached roster:
if (chatbotManager.isChatbot(address)) { roster = (Roster)CacheManager.getCache("username2roster").get(username);
userID = chatbotManager.getChatbotID(address.getNamePrep()); if (roster == null) {
} // Not in cache so load a new one:
} roster = new CachedRosterImpl(username);
} CacheManager.getCache("username2roster").put(username, roster);
catch (UserNotFoundException e) {
// do nothing
}
try {
if (userID == null && userManager != null) {
userID = userManager.getUserID(address.getNamePrep());
}
}
catch (UserNotFoundException e) {
// do nothing
}
if (userID != null) {
// Check for a cached roster:
roster = (Roster)CacheManager.getCache("userid2roster").get(userID);
if (roster == null) {
// Not in cache so load a new one:
roster = new CachedRosterImpl(userID, address.getNamePrep());
CacheManager.getCache("userid2roster").put(userID, roster);
}
} }
} }
return roster; return roster;
} }
/** /**
* Manage the subscription request. This method retrieves a user's roster * Manage the subscription request. This method retrieves a user's roster
* and updates it's state, storing any changes made, and updating the roster * and updates it's state, storing any changes made, and updating the roster
...@@ -163,11 +136,9 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand ...@@ -163,11 +136,9 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand
* @param type The subscription change type (subscribe, unsubscribe, etc.) * @param type The subscription change type (subscribe, unsubscribe, etc.)
* @throws UnauthorizedException If a security access violation occurs * @throws UnauthorizedException If a security access violation occurs
*/ */
private void manageSub(XMPPAddress target, private void manageSub(XMPPAddress target, boolean isSending, XMPPPacket.Type type,
boolean isSending, Roster roster) throws UnauthorizedException, UserAlreadyExistsException
XMPPPacket.Type type, {
Roster roster)
throws UnauthorizedException, UserAlreadyExistsException {
try { try {
RosterItem item; RosterItem item;
if (roster.isRosterItem(target)) { if (roster.isRosterItem(target)) {
...@@ -388,12 +359,10 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand ...@@ -388,12 +359,10 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand
public XMPPServer localServer; public XMPPServer localServer;
public PacketDeliverer deliverer; public PacketDeliverer deliverer;
public PacketFactory packetFactory; public PacketFactory packetFactory;
public ChatbotManager chatbotManager;
protected TrackInfo getTrackInfo() { protected TrackInfo getTrackInfo() {
TrackInfo trackInfo = new TrackInfo(); TrackInfo trackInfo = new TrackInfo();
trackInfo.getTrackerClasses().put(UserManager.class, "userManager"); trackInfo.getTrackerClasses().put(UserManager.class, "userManager");
trackInfo.getTrackerClasses().put(ChatbotManager.class, "chatbotManager");
trackInfo.getTrackerClasses().put(RoutingTable.class, "routingTable"); trackInfo.getTrackerClasses().put(RoutingTable.class, "routingTable");
trackInfo.getTrackerClasses().put(XMPPServer.class, "localServer"); trackInfo.getTrackerClasses().put(XMPPServer.class, "localServer");
trackInfo.getTrackerClasses().put(PacketDeliverer.class, "deliverer"); trackInfo.getTrackerClasses().put(PacketDeliverer.class, "deliverer");
......
...@@ -180,8 +180,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler ...@@ -180,8 +180,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
// Only user sessions need to be authenticated // Only user sessions need to be authenticated
if (!"".equals(session.getAddress().getName())) { if (!"".equals(session.getAddress().getName())) {
String username = session.getAddress().getNamePrep(); String username = session.getAddress().getNamePrep();
long userID = nameManager.getID(username); CachedRoster roster = rosterManager.getRoster(username);
CachedRoster roster = rosterManager.getRoster(userID);
Iterator items = roster.getRosterItems(); Iterator items = roster.getRosterItems();
while (items.hasNext()) { while (items.hasNext()) {
RosterItem item = (RosterItem)items.next(); RosterItem item = (RosterItem)items.next();
...@@ -197,7 +196,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler ...@@ -197,7 +196,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
} }
} }
// deliver offline messages if any // deliver offline messages if any
Iterator msgs = messageStore.getMessages(userID); Iterator msgs = messageStore.getMessages(username);
while (msgs.hasNext()) { while (msgs.hasNext()) {
Message msg = (Message)msgs.next(); Message msg = (Message)msgs.next();
session.getConnection().deliver(msg); session.getConnection().deliver(msg);
...@@ -243,8 +242,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler ...@@ -243,8 +242,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
try { try {
if (name != null && !"".equals(name)) { if (name != null && !"".equals(name)) {
name = name.toLowerCase(); name = name.toLowerCase();
long userID = nameManager.getID(name); CachedRoster roster = rosterManager.getRoster(name);
CachedRoster roster = rosterManager.getRoster(userID);
roster.broadcastPresence(update); roster.broadcastPresence(update);
} }
} }
...@@ -308,8 +306,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler ...@@ -308,8 +306,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
try { try {
if (name != null && !"".equals(name)) { if (name != null && !"".equals(name)) {
name = name.toLowerCase(); name = name.toLowerCase();
long userID = nameManager.getID(name); CachedRoster roster = rosterManager.getRoster(name);
CachedRoster roster = rosterManager.getRoster(userID);
// If the directed presence was sent to an entity that is not in the user's // If the directed presence was sent to an entity that is not in the user's
// roster, keep a registry of this so that when the user goes offline we will // roster, keep a registry of this so that when the user goes offline we will
// be able to send the unavialable presence to the entity // be able to send the unavialable presence to the entity
...@@ -398,12 +395,10 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler ...@@ -398,12 +395,10 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
public PacketDeliverer deliverer; public PacketDeliverer deliverer;
public PacketFactory packetFactory; public PacketFactory packetFactory;
public OfflineMessageStore messageStore; public OfflineMessageStore messageStore;
public NameIDManager nameManager;
protected TrackInfo getTrackInfo() { protected TrackInfo getTrackInfo() {
TrackInfo trackInfo = new TrackInfo(); TrackInfo trackInfo = new TrackInfo();
trackInfo.getTrackerClasses().put(RosterManager.class, "rosterManager"); trackInfo.getTrackerClasses().put(RosterManager.class, "rosterManager");
trackInfo.getTrackerClasses().put(NameIDManager.class, "nameManager");
trackInfo.getTrackerClasses().put(XMPPServer.class, "localServer"); trackInfo.getTrackerClasses().put(XMPPServer.class, "localServer");
trackInfo.getTrackerClasses().put(SessionManager.class, "sessionManager"); trackInfo.getTrackerClasses().put(SessionManager.class, "sessionManager");
trackInfo.getTrackerClasses().put(PresenceManager.class, "presenceManager"); trackInfo.getTrackerClasses().put(PresenceManager.class, "presenceManager");
......
...@@ -410,7 +410,7 @@ public class LdapManager { ...@@ -410,7 +410,7 @@ public class LdapManager {
} }
String userDN = ((SearchResult)answer.next()).getName(); String userDN = ((SearchResult)answer.next()).getName();
// Make sure there are no more search results. If there are, then // Make sure there are no more search results. If there are, then
// the userID isn't unique on the LDAP server (a perfectly possible // the username isn't unique on the LDAP server (a perfectly possible
// scenario since only fully qualified dn's need to be unqiue). // scenario since only fully qualified dn's need to be unqiue).
// There really isn't a way to handle this, so throw an exception. // There really isn't a way to handle this, so throw an exception.
// The baseDN must be set correctly so that this doesn't happen. // The baseDN must be set correctly so that this doesn't happen.
......
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.ldap;
import org.jivesoftware.messenger.user.UserAccountProvider;
/**
* <p>Defines the provider methods required for creating and deleting user accounts.</p>
* <p/>
* <p>Since the LDAP datastore is currently considered read-only, all the methods here throw
* UnsupportedOperationExceptions</p>
*
* @author Jim Berrettini
*/
public class LdapUserAccountProvider implements UserAccountProvider {
/**
* <p>Called to create a new user account. Not implemented, throws UnsupportedOperationException.</p>
*
* @param username the name of the user
* @param password the user's password
* @param email the user's email address
* @return the userID of the created account
* @throws UnsupportedOperationException always thrown because it is not supported
*/
public long createUser(String username, String password, String email) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Creating new users not supported.");
}
/**
* <p>Called to delete a user account. Not implemented, throws UnsupportedOperationException.</p>
*
* @param id the id of the user to delete
* @throws UnsupportedOperationException always thrown because it is not supported
*/
public void deleteUser(long id) throws UnsupportedOperationException {
// todo -- we can use this method to clean up the database.
throw new UnsupportedOperationException();
}
}
...@@ -25,34 +25,34 @@ public class LdapUserPropertiesProvider implements UserPropertiesProvider { ...@@ -25,34 +25,34 @@ public class LdapUserPropertiesProvider implements UserPropertiesProvider {
/** /**
* Delete Vcard property. Currently unimplemented. * Delete Vcard property. Currently unimplemented.
* *
* @param id * @param username
* @param name * @param name
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
public void deleteVcardProperty(long id, String name) throws UnsupportedOperationException { public void deleteVcardProperty(String username, String name) throws UnsupportedOperationException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
/** /**
* Delete user property. Currently unimplemented. * Delete user property. Currently unimplemented.
* *
* @param id * @param username
* @param name * @param name
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
public void deleteUserProperty(long id, String name) throws UnsupportedOperationException { public void deleteUserProperty(String username, String name) throws UnsupportedOperationException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
/** /**
* Insert new vCard property. Currently unimplemented. * Insert new vCard property. Currently unimplemented.
* *
* @param id * @param username
* @param name * @param name
* @param value * @param value
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
public void insertVcardProperty(long id, String name, String value) throws UnsupportedOperationException { public void insertVcardProperty(String username, String name, String value) throws UnsupportedOperationException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
...@@ -60,56 +60,56 @@ public class LdapUserPropertiesProvider implements UserPropertiesProvider { ...@@ -60,56 +60,56 @@ public class LdapUserPropertiesProvider implements UserPropertiesProvider {
/** /**
* Insert new user property. Currently unimplemented. * Insert new user property. Currently unimplemented.
* *
* @param id * @param username
* @param name * @param name
* @param value * @param value
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
public void insertUserProperty(long id, String name, String value) throws UnsupportedOperationException { public void insertUserProperty(String username, String name, String value) throws UnsupportedOperationException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
/** /**
* Update vCard. Currently unimplemented. * Update vCard. Currently unimplemented.
* *
* @param id * @param username
* @param name * @param name
* @param value * @param value
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
public void updateVcardProperty(long id, String name, String value) throws UnsupportedOperationException { public void updateVcardProperty(String username, String name, String value) throws UnsupportedOperationException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
/** /**
* Update user property. Currently unimplemented. * Update user property. Currently unimplemented.
* *
* @param id * @param username
* @param name * @param name
* @param value * @param value
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
public void updateUserProperty(long id, String name, String value) throws UnsupportedOperationException { public void updateUserProperty(String username, String name, String value) throws UnsupportedOperationException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
/** /**
* Get vCard properties. Unimplemented. * Get vCard properties. Unimplemented.
* *
* @param id * @param username
* @return empty Map * @return empty Map
*/ */
public Map getVcardProperties(long id) { public Map getVcardProperties(String username) {
return Collections.EMPTY_MAP; return Collections.EMPTY_MAP;
} }
/** /**
* Get user properties. Unimplemented. * Get user properties. Unimplemented.
* *
* @param id * @param username
* @return empty Map. * @return empty Map.
*/ */
public Map getUserProperties(long id) { public Map getUserProperties(String username) {
return Collections.EMPTY_MAP; return Collections.EMPTY_MAP;
} }
} }
...@@ -17,9 +17,7 @@ import java.util.LinkedList; ...@@ -17,9 +17,7 @@ import java.util.LinkedList;
import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamException;
import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotManager;
import org.jivesoftware.messenger.container.BasicModule; import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.messenger.container.ServiceLookupFactory;
import org.jivesoftware.messenger.container.TrackInfo; import org.jivesoftware.messenger.container.TrackInfo;
import org.jivesoftware.messenger.handler.IQHandler; import org.jivesoftware.messenger.handler.IQHandler;
import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.LocaleUtils;
...@@ -37,7 +35,6 @@ public class IQRouterImpl extends BasicModule implements IQRouter { ...@@ -37,7 +35,6 @@ public class IQRouterImpl extends BasicModule implements IQRouter {
public RoutingTable routingTable; public RoutingTable routingTable;
public LinkedList iqHandlers = new LinkedList(); public LinkedList iqHandlers = new LinkedList();
private HashMap namespace2Handlers = new HashMap(); private HashMap namespace2Handlers = new HashMap();
private ChatbotManager chatBotManager;
/** /**
* Creates a packet router. * Creates a packet router.
...@@ -72,24 +69,9 @@ public class IQRouterImpl extends BasicModule implements IQRouter { ...@@ -72,24 +69,9 @@ public class IQRouterImpl extends BasicModule implements IQRouter {
} }
private boolean isLocalServer(XMPPAddress recipientJID) { private boolean isLocalServer(XMPPAddress recipientJID) {
boolean isLocalServer = recipientJID == null || recipientJID.getHost() == null return recipientJID == null || recipientJID.getHost() == null
|| "".equals(recipientJID.getHost()) || recipientJID.getResource() == null || "".equals(recipientJID.getHost()) || recipientJID.getResource() == null
|| "".equals(recipientJID.getResource()); || "".equals(recipientJID.getResource());
if (recipientJID != null && isLocalServer) {
if (chatBotManager == null) {
try {
chatBotManager = (ChatbotManager)ServiceLookupFactory.getLookup().lookup(ChatbotManager.class);
}
catch (UnauthorizedException e) {
Log.error(e);
}
}
isLocalServer = !chatBotManager.isChatbot(recipientJID);
}
return isLocalServer;
} }
private void handle(IQ packet) { private void handle(IQ packet) {
......
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.spi;
import org.jivesoftware.util.Cache;
import org.jivesoftware.util.CacheManager;
import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.messenger.NameIDManager;
import org.jivesoftware.messenger.chatbot.spi.ChatbotManagerImpl;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.util.Cache;
import org.jivesoftware.util.CacheManager;
public class NameIDManagerImpl extends BasicModule implements NameIDManager {
protected Cache id2userCache;
protected Cache name2idCache;
protected ChatbotManagerImpl chatbotManager = new ChatbotManagerImpl();
/**
* Create a basic module with a set name.
*/
public NameIDManagerImpl() {
super("Name ID Manager");
}
public String getUsername(long id) throws UserNotFoundException {
if (id2userCache == null) {
id2userCache = CacheManager.getCache("userid2user");
}
User user = (User)id2userCache.get(new Long(id));
if (user == null) {
return chatbotManager.getChatbotUsername(id);
}
else {
return user.getUsername();
}
}
public long getID(String username) throws UserNotFoundException {
if (name2idCache == null) {
name2idCache = CacheManager.getCache("username2userid");
}
Long id = (Long)name2idCache.get(username);
if (id == null) {
return chatbotManager.getChatbotID(username);
}
else {
return id.longValue();
}
}
}
...@@ -55,30 +55,13 @@ public class OfflineMessageStoreProxy implements OfflineMessageStore { ...@@ -55,30 +55,13 @@ public class OfflineMessageStoreProxy implements OfflineMessageStore {
} }
} }
public Iterator getMessages(long userID) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
return store.getMessages(userID);
}
else {
throw new org.jivesoftware.messenger.auth.UnauthorizedException();
}
}
public int getSize(long userID) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
return store.getSize(userID);
}
else {
throw new org.jivesoftware.messenger.auth.UnauthorizedException();
}
}
public int getSize(String userName) throws UnauthorizedException, UserNotFoundException { public int getSize(String username) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
return store.getSize(userName); return store.getSize(username);
} }
else { else {
throw new org.jivesoftware.messenger.auth.UnauthorizedException(); throw new org.jivesoftware.messenger.auth.UnauthorizedException();
} }
} }
} }
\ No newline at end of file
...@@ -34,7 +34,7 @@ import org.dom4j.Element; ...@@ -34,7 +34,7 @@ import org.dom4j.Element;
*/ */
public class PresenceImpl extends AbstractPacket implements Presence, Cacheable { public class PresenceImpl extends AbstractPacket implements Presence, Cacheable {
private long userID = -1; private String username;
private String uid = ""; private String uid = "";
private Date loginTime; private Date loginTime;
private Date updateTime; private Date updateTime;
...@@ -46,7 +46,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable ...@@ -46,7 +46,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable
public PresenceImpl(User user, String uid) { public PresenceImpl(User user, String uid) {
this(); this();
if (user != null) { if (user != null) {
this.userID = user.getID(); this.username = user.getUsername();
} }
this.uid = uid; this.uid = uid;
...@@ -140,8 +140,8 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable ...@@ -140,8 +140,8 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable
} }
} }
public long getUserID() { public String getUsername() {
return userID; return username;
} }
public Date getLoginTime() { public Date getLoginTime() {
...@@ -184,7 +184,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable ...@@ -184,7 +184,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable
// Approximate the size of the object in bytes by calculating the size of each field. // Approximate the size of the object in bytes by calculating the size of each field.
int size = 0; int size = 0;
size += CacheSizes.sizeOfObject(); // overhead of object size += CacheSizes.sizeOfObject(); // overhead of object
size += CacheSizes.sizeOfLong(); // userID size += CacheSizes.sizeOfString(username); // username
size += CacheSizes.sizeOfString(uid); // uid size += CacheSizes.sizeOfString(uid); // uid
size += CacheSizes.sizeOfDate(); // login date size += CacheSizes.sizeOfDate(); // login date
size += CacheSizes.sizeOfDate(); // last update date size += CacheSizes.sizeOfDate(); // last update date
...@@ -250,7 +250,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable ...@@ -250,7 +250,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable
public XMPPFragment createDeepCopy() { public XMPPFragment createDeepCopy() {
PresenceImpl presence = new PresenceImpl(); PresenceImpl presence = new PresenceImpl();
deepCopy(presence); deepCopy(presence);
presence.userID = userID; presence.username = username;
presence.uid = uid; presence.uid = uid;
presence.loginTime = loginTime; presence.loginTime = loginTime;
presence.updateTime = updateTime; presence.updateTime = updateTime;
......
...@@ -18,9 +18,7 @@ import org.jivesoftware.messenger.auth.AuthToken; ...@@ -18,9 +18,7 @@ import org.jivesoftware.messenger.auth.AuthToken;
import org.jivesoftware.messenger.auth.Permissions; import org.jivesoftware.messenger.auth.Permissions;
import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.User; import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.spi.UserIteratorProxy; import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
/** /**
* Enforces security constraints. * Enforces security constraints.
...@@ -44,65 +42,20 @@ public class PresenceManagerProxy implements PresenceManager { ...@@ -44,65 +42,20 @@ public class PresenceManagerProxy implements PresenceManager {
return manager.isAvailable(user); return manager.isAvailable(user);
} }
public int getOnlineUserCount() {
Iterator iter = getOnlineUsers();
int count = 0;
while (iter.hasNext()) {
iter.next();
count++;
}
return count;
}
public int getOnlineGuestCount() { public int getOnlineGuestCount() {
return manager.getOnlineGuestCount(); return manager.getOnlineGuestCount();
} }
public Iterator getOnlineUsers() { public Collection<User> getOnlineUsers() {
Iterator iter = manager.getOnlineUsers(); return manager.getOnlineUsers();
ArrayList users = new ArrayList();
while (iter.hasNext()) {
User user = (User)iter.next();
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN) ||
user.isAuthorized(Permissions.VIEW_ONLINE_STATUS)) {
users.add(user);
}
}
return new UserIteratorProxy(users.iterator(), authToken, permissions);
} }
public Iterator getOnlineUsers(boolean ascending, int sortField) { public Collection<User> getOnlineUsers(boolean ascending, int sortField) {
Iterator iter = manager.getOnlineUsers(ascending, sortField); return manager.getOnlineUsers(ascending, sortField);
ArrayList users = new ArrayList();
while (iter.hasNext()) {
User user = (User)iter.next();
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN) ||
user.isAuthorized(Permissions.VIEW_ONLINE_STATUS)) {
users.add(user);
}
}
return new UserIteratorProxy(users.iterator(), authToken, permissions);
} }
public Iterator getOnlineUsers(boolean ascending, int sortField, int numResults) { public Collection<User> getOnlineUsers(boolean ascending, int sortField, int numResults) {
Iterator iter = manager.getOnlineUsers(ascending, sortField, numResults); return manager.getOnlineUsers(ascending, sortField, numResults);
ArrayList users = new ArrayList();
while (iter.hasNext()) {
User user = (User)iter.next();
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN) ||
user.isAuthorized(Permissions.VIEW_ONLINE_STATUS)) {
users.add(user);
}
}
return new UserIteratorProxy(users.iterator(), authToken, permissions);
} }
public Presence createPresence(User user, String uid) throws UnauthorizedException { public Presence createPresence(User user, String uid) throws UnauthorizedException {
...@@ -115,7 +68,7 @@ public class PresenceManagerProxy implements PresenceManager { ...@@ -115,7 +68,7 @@ public class PresenceManagerProxy implements PresenceManager {
} }
public void setOffline(Presence presence) throws UnauthorizedException { public void setOffline(Presence presence) throws UnauthorizedException {
if ((presence.getUserID() == authToken.getUserID()) || if (presence.getUsername().equals(authToken.getUsername()) ||
permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
manager.setOffline(presence); manager.setOffline(presence);
} }
......
...@@ -36,7 +36,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence { ...@@ -36,7 +36,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
} }
public void setAvailable(boolean online) throws UnauthorizedException { public void setAvailable(boolean online) throws UnauthorizedException {
if ((presence.getUserID() == authToken.getUserID()) || if (presence.getUsername().equals(authToken.getUsername()) ||
permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
presence.setAvailable(online); presence.setAvailable(online);
} }
...@@ -50,7 +50,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence { ...@@ -50,7 +50,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
} }
public void setVisible(boolean visible) throws UnauthorizedException { public void setVisible(boolean visible) throws UnauthorizedException {
if ((presence.getUserID() == authToken.getUserID()) || if (presence.getUsername().equals(authToken.getUsername()) ||
permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
presence.setVisible(visible); presence.setVisible(visible);
} }
...@@ -63,8 +63,8 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence { ...@@ -63,8 +63,8 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
return presence.getID(); return presence.getID();
} }
public long getUserID() { public String getUsername() {
return presence.getUserID(); return presence.getUsername();
} }
public Date getLoginTime() { public Date getLoginTime() {
...@@ -76,7 +76,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence { ...@@ -76,7 +76,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
} }
public void setLastUpdateTime(Date time) throws UnauthorizedException { public void setLastUpdateTime(Date time) throws UnauthorizedException {
if ((presence.getUserID() == authToken.getUserID()) || if (presence.getUsername().equals(authToken.getUsername()) ||
permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
presence.setLastUpdateTime(time); presence.setLastUpdateTime(time);
} }
...@@ -90,7 +90,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence { ...@@ -90,7 +90,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
} }
public void setShow(int status) throws UnauthorizedException { public void setShow(int status) throws UnauthorizedException {
if ((presence.getUserID() == authToken.getUserID()) || if (presence.getUsername().equals(authToken.getUsername()) ||
permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
presence.setShow(status); presence.setShow(status);
} }
...@@ -104,7 +104,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence { ...@@ -104,7 +104,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
} }
public void setStatus(String status) throws UnauthorizedException { public void setStatus(String status) throws UnauthorizedException {
if ((presence.getUserID() == authToken.getUserID()) || if (presence.getUsername().equals(authToken.getUsername()) ||
permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
presence.setStatus(status); presence.setStatus(status);
} }
...@@ -118,7 +118,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence { ...@@ -118,7 +118,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
} }
public void setPriority(int priority) throws UnauthorizedException { public void setPriority(int priority) throws UnauthorizedException {
if ((presence.getUserID() == authToken.getUserID()) || if (presence.getUsername().equals(authToken.getUsername()) ||
permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
presence.setPriority(priority); presence.setPriority(priority);
} }
......
...@@ -57,18 +57,18 @@ public class PrivateStoreProxy implements PrivateStore { ...@@ -57,18 +57,18 @@ public class PrivateStoreProxy implements PrivateStore {
} }
} }
public void add(long userID, Element data) throws UnauthorizedException { public void add(String username, Element data) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
store.add(userID, data); store.add(username, data);
} }
else { else {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
} }
public Element get(long userID, Element data) throws UnauthorizedException { public Element get(String username, Element data) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) { if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
return store.get(userID, data); return store.get(username, data);
} }
else { else {
throw new UnauthorizedException(); throw new UnauthorizedException();
......
...@@ -92,11 +92,11 @@ public class SessionImpl implements Session { ...@@ -92,11 +92,11 @@ public class SessionImpl implements Session {
} }
} }
public long getUserID() throws UserNotFoundException { public String getUsername() throws UserNotFoundException {
if (authToken == null) { if (authToken == null) {
throw new UserNotFoundException(); throw new UserNotFoundException();
} }
return authToken.getUserID(); return authToken.getUsername();
} }
public String getServerName() { public String getServerName() {
...@@ -104,7 +104,7 @@ public class SessionImpl implements Session { ...@@ -104,7 +104,7 @@ public class SessionImpl implements Session {
} }
public void setAuthToken(AuthToken auth, UserManager userManager, String resource) throws UserNotFoundException { public void setAuthToken(AuthToken auth, UserManager userManager, String resource) throws UserNotFoundException {
User user = userManager.getUser(auth.getUserID()); User user = userManager.getUser(auth.getUsername());
jid = new XMPPAddress(user.getUsername(), serverName, resource); jid = new XMPPAddress(user.getUsername(), serverName, resource);
authToken = auth; authToken = auth;
......
...@@ -471,22 +471,16 @@ public class SessionManagerImpl extends BasicModule implements SessionManager, ...@@ -471,22 +471,16 @@ public class SessionManagerImpl extends BasicModule implements SessionManager,
// Grab all the possible matching sessions by user // Grab all the possible matching sessions by user
LinkedList results = new LinkedList(); LinkedList results = new LinkedList();
if (filter.getUserID() == SessionResultFilter.ALL_USER_ID) { if (filter.getUsername() == null) {
// No user id filtering // No user id filtering
copyAnonSessions(results); copyAnonSessions(results);
copyUserSessions(results); copyUserSessions(results);
} }
else { else {
// user id filtering try {
if (filter.getUserID() == SessionResultFilter.ANONYMOUS_USER_ID) { copyUserSessions(userManager.getUser(filter.getUsername()).getUsername(), results);
copyAnonSessions(results);
} }
else { catch (UserNotFoundException e) {
try {
copyUserSessions(userManager.getUser(filter.getUserID()).getUsername(), results);
}
catch (UserNotFoundException e) {
}
} }
} }
......
...@@ -28,11 +28,11 @@ import org.jivesoftware.util.Cacheable; ...@@ -28,11 +28,11 @@ import org.jivesoftware.util.Cacheable;
public interface CachedRoster extends Roster, Cacheable { public interface CachedRoster extends Roster, Cacheable {
/** /**
* <p>Return the id of the user or chatbot that owns this roster.</p> * <p>Return the username of the user or chatbot that owns this roster.</p>
* *
* @return The long ID of the user or chatbot that owns this roster * @return the username of the user or chatbot that owns this roster
*/ */
long getUserID(); String getUsername();
/** /**
* <p>Obtain a 'roster reset', a snapshot of the full cached roster as an IQRoster.</p> * <p>Obtain a 'roster reset', a snapshot of the full cached roster as an IQRoster.</p>
......
...@@ -36,35 +36,35 @@ public interface RosterItemProvider { ...@@ -36,35 +36,35 @@ public interface RosterItemProvider {
* <p/> * <p/>
* <p>If you don't want roster items edited through messenger, throw UnsupportedOperationException.</p> * <p>If you don't want roster items edited through messenger, throw UnsupportedOperationException.</p>
* *
* @param userID The long ID of the user/chatbot that owns the roster item * @param username the username of the user/chatbot that owns the roster item
* @param item The settings for the roster item to create * @param item the settings for the roster item to create
* @return The created roster item * @return The created roster item
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation) * @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/ */
CachedRosterItem createItem(long userID, RosterItem item) throws UserAlreadyExistsException, UnsupportedOperationException; CachedRosterItem createItem(String username, RosterItem item) throws UserAlreadyExistsException, UnsupportedOperationException;
/** /**
* <p>Update the roster item in storage with the information contained in the given item (optional operation).</p> * <p>Update the roster item in storage with the information contained in the given item (optional operation).</p>
* <p/> * <p/>
* <p>If you don't want roster items edited through messenger, throw UnsupportedOperationException.</p> * <p>If you don't want roster items edited through messenger, throw UnsupportedOperationException.</p>
* *
* @param userID The long ID of the user/chatbot that owns the roster item * @param username the username of the user/chatbot that owns the roster item
* @param item The roster item to update * @param item The roster item to update
* @throws UserNotFoundException If no entry could be found to update * @throws UserNotFoundException If no entry could be found to update
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation) * @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/ */
void updateItem(long userID, CachedRosterItem item) throws UserNotFoundException, UnsupportedOperationException; void updateItem(String username, CachedRosterItem item) throws UserNotFoundException, UnsupportedOperationException;
/** /**
* <p>Delete the roster item with the given itemJID for the user (optional operation).</p> * <p>Delete the roster item with the given itemJID for the user (optional operation).</p>
* <p/> * <p/>
* <p>If you don't want roster items deleted through messenger, throw UnsupportedOperationException.</p> * <p>If you don't want roster items deleted through messenger, throw UnsupportedOperationException.</p>
* *
* @param userID The long ID of the user/chatbot that owns the roster item * @param username the long ID of the user/chatbot that owns the roster item
* @param rosterItemID The roster item to delete * @param rosterItemID The roster item to delete
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation) * @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/ */
void deleteItem(long userID, long rosterItemID) throws UnsupportedOperationException; void deleteItem(String username, long rosterItemID) throws UnsupportedOperationException;
/** /**
* <p>Delete all roster items associated with the given user (optional operation).</p> * <p>Delete all roster items associated with the given user (optional operation).</p>
...@@ -74,18 +74,18 @@ public interface RosterItemProvider { ...@@ -74,18 +74,18 @@ public interface RosterItemProvider {
* <p/> * <p/>
* <p>If you don't want roster items deleted through messenger, throw UnsupportedOperationException.</p> * <p>If you don't want roster items deleted through messenger, throw UnsupportedOperationException.</p>
* *
* @param userID The long ID of the user/chatbot that owns the roster items * @param username the username of the user/chatbot that owns the roster items
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation) * @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/ */
void deleteItems(long userID) throws UnsupportedOperationException; void deleteItems(String username) throws UnsupportedOperationException;
/** /**
* <p>Obtain a count of the number of roster items available for the given user.</p> * <p>Obtain a count of the number of roster items available for the given user.</p>
* *
* @param userID The long ID of the user/chatbot that owns the roster items * @param username the username of the user/chatbot that owns the roster items
* @return The number of roster items available for the user * @return The number of roster items available for the user
*/ */
int getItemCount(long userID); int getItemCount(String username);
/** /**
* <p>Retrieve an iterator of RosterItems for the given user.</p> * <p>Retrieve an iterator of RosterItems for the given user.</p>
...@@ -94,8 +94,8 @@ public interface RosterItemProvider { ...@@ -94,8 +94,8 @@ public interface RosterItemProvider {
* in memory when possible. However, some rosters may be very large so items may need * in memory when possible. However, some rosters may be very large so items may need
* to be retrieved from the provider more frequently than usual for provider data. * to be retrieved from the provider more frequently than usual for provider data.
* *
* @param userID The long ID of the user/chatbot that owns the roster items * @param username the username of the user/chatbot that owns the roster items
* @return An iterator of all RosterItems owned by the user * @return An iterator of all RosterItems owned by the user
*/ */
Iterator getItems(long userID); Iterator getItems(String username);
} }
...@@ -24,11 +24,11 @@ package org.jivesoftware.messenger.user; ...@@ -24,11 +24,11 @@ package org.jivesoftware.messenger.user;
*/ */
public interface RosterManager { public interface RosterManager {
/** /**
* <p>Obtain the roster for the given ID.</p> * <p>Obtain the roster for the given username.</p>
* *
* @param id The ID to search for * @param username the username to search for
* @return The roster associated with the ID * @return The roster associated with the ID
* @throws UserNotFoundException If the ID does not correspond to a known entity on the server * @throws UserNotFoundException If the ID does not correspond to a known entity on the server
*/ */
CachedRoster getRoster(long id) throws UserNotFoundException; CachedRoster getRoster(String username) throws UserNotFoundException;
} }
...@@ -11,7 +11,6 @@ ...@@ -11,7 +11,6 @@
package org.jivesoftware.messenger.user; package org.jivesoftware.messenger.user;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.AuthToken; import org.jivesoftware.messenger.auth.AuthToken;
import org.jivesoftware.messenger.auth.Group; import org.jivesoftware.messenger.auth.Group;
import org.jivesoftware.messenger.auth.Permissions; import org.jivesoftware.messenger.auth.Permissions;
...@@ -29,7 +28,16 @@ import java.util.Iterator; ...@@ -29,7 +28,16 @@ import java.util.Iterator;
* *
* @see Group * @see Group
*/ */
public interface User extends Entity { public interface User {
/**
* <p>Returns the entity's username.</p>
* <p/>
* <p>All usernames must be unique in the system.</p>
*
* @return the username of the entity.
*/
String getUsername();
/** /**
* <p>Sets a new password for the user.</p> * <p>Sets a new password for the user.</p>
......
...@@ -34,21 +34,21 @@ public interface UserInfoProvider { ...@@ -34,21 +34,21 @@ public interface UserInfoProvider {
* <p>If your implementation doesn't support user info, simply return a UserInfo object filled with default * <p>If your implementation doesn't support user info, simply return a UserInfo object filled with default
* values.</p> * values.</p>
* *
* @param id The id of the user * @param username the username of the user.
* @return The user's info * @return The user's info
* @throws UserNotFoundException If a user with the given ID couldn't be found * @throws UserNotFoundException If a user with the given ID couldn't be found
*/ */
UserInfo getInfo(long id) throws UserNotFoundException; UserInfo getInfo(String username) throws UserNotFoundException;
/** /**
* <p>Sets the user's info (optional operation).</p> * <p>Sets the user's info (optional operation).</p>
* *
* @param id The ID of the user * @param username the username of the user.
* @param info The user's new info * @param info The user's new info
* @throws UserNotFoundException If a user with the given ID couldn't be found * @throws UserNotFoundException If a user with the given ID couldn't be found
* @throws UnauthorizedException If this operation is not allowed for the caller's permissions * @throws UnauthorizedException If this operation is not allowed for the caller's permissions
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation) * @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/ */
void setInfo(long id, UserInfo info) void setInfo(String username, UserInfo info)
throws UserNotFoundException, UnauthorizedException, UnsupportedOperationException; throws UserNotFoundException, UnauthorizedException, UnsupportedOperationException;
} }
...@@ -24,8 +24,8 @@ public class CachedRosterProxy extends RosterProxy implements CachedRoster { ...@@ -24,8 +24,8 @@ public class CachedRosterProxy extends RosterProxy implements CachedRoster {
super(roster, authToken, permissions); super(roster, authToken, permissions);
} }
public long getUserID() { public String getUsername() {
return ((CachedRoster)roster).getUserID(); return ((CachedRoster)roster).getUsername();
} }
public IQRoster getReset() throws UnauthorizedException { public IQRoster getReset() throws UnauthorizedException {
......
...@@ -41,10 +41,6 @@ public class UserProxy implements User { ...@@ -41,10 +41,6 @@ public class UserProxy implements User {
this.permissions = permissions; this.permissions = permissions;
} }
public long getID() {
return user.getID();
}
public String getUsername() { public String getUsername() {
return user.getUsername(); return user.getUsername();
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment