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 @@
-- $Date$
CREATE TABLE jiveUser (
userID INTEGER NOT NULL,
username VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL,
name VARCHAR(100),
nameVisible INTEGER NOT NULL,
email VARCHAR(100),
emailVisible INTEGER NOT NULL,
creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL,
CONSTRAINT jiveUser_pk PRIMARY KEY (userID)
......@@ -17,7 +15,7 @@ CREATE INDEX jiveUsr_cDate_idx ON jiveUser (creationDate ASC);
CREATE TABLE jiveUserProp (
userID INTEGER NOT NULL,
username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL,
propValue VARCHAR(2000) NOT NULL,
CONSTRAINT jiveUsrProp_pk PRIMARY KEY (userID, name)
......@@ -25,7 +23,7 @@ CREATE TABLE jiveUserProp (
CREATE TABLE jivePrivate (
userID INTEGER NOT NULL,
username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL,
namespace VARCHAR(200) NOT NULL,
value LONG VARCHAR NOT NULL,
......@@ -34,7 +32,7 @@ CREATE TABLE jivePrivate (
CREATE TABLE jiveOffline (
userID INTEGER NOT NULL,
username VARCHAR(32) NOT NULL,
messageID INTEGER NOT NULL,
creationDate CHAR(15) NOT NULL,
messageSize INTEGER NOT NULL,
......@@ -45,7 +43,7 @@ CREATE TABLE jiveOffline (
CREATE TABLE jiveRoster (
rosterID INTEGER NOT NULL,
userID INTEGER NOT NULL,
username VARCHAR(32) NOT NULL,
jid VARCHAR(2000) NOT NULL,
sub INTEGER NOT NULL,
ask INTEGER NOT NULL,
......@@ -66,23 +64,13 @@ CREATE INDEX jiveRoGrps_rid_idx ON jiveRosterGroups (rosterID ASC);
CREATE TABLE jiveVCard (
userID INTEGER NOT NULL,
username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL,
propValue VARCHAR(2000) NOT NULL,
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 (
chatbotID INTEGER NOT NULL,
description VARCHAR(255),
......@@ -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 (
groupID INTEGER NOT NULL,
name VARCHAR(50) NOT NULL,
......
......@@ -3,49 +3,47 @@
// $Date$
CREATE TABLE jiveUser (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL,
name VARCHAR(100),
nameVisible INTEGER NOT NULL,
email VARCHAR(100),
emailVisible INTEGER NOT NULL,
creationDate 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 TABLE jiveUserProp (
userID BIGINT NOT NULL,
username VARHCAR(32) NOT NULL,
name VARCHAR(100) NOT NULL,
propValue VARCHAR(4000) NOT NULL,
CONSTRAINT jiveUserProp_pk PRIMARY KEY (userID, name)
CONSTRAINT jiveUserProp_pk PRIMARY KEY (username, name)
);
CREATE TABLE jivePrivate (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL,
namespace VARCHAR(200) 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 (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
messageID BIGINT NOT NULL,
creationDate VARCHAR(15) NOT NULL,
messageSize INTEGER NOT NULL,
message LONGVARCHAR NOT NULL,
CONSTRAINT jiveOffline_pk PRIMARY KEY (userID, messageID)
CONSTRAINT jiveOffline_pk PRIMARY KEY (username, messageID)
);
CREATE TABLE jiveRoster (
rosterID BIGINT NOT NULL,
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
jid VARCHAR(3071) NOT NULL,
sub INTEGER NOT NULL,
ask INTEGER NOT NULL,
......@@ -53,7 +51,7 @@ CREATE TABLE jiveRoster (
nick VARCHAR(255),
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 (
......@@ -66,10 +64,10 @@ CREATE INDEX jiveRosterGroup_rosterid_idx ON jiveRosterGroups (rosterID);
CREATE TABLE jiveVCard (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
name VARCHAR(100) 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 (
);
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 (
groupID BIGINT NOT NULL,
name VARCHAR(50) NOT NULL,
......@@ -126,9 +104,9 @@ CREATE TABLE jiveGroupProp (
CREATE TABLE jiveGroupUser (
groupID BIGINT NOT NULL,
userID BIGINT NOT NULL,
username BIGINT 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);
INSERT INTO jiveID (idType, id) VALUES (23, 1);
// Entry for admin user -- password is "admin"
INSERT INTO jiveUserID (username, domainID, objectType, objectID) VALUES ('admin', 1, 0, 1);
INSERT INTO jiveUser (userID, name, password, email, emailVisible, nameVisible, creationDate, modificationDate)
VALUES (1, 'Administrator', 'admin', 'admin@example.com', 1, 1, '0', '0');
// 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);
INSERT INTO jiveUser (username, password, name, email, creationDate, modificationDate)
VALUES ('admin', 'admin', 'Administrator', 'admin@example.com', '0', '0');
\ No newline at end of file
......@@ -3,53 +3,75 @@
# $Date$
CREATE TABLE jiveUser (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL,
name VARCHAR(100),
nameVisible TINYINT NOT NULL,
email VARCHAR(100),
emailVisible TINYINT NOT NULL,
creationDate CHAR(15) NOT NULL,
modificationDate CHAR(15) NOT NULL,
PRIMARY KEY (userID),
PRIMARY KEY (username),
INDEX jiveUser_cDate_idx (creationDate)
);
CREATE TABLE jiveUserProp (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
name VARCHAR(100) 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,
administrator TINYINT NOT NULL,
PRIMARY KEY (groupID, userID, administrator)
);
CREATE TABLE jivePrivate (
username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL,
namespace VARCHAR(200) NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (userID, name, namespace)
PRIMARY KEY (username, name, namespace)
);
CREATE TABLE jiveOffline (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
messageID BIGINT NOT NULL,
creationDate CHAR(15) NOT NULL,
messageSize INTEGER NOT NULL,
message TEXT NOT NULL,
PRIMARY KEY (userID, messageID)
PRIMARY KEY (username, messageID)
);
CREATE TABLE jiveRoster (
rosterID BIGINT NOT NULL,
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
jid TEXT NOT NULL,
sub TINYINT NOT NULL,
ask TINYINT NOT NULL,
recv TINYINT NOT NULL,
nick VARCHAR(255),
PRIMARY KEY (rosterID),
INDEX jiveRoster_userid_idx (userID)
INDEX jiveRoster_unameid_idx (username)
);
CREATE TABLE jiveRosterGroups (
......@@ -61,19 +83,10 @@ CREATE TABLE jiveRosterGroups (
);
CREATE TABLE jiveVCard (
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
name VARCHAR(100) NOT NULL,
propValue TEXT NOT NULL,
PRIMARY KEY (userID, 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)
PRIMARY KEY (username, name)
);
CREATE TABLE jiveChatbot (
......@@ -84,40 +97,6 @@ CREATE TABLE jiveChatbot (
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 (
idType INTEGER NOT NULL,
id BIGINT NOT NULL,
......@@ -198,18 +177,12 @@ INSERT INTO jiveID (idType, id) VALUES (23, 1);
CREATE TABLE jiveUserPerm (
objectType INTEGER NOT NULL,
objectID BIGINT NOT NULL,
userID BIGINT NOT NULL,
username VARCHAR(32) NOT NULL,
permission INTEGER NOT NULL,
INDEX jiveUserPerm_object_idx (objectType, objectID),
INDEX jiveUserPerm_userID_idx (userID)
INDEX jiveUserPerm_uname_idx (username)
);
# Entry for admin user -- password is "admin"
INSERT INTO jiveUserID (username, domainID, objectType, objectID) VALUES ('admin', 1, 0, 1);
INSERT INTO jiveUser (userID, name, password, email, emailVisible, nameVisible, creationDate, modificationDate)
VALUES (1, 'Administrator', 'admin', 'admin@example.com', 1, 1, '0', '0');
# 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);
INSERT INTO jiveUser (username, password, name, email, creationDate, modificationDate)
VALUES ('admin', 'admin', 'Administrator', 'admin@example.com', '0', '0');
\ 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;
/**
* <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 {
* messages stay in the message store and will be available to other
* 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
* @throws UnauthorizedException If the user is not allowed to retrieve messages
*/
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;
Iterator getMessages(String username) throws UnauthorizedException, UserNotFoundException;
/**
* <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
* @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
* @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(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 {
*
* @return the presence owner.
*/
public long getUserID();
public String getUsername();
/**
* Return the time when the presence was created.
......@@ -210,4 +210,4 @@ public interface Presence extends XMPPPacket {
* @throws UnauthorizedException If the caller doesn't have the appropriate authorization
*/
public void setPriority(int priority) throws UnauthorizedException;
}
}
\ No newline at end of file
......@@ -14,6 +14,7 @@ package org.jivesoftware.messenger;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.User;
import java.util.Iterator;
import java.util.Collection;
/**
* The presence manager tracks on a global basis who's online. The presence
......@@ -43,14 +44,6 @@ public interface PresenceManager {
*/
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
* presence status other that online or idle will not be included.
......@@ -60,33 +53,33 @@ public interface PresenceManager {
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.
*
* @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.
*
* @param ascending sort ascending if true, descending if false.
* @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.
*
* @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 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
......@@ -133,4 +126,4 @@ public interface PresenceManager {
* @param probee The XMPPAddress whos presence we would like sent have have probed
*/
public void probePresence(XMPPAddress prober, XMPPAddress probee) throws UnauthorizedException;
}
}
\ No newline at end of file
......@@ -46,11 +46,11 @@ public interface PrivateStore {
* <p>If the name and namespace of the element matches another
* stored private data XML document, then replace it with the new one.</p>
*
* @param data The data to store (XML element)
* @param userID The user ID of account where private data is being stored
* @param data the data to store (XML element)
* @param username the username of the account where private data is being stored
* @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
......@@ -62,9 +62,9 @@ public interface PrivateStore {
* <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 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
* @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 {
return null;
}
public void setAuthToken(AuthToken auth,
UserManager userManager,
String resource) {
public void setAuthToken(AuthToken auth, UserManager userManager, String resource) {
}
public void setAnonymousAuth() throws UnauthorizedException {
......@@ -77,8 +75,8 @@ public class ServerSession implements Session {
return streamID;
}
public long getUserID() throws UserNotFoundException, UnauthorizedException {
return 0;
public String getUsername() throws UserNotFoundException, UnauthorizedException {
return null;
}
public String getServerName() {
......
......@@ -144,15 +144,15 @@ public interface Session extends RoutableChannelHandler {
public StreamID getStreamID();
/**
* <p>Obtain the user ID associated with this session.</p>
* <p>Use this information with the user manager to obtain the
* user based on ID.</p>
* Returns the username associated with this session. Use this information
* with the user manager to obtain the user based on username.
*
* @return The user ID associated with this session
* @throws UserNotFoundException if a user is not associated with a session (the session has not authenticated yet)
* @throws UnauthorizedException If caller doesn't have permission to access this information
* @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 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.
......
......@@ -46,19 +46,6 @@ public class SessionResultFilter {
*/
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
// ############################################################
......@@ -101,6 +88,8 @@ public class SessionResultFilter {
private long serverPacketRangeMin = NO_PACKET_LIMIT;
private long serverPacketRangeMax = NO_PACKET_LIMIT;
private String username = null;
/**
* The starting index for results. Default is 0.
*/
......@@ -112,32 +101,29 @@ public class SessionResultFilter {
*/
private int numResults = NO_RESULT_LIMIT;
private long userID = ALL_USER_ID;
private Date creationDateRangeMin = null;
private Date creationDateRangeMax = null;
private Date lastActivityDateRangeMin = null;
private Date lastActivityDateRangeMax = null;
/**
* Returns the userID that results will be filtered on. The method will
* return ALL_USER_ID if no user to filter on has been specified. The method
* will return ANONYMOUS_USER_ID if filtering is to take place on all "anonymous" users.
* Returns the username that results will be filtered on. The method will
* return <tt>null</tt> if no user to filter on has been specified.
*
* @return the userID that results will be filtered on.
* @return the username that results will be filtered on.
*/
public long getUserID() {
return userID;
public String getUsername() {
return username;
}
/**
* Sets the userID that results will be filtered on. If you'd like to filter
* on "anonymous" users, pass in an id of ANONYMOUS_USER_ID. By default, no filtering on
* userID's will take place. To avoid filtering on userID pass ALL_USER_ID.
* Sets the username that results will be filtered on. By default, no filtering on
* username will take place. To avoid filtering on username pass in <tt>null</tt>.
*
* @param userID the user ID to filter on.
* @param username the user ID to filter on.
*/
public void setUserID(long userID) {
this.userID = userID;
public void setUsername(String username) {
this.username = username;
}
/**
......@@ -145,8 +131,7 @@ public class SessionResultFilter {
* sessions to be filtered on. If this value has not been set, the method
* will return null.
*
* @return a Date representing the lower bound for creation dates to filter
* on.
* @return a Date representing the lower bound for creation dates to filter on.
*/
public Date getCreationDateRangeMin() {
return creationDateRangeMin;
......@@ -575,7 +560,7 @@ public class SessionResultFilter {
clonedFilter.setSortField(getSortField());
clonedFilter.setSortOrder(getSortOrder());
clonedFilter.setStartIndex(getStartIndex());
clonedFilter.setUserID(getUserID());
clonedFilter.setUsername(getUsername());
return clonedFilter;
}
......@@ -590,7 +575,7 @@ public class SessionResultFilter {
sortOrder == o.sortOrder &&
startIndex == o.startIndex &&
numResults == o.numResults &&
userID == o.userID &&
username == o.username &&
((creationDateRangeMin == null && o.creationDateRangeMin == null) ||
creationDateRangeMin.equals(o.creationDateRangeMin)) &&
((creationDateRangeMax == null && o.creationDateRangeMax == null) ||
......
......@@ -17,7 +17,6 @@ import org.jivesoftware.messenger.disco.IQDiscoItemsHandler;
import org.jivesoftware.messenger.muc.spi.MultiUserChatServerImpl;
import org.jivesoftware.messenger.audit.spi.AuditManagerImpl;
import org.jivesoftware.messenger.auth.spi.GroupManagerImpl;
import org.jivesoftware.messenger.chatbot.spi.ChatbotManagerImpl;
import org.jivesoftware.messenger.handler.*;
import org.jivesoftware.messenger.spi.*;
import org.jivesoftware.messenger.transport.TransportHandler;
......@@ -41,9 +40,7 @@ public class XMPPBootContainer extends BootstrapContainer {
return new String[]{
BasicServer.class.getName(),
RoutingTableImpl.class.getName(),
NameIDManagerImpl.class.getName(),
AuditManagerImpl.class.getName(),
ChatbotManagerImpl.class.getName(),
UserManagerImpl.class.getName(),
RosterManagerImpl.class.getName(),
DbPrivateStore.class.getName()};
......
......@@ -15,9 +15,6 @@ import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;
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.NoSuchAlgorithmException;
......@@ -50,7 +47,6 @@ public abstract class AuthFactory {
*/
public static final String SESSION_AUTHORIZATION = "jive.authToken";
private static UserIDProvider userIDProvider = null;
private static AuthProvider authProvider = null;
private static MessageDigest sha;
......@@ -62,8 +58,6 @@ public abstract class AuthFactory {
*/
static {
authProvider = AuthProviderFactory.getAuthProvider();
userIDProvider = UserProviderFactory.getUserIDProvider();
try {
sha = MessageDigest.getInstance("SHA");
}
......@@ -119,14 +113,10 @@ public abstract class AuthFactory {
* @throws UnauthorizedException if the username and password do not match any existing user.
*/
public static AuthToken getAuthToken(String username, String password)
throws UnauthorizedException {
throws UnauthorizedException
{
authProvider.authenticate(username, password);
try {
return new AuthTokenImpl(userIDProvider.getUserID(username));
}
catch (UserNotFoundException e) {
throw new UnauthorizedException("User " + username + " authenticated but no ID found", e);
}
return new AuthTokenImpl(username);
}
/**
......@@ -144,19 +134,13 @@ public abstract class AuthFactory {
public static AuthToken getAuthToken(String username, String token, String digest)
throws UnauthorizedException {
authProvider.authenticate(username, token, digest);
try {
return new AuthTokenImpl(userIDProvider.getUserID(username));
}
catch (UserNotFoundException e) {
throw new UnauthorizedException("User " + username + " digest authenticated but no ID found", e);
}
return new AuthTokenImpl(username);
}
/**
* 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.
......
......@@ -28,11 +28,11 @@ package org.jivesoftware.messenger.auth;
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.
......
......@@ -11,8 +11,9 @@
package org.jivesoftware.messenger.auth;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.User;
import java.util.Date;
import java.util.Iterator;
......@@ -30,8 +31,6 @@ import java.util.Iterator;
* Security for Group objects is provide by GroupProxy protection proxy objects.
*
* @author Iain Shigeoka
*
* @see Entity
*/
public interface Group {
......@@ -156,52 +155,52 @@ public interface Group {
* Grants administrator privileges of the group to a user. 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.
*/
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.
* 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.
*/
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
* 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.
*/
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
* in the group, this method does nothing. This method
* 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.
*/
public void removeMember(Entity entity) throws UnauthorizedException;
public void removeMember(User user) throws UnauthorizedException;
/**
* Returns true if the User has group administrator permissions.
*
* @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.
*
* @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.
......
......@@ -12,7 +12,8 @@
package org.jivesoftware.messenger.auth;
import org.jivesoftware.util.BasicResultFilter;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.user.User;
import java.util.Iterator;
/**
......@@ -105,8 +106,8 @@ public interface GroupManager {
/**
* 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.
*/
public Iterator getGroups(Entity entity);
public Iterator getGroups(User user);
}
\ No newline at end of file
......@@ -116,17 +116,17 @@ public interface GroupProvider {
* <p>Obtain an list of all Group IDs known by the provider
* 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
*/
LongList getGroups(long entityID);
LongList getGroups(String username);
/**
* <p>Creates a membership relationship between the
* group and the entity (optional operation).</p>
*
* @param groupID The group to add the member to
* @param entityID The entity to add
* @param groupID the group to add the member to
* @param username the username to add
* @param administrator True if the member is an administrator of the group
* @throws UnauthorizedException If the password is invalid or
* the caller does not have permission to make the change
......@@ -135,7 +135,7 @@ public interface GroupProvider {
* @throws UserAlreadyExistsException If the given entity is already a member
* of the group
*/
void createMember(long groupID, long entityID, boolean administrator)
void createMember(long groupID, String username, boolean administrator)
throws UnauthorizedException,
UserAlreadyExistsException,
UnsupportedOperationException;
......@@ -145,28 +145,26 @@ public interface GroupProvider {
* group and the entity (optional operation).</p>
*
* @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
* @throws UnauthorizedException If the password is invalid or
* the caller does not have permission to make the change
* @throws UnsupportedOperationException If the provider does not
* 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;
/**
* <p>Deletes a membership relationship between the
* group and the entity (optional operation).</p>
* Deletes a membership relationship between the group and the user (optional operation).
*
* @param groupID The group to add the member to
* @param entityID The entity to add
* @throws UnauthorizedException If the password is invalid or
* the caller does not have permission to make the change
* @throws UnsupportedOperationException If the provider does not
* support the operation (this is an optional operation)
* @param groupID the group.
* @param username the username.
* @throws UnauthorizedException if does not have permission to make the change.
* @throws UnsupportedOperationException if the provider does not
* support the operation (this is an optional operation).
*/
void deleteMember(long groupID, long entityID)
void deleteMember(long groupID, String username)
throws UnauthorizedException, UnsupportedOperationException;
/**
......@@ -185,7 +183,7 @@ public interface GroupProvider {
* @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
*/
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
......@@ -196,17 +194,17 @@ public interface GroupProvider {
* @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
*/
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>
*
* @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
* @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>
......@@ -225,9 +223,9 @@ public interface GroupProvider {
/**
* <p>Updates a property on a group (optional operation).</p>
*
* @param groupID The ID of the group
* @param name The name of the property
* @param value The value of the property
* @param groupID the ID of the group.
* @param name the name of the property.
* @param value the value of the property.
* @throws UnauthorizedException If the password is invalid or
* the caller does not have permission to make the change
* @throws UnsupportedOperationException If the provider does not
......@@ -248,4 +246,4 @@ public interface GroupProvider {
*/
void deleteProperty(long groupID, String name)
throws UnauthorizedException, UnsupportedOperationException;
}
}
\ No newline at end of file
......@@ -23,24 +23,24 @@ public final class AuthTokenImpl implements AuthToken, Serializable {
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) {
this.userID = userID;
public AuthTokenImpl(String username) {
this.username = username;
}
// AuthToken Interface
public long getUserID() {
return userID;
public String getUsername() {
return username;
}
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;
import org.jivesoftware.messenger.auth.AuthProvider;
import org.jivesoftware.messenger.auth.UnauthorizedException;
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;
......@@ -53,21 +51,12 @@ import java.sql.SQLException;
*/
public class DbAuthProvider implements AuthProvider {
/**
* DATABASE QUERIES *
*/
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 =
"SELECT password FROM jiveUser WHERE userID=?";
"SELECT password FROM jiveUser WHERE username=?";
private static final String UPDATE_PASSWORD =
"UPDATE jiveUser set password=? WHERE userID=?";
/**
* <p>Used to map usernames to ids.</p>
*/
private DbUserIDProvider idProvider = new DbUserIDProvider();
"UPDATE jiveUser set password=? WHERE username=?";
/**
* <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 {
throw new UnauthorizedException();
}
username = NodePrep.prep(username);
long userID = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
userID = idProvider.getUserID(username);
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(AUTHORIZE);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
......@@ -101,14 +88,12 @@ public class DbAuthProvider implements AuthProvider {
if (!rs.next()) {
throw new UnauthorizedException();
}
rs.close();
}
catch (SQLException e) {
Log.error("Exception in DbAuthProvider", e);
throw new UnauthorizedException();
}
catch (UserNotFoundException e) {
throw new UnauthorizedException();
}
finally {
try { if (pstmt != null) pstmt.close(); }
catch (Exception e) { Log.error(e); }
......@@ -135,14 +120,12 @@ public class DbAuthProvider implements AuthProvider {
throw new UnauthorizedException();
}
username = NodePrep.prep(username);
long userID = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
userID = idProvider.getUserID(username);
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(SELECT_PASSWORD);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
......@@ -156,27 +139,17 @@ public class DbAuthProvider implements AuthProvider {
if (!digest.equalsIgnoreCase(anticipatedDigest)) {
throw new UnauthorizedException();
}
rs.close();
}
catch (SQLException e) {
Log.error("Exception in DbAuthProvider", e);
throw new UnauthorizedException();
}
catch (UserNotFoundException 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);
}
try { if (pstmt != null) pstmt.close(); }
catch (Exception 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.
}
......@@ -195,16 +168,13 @@ public class DbAuthProvider implements AuthProvider {
throw new UnauthorizedException();
}
username = NodePrep.prep(username);
long userID = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
userID = idProvider.getUserID(username);
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(UPDATE_PASSWORD);
pstmt.setString(1, password);
pstmt.setLong(2, userID);
pstmt.setString(2, username);
pstmt.executeUpdate();
}
catch (SQLException e) {
......@@ -212,18 +182,10 @@ public class DbAuthProvider implements AuthProvider {
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);
}
try { if (pstmt != null) pstmt.close(); }
catch (Exception e) { Log.error(e); }
try { if (con != null) con.close(); }
catch (Exception e) { Log.error(e); }
}
}
......
......@@ -16,14 +16,14 @@ import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
/**
* Database implementation of the GroupManager interface.
......@@ -56,30 +56,30 @@ public class DbGroupProvider implements GroupProvider {
private static final String INSERT_PROPERTY =
"INSERT INTO jiveGroupProp (groupID, name, propValue) VALUES (?, ?, ?)";
private static final String MEMBER_TEST =
"SELECT userID FROM jiveGroupUser " +
"WHERE groupID=? AND userID=? AND administrator=0";
"SELECT username FROM jiveGroupUser " +
"WHERE groupID=? AND username=? AND administrator=0";
private static final String ADMIN_TEST =
"SELECT userID FROM jiveGroupUser " +
"WHERE groupID=? AND userID=? AND administrator=1";
"SELECT username FROM jiveGroupUser " +
"WHERE groupID=? AND username=? AND administrator=1";
private static final String LOAD_ADMINS =
"SELECT userID FROM jiveGroupUser WHERE administrator=1 AND groupID=?";
"SELECT username FROM jiveGroupUser WHERE administrator=1 AND groupID=?";
private static final String LOAD_MEMBERS =
"SELECT userID FROM jiveGroupUser WHERE administrator=0 AND groupID=?";
"SELECT username FROM jiveGroupUser WHERE administrator=0 AND groupID=?";
private static final String GROUP_MEMBER_COUNT =
"SELECT count(*) FROM jiveGroupUser WHERE administrator =0";
"SELECT count(*) FROM jiveGroupUser WHERE administrator=0";
private static final String GROUP_ADMIN_COUNT =
"SELECT count(*) FROM jiveGroupUser WHERE administrator =1";
"SELECT count(*) FROM jiveGroupUser WHERE administrator=1";
private static final String SELECT_GROUP_BY_NAME =
"SELECT name, description, groupID, creationDate, modificationDate " +
"FROM jiveGroup WHERE name=?";
private static final String REMOVE_USER =
"DELETE FROM jiveGroupUser WHERE groupID=? AND userID=?";
"DELETE FROM jiveGroupUser WHERE groupID=? AND username=?";
private static final String UPDATE_USER =
"UPDATE jiveGroupUser SET administrator=? WHERE groupID=? userID=?";
"UPDATE jiveGroupUser SET administrator=? WHERE groupID=? username=?";
private static final String ADD_USER =
"INSERT INTO jiveGroupUser (groupID, userID, administrator) VALUES (?, ?, ?)";
"INSERT INTO jiveGroupUser (groupID, username, administrator) VALUES (?, ?, ?)";
private static final String USER_GROUPS =
"SELECT groupID FROM jiveGroupUser WHERE userID=? AND administrator=0";
"SELECT groupID FROM jiveGroupUser WHERE username=? AND administrator=0";
private static final String ALL_GROUPS = "SELECT groupID FROM jiveGroup";
public Group createGroup(String name) throws UnauthorizedException,
......@@ -119,9 +119,9 @@ public class DbGroupProvider implements GroupProvider {
}
public Group getGroup(long groupID) throws GroupNotFoundException {
Group group = null;
Connection con = null;
PreparedStatement pstmt = null;
Group group = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_GROUP_BY_ID);
......@@ -141,6 +141,7 @@ public class DbGroupProvider implements GroupProvider {
// Add in name, value as a new property.
group.setProperty(rs.getString(1), rs.getString(2));
}
rs.close();
}
}
catch (SQLException e) {
......@@ -171,9 +172,9 @@ public class DbGroupProvider implements GroupProvider {
}
public Group getGroup(String name) throws GroupNotFoundException {
Group group = null;
Connection con = null;
PreparedStatement pstmt = null;
Group group = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(SELECT_GROUP_BY_NAME);
......@@ -191,6 +192,7 @@ public class DbGroupProvider implements GroupProvider {
// Add in name, value as a new property.
group.setProperty(rs.getString(1), rs.getString(2));
}
rs.close();
}
}
catch (SQLException e) {
......@@ -216,7 +218,6 @@ public class DbGroupProvider implements GroupProvider {
group.setModificationDate(new Date());
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(SAVE_GROUP);
......@@ -243,7 +244,6 @@ public class DbGroupProvider implements GroupProvider {
Connection con = null;
PreparedStatement pstmt = null;
boolean abortTransaction = false;
try {
con = DbConnectionManager.getTransactionConnection();
// Remove all users in the group.
......@@ -274,7 +274,6 @@ public class DbGroupProvider implements GroupProvider {
int count = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(GROUP_COUNT);
......@@ -282,6 +281,7 @@ public class DbGroupProvider implements GroupProvider {
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -299,7 +299,6 @@ public class DbGroupProvider implements GroupProvider {
LongList groups = new LongList();
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_GROUPS);
......@@ -307,6 +306,7 @@ public class DbGroupProvider implements GroupProvider {
while (rs.next()) {
groups.add(rs.getLong(1));
}
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -324,7 +324,6 @@ public class DbGroupProvider implements GroupProvider {
LongList groups = new LongList();
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_GROUPS);
......@@ -344,6 +343,7 @@ public class DbGroupProvider implements GroupProvider {
break;
}
}
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -357,18 +357,19 @@ public class DbGroupProvider implements GroupProvider {
return groups;
}
public LongList getGroups(long entityID) {
public LongList getGroups(String username) {
LongList groups = new LongList();
Connection con = null;
PreparedStatement pstmt = null;
LongList groups = new LongList();
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(USER_GROUPS);
pstmt.setLong(1, entityID);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
groups.add(rs.getLong(1));
}
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -382,16 +383,16 @@ public class DbGroupProvider implements GroupProvider {
return groups;
}
public void createMember(long groupID, long entityID, boolean administrator)
throws UserAlreadyExistsException {
public void createMember(long groupID, String username, boolean administrator)
throws UserAlreadyExistsException
{
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ADD_USER);
pstmt.setLong(1, groupID);
pstmt.setLong(2, entityID);
pstmt.setString(2, username);
pstmt.setInt(3, administrator ? 1 : 0);
pstmt.executeUpdate();
}
......@@ -407,16 +408,15 @@ public class DbGroupProvider implements GroupProvider {
}
}
public void updateMember(long groupID, long entityID, boolean administrator) {
public void updateMember(long groupID, String username, boolean administrator) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(UPDATE_USER);
pstmt.setInt(1, administrator ? 1 : 0);
pstmt.setLong(2, groupID);
pstmt.setLong(3, entityID);
pstmt.setString(3, username);
pstmt.executeUpdate();
}
catch (SQLException e) {
......@@ -430,7 +430,7 @@ public class DbGroupProvider implements GroupProvider {
}
}
public void deleteMember(long groupID, long entityID) {
public void deleteMember(long groupID, String username) {
Connection con = null;
PreparedStatement pstmt = null;
......@@ -438,7 +438,7 @@ public class DbGroupProvider implements GroupProvider {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(REMOVE_USER);
pstmt.setLong(1, groupID);
pstmt.setLong(2, entityID);
pstmt.setString(2, username);
pstmt.executeUpdate();
}
catch (SQLException e) {
......@@ -456,7 +456,6 @@ public class DbGroupProvider implements GroupProvider {
int count = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
if (adminsOnly) {
......@@ -469,6 +468,7 @@ public class DbGroupProvider implements GroupProvider {
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -482,10 +482,10 @@ public class DbGroupProvider implements GroupProvider {
return count;
}
public LongList getMembers(long groupID, boolean adminsOnly) {
public String [] getMembers(long groupID, boolean adminsOnly) {
List<String> members = new ArrayList<String>();
Connection con = null;
PreparedStatement pstmt = null;
LongList members = new LongList();
try {
con = DbConnectionManager.getConnection();
if (adminsOnly) {
......@@ -497,8 +497,9 @@ public class DbGroupProvider implements GroupProvider {
pstmt.setLong(1, groupID);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
members.add(rs.getLong(1));
members.add(rs.getString(1));
}
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -509,13 +510,13 @@ public class DbGroupProvider implements GroupProvider {
try { if (con != null) con.close(); }
catch (Exception e) { Log.error(e); }
}
return members;
return (String [])members.toArray();
}
public LongList getMembers(long groupID, BasicResultFilter filter, boolean adminsOnly) {
public String [] getMembers(long groupID, BasicResultFilter filter, boolean adminsOnly) {
List<String> members = new ArrayList<String>();
Connection con = null;
PreparedStatement pstmt = null;
LongList members = new LongList();
try {
con = DbConnectionManager.getConnection();
if (adminsOnly) {
......@@ -535,12 +536,13 @@ public class DbGroupProvider implements GroupProvider {
// Now read in desired number of results
for (int i = 0; i < filter.getNumResults(); i++) {
if (rs.next()) {
members.add(rs.getLong(1));
members.add(rs.getString(1));
}
else {
break;
}
}
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -551,14 +553,13 @@ public class DbGroupProvider implements GroupProvider {
try { if (con != null) con.close(); }
catch (Exception e) { Log.error(e); }
}
return members;
return (String [])members.toArray();
}
public boolean isMember(long groupID, long entityID, boolean adminsOnly) {
public boolean isMember(long groupID, String username, boolean adminsOnly) {
boolean member = false;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
if (adminsOnly) {
......@@ -568,10 +569,11 @@ public class DbGroupProvider implements GroupProvider {
pstmt = con.prepareStatement(MEMBER_TEST);
}
pstmt.setLong(1, groupID);
pstmt.setLong(2, entityID);
pstmt.setString(2, username);
ResultSet rs = pstmt.executeQuery();
// If there is a result, then the user is a member of the group.
member = rs.next();
rs.close();
}
catch (SQLException e) {
Log.error(e);
......@@ -588,7 +590,6 @@ public class DbGroupProvider implements GroupProvider {
public void createProperty(long groupID, String name, String value) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(INSERT_PROPERTY);
......@@ -611,7 +612,6 @@ public class DbGroupProvider implements GroupProvider {
public void updateProperty(long groupID, String name, String value) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(UPDATE_PROPERTY);
......@@ -634,7 +634,6 @@ public class DbGroupProvider implements GroupProvider {
public void deleteProperty(long groupID, String name) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(DELETE_PROPERTY);
......
......@@ -15,9 +15,9 @@ import org.jivesoftware.util.CacheManager;
import org.jivesoftware.util.CacheSizes;
import org.jivesoftware.util.Cache;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.spi.UserIterator;
import java.util.*;
......@@ -39,8 +39,8 @@ public class GroupImpl implements Group, Cacheable {
private Date creationDate;
private Date modificationDate;
private Map properties;
private long[] memberList;
private long[] adminList;
private String[] memberList;
private String[] adminList;
private Cache groupCache;
private Cache groupMemberCache;
......@@ -53,11 +53,9 @@ public class GroupImpl implements Group, Cacheable {
* @param created The date-time the group was created
* @param modified The date-time the group was last modified
*/
GroupImpl(long id,
String groupName,
String groupDescription,
Date created,
Date modified) {
GroupImpl(long id, String groupName, String groupDescription, Date created,
Date modified)
{
groupID = id;
name = groupName;
description = groupDescription;
......@@ -181,16 +179,15 @@ public class GroupImpl implements Group, Cacheable {
return Collections.unmodifiableSet(properties.keySet()).iterator();
}
public void addAdministrator(Entity entity)
public void addAdministrator(User user)
throws UnauthorizedException, UserAlreadyExistsException {
// If the user is already an administrator, do nothing.
if (isAdministrator(entity)) {
throw new UserAlreadyExistsException("User " + entity.getUsername() + "with ID " + entity.getID() +
if (isAdministrator(user)) {
throw new UserAlreadyExistsException("User " + user.getUsername() +
" already is a member of the group");
}
long userID = entity.getID();
provider.createMember(groupID, userID, true);
String username = user.getUsername();
provider.createMember(groupID, username, true);
try {
provider.updateGroup(this);
}
......@@ -201,22 +198,22 @@ public class GroupImpl implements Group, Cacheable {
// Changed admins, so reset admin list
adminList = null;
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.
// This is handled via a listener for the GroupEvent.GROUP_ADMINISTRATOR_ADD event
// fire off an event
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 (isAdministrator(entity)) {
if (isAdministrator(user)) {
long userID = entity.getID();
provider.deleteMember(groupID, userID);
String username = user.getUsername();
provider.deleteMember(groupID, username);
try {
provider.updateGroup(this);
}
......@@ -229,23 +226,23 @@ public class GroupImpl implements Group, Cacheable {
groupCache.put(new Long(groupID), this);
// Remove user from admin cache
groupMemberCache.remove(groupID + ",admin," + userID);
groupMemberCache.remove(groupID + ",admin," + username);
// Now, clear the permissions cache.
// 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 {
// Don't do anything if the user is already a member of the group.
if (isMember(entity)) {
throw new UserAlreadyExistsException("User " + entity.getUsername() + "with ID " + entity.getID() +
" already is a member of the group");
if (isMember(user)) {
throw new UserAlreadyExistsException("User " + user.getUsername() +
" is already a member of the group");
}
String username = user.getUsername();
long userID = entity.getID();
provider.createMember(groupID, userID, false);
provider.createMember(groupID, username, false);
try {
provider.updateGroup(this);
}
......@@ -258,59 +255,59 @@ public class GroupImpl implements Group, Cacheable {
groupCache.put(new Long(groupID), this);
// 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.
groupMemberCache.remove("userGroups-" + userID);
groupMemberCache.remove("userGroups-" + username);
// Now, clear the permissions cache.
// 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.
if (!isMember(entity)) {
if (!isMember(user)) {
return;
}
long userID = entity.getID();
provider.deleteMember(groupID, userID);
String username = user.getUsername();
provider.deleteMember(groupID, username);
// Changed membership, so reset member list
memberList = null;
groupCache.put(new Long(groupID), this);
// 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.
groupMemberCache.remove("userGroups-" + userID);
groupMemberCache.remove("userGroups-" + username);
// Now, clear the permissions cache.
// This is handled via a listener for the GroupEvent.GROUP_USER_DELETE event
}
public boolean isAdministrator(Entity entity) {
long userID = entity.getID();
public boolean isAdministrator(User user) {
String username = user.getUsername();
Boolean bool = null;
bool = (Boolean)groupMemberCache.get(groupID + ",admin," + userID);
bool = (Boolean)groupMemberCache.get(groupID + ",admin," + username);
if (bool == null) {
bool = new Boolean(provider.isMember(groupID, userID, true));
bool = new Boolean(provider.isMember(groupID, username, true));
// Add to cache
groupMemberCache.put(groupID + ",admin," + userID, bool);
groupMemberCache.put(groupID + ",admin," + username, bool);
}
return bool.booleanValue();
}
public boolean isMember(Entity entity) {
long userID = entity.getID();
public boolean isMember(User user) {
String username = user.getUsername();
Boolean bool = null;
bool = (Boolean)groupMemberCache.get(groupID + ",member," + userID);
bool = (Boolean)groupMemberCache.get(groupID + ",member," + username);
if (bool == null) {
bool = new Boolean(provider.isMember(groupID, userID, false));
bool = new Boolean(provider.isMember(groupID, username, false));
// Add to cache
groupMemberCache.put(groupID + ",member," + userID, bool);
groupMemberCache.put(groupID + ",member," + username, bool);
}
return bool.booleanValue();
}
......@@ -333,7 +330,7 @@ public class GroupImpl implements Group, Cacheable {
public Iterator members() {
if (memberList == null) {
memberList = provider.getMembers(groupID, false).toArray();
memberList = provider.getMembers(groupID, false);
// Re-add group to cache.
groupCache.put(new Long(groupID), this);
}
......@@ -349,7 +346,7 @@ public class GroupImpl implements Group, Cacheable {
public Iterator administrators() {
if (adminList == null) {
adminList = provider.getMembers(groupID, true).toArray();
adminList = provider.getMembers(groupID, true);
// Re-add group to cache.
groupCache.put(new Long(groupID), this);
}
......@@ -364,15 +361,15 @@ public class GroupImpl implements Group, Cacheable {
}
public Permissions getPermissions(AuthToken auth) {
long userID = auth.getUserID();
String username = auth.getUsername();
try {
Boolean bool = null;
bool = (Boolean)groupMemberCache.get(groupID + ",admin," + userID);
bool = (Boolean)groupMemberCache.get(groupID + ",admin," + username);
if (bool == null) {
bool = new Boolean(provider.isMember(groupID, userID, true));
bool = new Boolean(provider.isMember(groupID, username, true));
// Add to cache
groupMemberCache.put(groupID + ",admin," + userID, bool);
groupMemberCache.put(groupID + ",admin," + username, bool);
}
if (bool.booleanValue()) {
......
......@@ -16,7 +16,6 @@ import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.messenger.container.Container;
import org.jivesoftware.util.Cache;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.User;
import java.util.Iterator;
......@@ -87,12 +86,12 @@ public class GroupManagerImpl extends BasicModule implements GroupManager {
public void deleteGroup(Group group) throws UnauthorizedException {
long groupID = group.getID();
long[] members = new long[group.getMemberCount()];
String[] members = new String[group.getMemberCount()];
Iterator iter = group.members();
for (int i = 0; i < members.length; i++) {
User user = (User)iter.next();
members[i] = user.getID();
members[i] = user.getUsername();
}
provider.deleteGroup(group.getID());
......@@ -122,14 +121,14 @@ public class GroupManagerImpl extends BasicModule implements GroupManager {
return new GroupIterator(this, groups.toArray());
}
public Iterator getGroups(Entity entity) {
long userID = entity.getID();
String key = "userGroups-" + userID;
public Iterator getGroups(User user) {
String username = user.getUsername();
String key = "userGroups-" + username;
// Look in the group membership cache for the value.
long[] groups = (long[])groupMemberCache.get(key);
if (groups == null) {
groups = provider.getGroups(entity.getID()).toArray();
groups = provider.getGroups(username).toArray();
}
return new GroupIterator(this, groups);
}
......
......@@ -13,9 +13,10 @@ package org.jivesoftware.messenger.auth.spi;
import org.jivesoftware.util.BasicResultFilter;
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.spi.UserGroupIteratorProxy;
import org.jivesoftware.messenger.user.User;
import java.util.Iterator;
/**
......@@ -90,8 +91,8 @@ public class GroupManagerProxy implements GroupManager {
return new UserGroupIteratorProxy(JiveConstants.GROUP, iterator, auth, permissions);
}
public Iterator getGroups(Entity entity) {
Iterator iterator = groupManager.getGroups(entity);
public Iterator getGroups(User user) {
Iterator iterator = groupManager.getGroups(user);
return new UserGroupIteratorProxy(JiveConstants.GROUP, iterator, auth, permissions);
}
}
......@@ -11,12 +11,12 @@
package org.jivesoftware.messenger.auth.spi;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.AuthToken;
import org.jivesoftware.messenger.auth.Group;
import org.jivesoftware.messenger.auth.Permissions;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.spi.UserIteratorProxy;
import java.util.Date;
import java.util.Iterator;
......@@ -126,54 +126,54 @@ public class GroupProxy implements Group {
return group.getPropertyNames();
}
public void addAdministrator(Entity entity)
public void addAdministrator(User user)
throws UnauthorizedException, UserAlreadyExistsException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) {
group.addAdministrator(entity);
group.addAdministrator(user);
}
else {
throw new UnauthorizedException();
}
}
public void removeAdministrator(Entity entity) throws UnauthorizedException {
public void removeAdministrator(User user) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) {
group.removeAdministrator(entity);
group.removeAdministrator(user);
}
else {
throw new UnauthorizedException();
}
}
public void addMember(Entity entity)
public void addMember(User user)
throws UnauthorizedException, UserAlreadyExistsException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) {
group.addMember(entity);
group.addMember(user);
}
else {
throw new UnauthorizedException();
}
}
public void removeMember(Entity entity) throws UnauthorizedException {
public void removeMember(User user) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN
| Permissions.GROUP_ADMIN)) {
group.removeMember(entity);
group.removeMember(user);
}
else {
throw new UnauthorizedException();
}
}
public boolean isAdministrator(Entity entity) {
return group.isAdministrator(entity);
public boolean isAdministrator(User user) {
return group.isAdministrator(user);
}
public boolean isMember(Entity entity) {
return group.isMember(entity);
public boolean isMember(User user) {
return group.isMember(user);
}
public int getAdministratorCount() {
......@@ -199,4 +199,4 @@ public class GroupProxy implements Group {
public boolean isAuthorized(long 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
if (IQ.GET.equals(packet.getType())) {
replyPacket = packet.createResult();
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);
}
else {
privateStore.add(packet.getOriginatingSession().getUserID(), dataElement);
privateStore.add(packet.getOriginatingSession().getUsername(), dataElement);
replyPacket = packet.createResult();
}
}
......
......@@ -177,7 +177,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
reply = packet.createResult();
if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
try {
User user = userManager.getUser(session.getUserID());
User user = userManager.getUser(session.getUsername());
MetaDataFragment currentRegistration = (MetaDataFragment) probeResult
.createDeepCopy();
currentRegistration.setProperty("query.registered", null);
......@@ -191,15 +191,6 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
form.getField("username").addValue(user.getUsername());
form.getField("name").addValue(user.getInfo().getName());
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);
}
catch (UserNotFoundException e) {
......@@ -228,7 +219,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
presence.setSender(packet.getSender());
presenceHandler.process(presence);
// Delete the user
userManager.deleteUser(session.getUserID());
userManager.deleteUser(userManager.getUser(session.getUsername()));
reply = packet.createResult();
session.getConnection().deliver(reply);
// Close the user's connection
......@@ -290,7 +281,7 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
}
if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
User user = userManager.getUser(session.getUserID());
User user = userManager.getUser(session.getUsername());
if (user != null) {
if (user.getUsername().equalsIgnoreCase(username)) {
user.setPassword(password);
......@@ -324,17 +315,6 @@ public class IQRegisterHandler extends IQHandler implements ServerFeaturesProvid
String name = (values.hasNext() ? values.next() : " ");
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();
}
......
......@@ -17,7 +17,6 @@ import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.Chatbot;
import org.jivesoftware.messenger.user.*;
import org.jivesoftware.messenger.user.spi.IQRosterItemImpl;
import java.util.ArrayList;
......@@ -151,7 +150,7 @@ public class IQRosterHandler extends IQHandler implements ServerFeaturesProvider
XMPPPacket.Type type = packet.getType();
try {
User sessionUser = userManager.getUser(session.getUserID());
User sessionUser = userManager.getUser(session.getUsername());
CachedRoster cachedRoster = (CachedRoster)sessionUser.getRoster();
if (IQ.GET == type) {
returnPacket = cachedRoster.getReset();
......@@ -226,15 +225,6 @@ public class IQRosterHandler extends IQHandler implements ServerFeaturesProvider
recipientRoster.deleteRosterItem(sender);
}
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
......
......@@ -71,7 +71,7 @@ public class IQvCardHandler extends IQHandler {
XMPPAddress recipient = packet.getRecipient();
XMPPPacket.Type type = packet.getType();
if (type.equals(IQ.SET)) {
User user = userManager.getUser(packet.getOriginatingSession().getUserID());
User user = userManager.getUser(packet.getOriginatingSession().getUsername());
// Proper format
Element vcard = ((XMPPDOMFragment)packet.getChildFragment()).getRootElement();
if (vcard != null) {
......
......@@ -18,7 +18,6 @@ import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotManager;
import org.jivesoftware.messenger.user.*;
import org.jivesoftware.messenger.user.spi.CachedRosterImpl;
import java.util.Hashtable;
......@@ -88,22 +87,16 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand
if (roster != null) {
manageSub(senderJID, false, type, roster);
}
if (chatbotManager.isChatbot(recipientJID)) {
RoutableChannelHandler route = routingTable.getRoute(recipientJID);
route.process((XMPPPacket)presence.createDeepCopy());
try {
// 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());
}
else {
try {
// 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 (NoSuchRouteException e) {
deliverer.deliver((XMPPPacket)presence.createDeepCopy());
}
}
catch (Exception e) {
......@@ -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
*/
private Roster getRoster(XMPPAddress address) {
Long userID = null;
String username = null;
Roster roster = null;
if (localServer.isLocal(address) && !"".equals(address.getName())) {
try {
if (chatbotManager != null) {
if (chatbotManager.isChatbot(address)) {
userID = chatbotManager.getChatbotID(address.getNamePrep());
}
}
}
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);
}
username = address.getNamePrep();
// Check for a cached roster:
roster = (Roster)CacheManager.getCache("username2roster").get(username);
if (roster == null) {
// Not in cache so load a new one:
roster = new CachedRosterImpl(username);
CacheManager.getCache("username2roster").put(username, roster);
}
}
return 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
......@@ -163,11 +136,9 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand
* @param type The subscription change type (subscribe, unsubscribe, etc.)
* @throws UnauthorizedException If a security access violation occurs
*/
private void manageSub(XMPPAddress target,
boolean isSending,
XMPPPacket.Type type,
Roster roster)
throws UnauthorizedException, UserAlreadyExistsException {
private void manageSub(XMPPAddress target, boolean isSending, XMPPPacket.Type type,
Roster roster) throws UnauthorizedException, UserAlreadyExistsException
{
try {
RosterItem item;
if (roster.isRosterItem(target)) {
......@@ -388,12 +359,10 @@ public class PresenceSubscribeHandler extends BasicModule implements ChannelHand
public XMPPServer localServer;
public PacketDeliverer deliverer;
public PacketFactory packetFactory;
public ChatbotManager chatbotManager;
protected TrackInfo getTrackInfo() {
TrackInfo trackInfo = new TrackInfo();
trackInfo.getTrackerClasses().put(UserManager.class, "userManager");
trackInfo.getTrackerClasses().put(ChatbotManager.class, "chatbotManager");
trackInfo.getTrackerClasses().put(RoutingTable.class, "routingTable");
trackInfo.getTrackerClasses().put(XMPPServer.class, "localServer");
trackInfo.getTrackerClasses().put(PacketDeliverer.class, "deliverer");
......
......@@ -180,8 +180,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
// Only user sessions need to be authenticated
if (!"".equals(session.getAddress().getName())) {
String username = session.getAddress().getNamePrep();
long userID = nameManager.getID(username);
CachedRoster roster = rosterManager.getRoster(userID);
CachedRoster roster = rosterManager.getRoster(username);
Iterator items = roster.getRosterItems();
while (items.hasNext()) {
RosterItem item = (RosterItem)items.next();
......@@ -197,7 +196,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
}
}
// deliver offline messages if any
Iterator msgs = messageStore.getMessages(userID);
Iterator msgs = messageStore.getMessages(username);
while (msgs.hasNext()) {
Message msg = (Message)msgs.next();
session.getConnection().deliver(msg);
......@@ -243,8 +242,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
try {
if (name != null && !"".equals(name)) {
name = name.toLowerCase();
long userID = nameManager.getID(name);
CachedRoster roster = rosterManager.getRoster(userID);
CachedRoster roster = rosterManager.getRoster(name);
roster.broadcastPresence(update);
}
}
......@@ -308,8 +306,7 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
try {
if (name != null && !"".equals(name)) {
name = name.toLowerCase();
long userID = nameManager.getID(name);
CachedRoster roster = rosterManager.getRoster(userID);
CachedRoster roster = rosterManager.getRoster(name);
// 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
// be able to send the unavialable presence to the entity
......@@ -398,12 +395,10 @@ public class PresenceUpdateHandler extends BasicModule implements ChannelHandler
public PacketDeliverer deliverer;
public PacketFactory packetFactory;
public OfflineMessageStore messageStore;
public NameIDManager nameManager;
protected TrackInfo getTrackInfo() {
TrackInfo trackInfo = new TrackInfo();
trackInfo.getTrackerClasses().put(RosterManager.class, "rosterManager");
trackInfo.getTrackerClasses().put(NameIDManager.class, "nameManager");
trackInfo.getTrackerClasses().put(XMPPServer.class, "localServer");
trackInfo.getTrackerClasses().put(SessionManager.class, "sessionManager");
trackInfo.getTrackerClasses().put(PresenceManager.class, "presenceManager");
......
......@@ -410,7 +410,7 @@ public class LdapManager {
}
String userDN = ((SearchResult)answer.next()).getName();
// 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).
// 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.
......
/**
* $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();
}
}
......@@ -11,177 +11,56 @@
package org.jivesoftware.messenger.ldap;
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.LongList;
import org.jivesoftware.messenger.user.UserIDProvider;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.spi.DbUserIDProvider;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.*;
import javax.naming.directory.*;
/**
* LDAP implementation of the UserIDProvider interface.<p>
* LDAP implementation of the UserIDProvider interface.
*
* The LdapUserIDProvider can operate in two modes -- in the pure LDAP mode,
* all user data is stored in the LDAP store. This mode generally requires
* modifications to the LDAP schema to accommodate data that Messenger needs.
* In the mixed mode, data that Messenger needs is stored locally.
*
* @author Jim Berrettini
* @author Matt Tucker
*/
public class LdapUserIDProvider implements UserIDProvider {
public class LdapUserIDProvider {
private LdapManager manager;
/**
* Object type for users.
*/
public static final int USER_TYPE = 0;
/**
* Object type for chatbots.
*/
public static final int CHATBOT_TYPE = 1;
/**
* The default domain id - the messenger domain.
*/
public static final long DEFAULT_DOMAIN = 1;
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=?";
private static final String USER_COUNT =
"SELECT count(*) FROM jiveUser";
private static final String INSERT_USERID =
"INSERT INTO jiveUserID (username,domainID,objectType,objectID) VALUES (?,?,?,?)";
private static final String ALL_USERS =
"SELECT userID from jiveUser";
public LdapUserIDProvider() {
manager = LdapManager.getInstance();
}
public String getUsername(long id) throws UserNotFoundException {
if (manager.getMode() == LdapManager.ALL_LDAP_MODE) {
return getUsernameFromLdap(id);
}
else {
return getUsernameFromDb(id);
}
}
public long getUserID(String username) throws UserNotFoundException {
if (manager.getMode() == LdapManager.ALL_LDAP_MODE) {
return getUserIDFromLdap(username);
}
else {
long id = 0L;
try {
id = getUserIDLocally(username);
}
catch (UserNotFoundException e) {
id = generateNewUserIDLocally(username);
}
return id;
}
}
public int getUserCount() {
int count = 0;
// If using the pure LDAP mode.
if (manager.getMode() == LdapManager.ALL_LDAP_MODE) {
// Note: the performance of this check may suffer badly for very large
// numbers of users since we manually iterate through results to get
// a count.
DirContext ctx = null;
try {
ctx = manager.getContext();
// Search for the dn based on the username.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[]{"jiveUserID"});
String filter = "(jiveUserID=*)";
NamingEnumeration answer = ctx.search("", filter, constraints);
while (answer.hasMoreElements()) {
count++;
answer.nextElement();
}
}
catch (Exception e) {
Log.error(e);
}
finally {
try { if (ctx != null) { ctx.close(); } }
catch (Exception e) { Log.error(e); }
// Note: the performance of this check may suffer badly for very large
// numbers of users since we manually iterate through results to get
// a count.
DirContext ctx = null;
try {
ctx = manager.getContext();
// Search for the dn based on the username.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[]{manager.getUsernameField()});
String filter = "(" + manager.getUsernameField() + " + =*)";
NamingEnumeration answer = ctx.search("", filter, constraints);
while (answer.hasMoreElements()) {
count++;
answer.nextElement();
}
}
// Otherwise, we're using the mixed LDAP mode.
else {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(USER_COUNT);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
}
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); }
}
catch (Exception e) {
Log.error(e);
}
finally {
try { if (ctx != null) { ctx.close(); } }
catch (Exception e) { Log.error(e); }
}
return count;
}
public LongList getUserIDs() {
LongList users = new LongList(500);
if (manager.getMode() == LdapManager.LDAP_DB_MODE) { // if in mixed mode, get id's from DB.
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
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));
}
rs.close();
}
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;
}
// Otherwise, in LDAP-only mode.
DirContext ctx = null;
try {
......@@ -189,8 +68,8 @@ public class LdapUserIDProvider implements UserIDProvider {
// Search for the dn based on the username.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[]{"jiveUserID"});
String filter = "(jiveUserID=*)";
constraints.setReturningAttributes(new String[]{manager.getUsernameField()});
String filter = "(" + manager.getUsernameField() + " + =*)";
NamingEnumeration answer = ctx.search("", filter, constraints);
while (answer.hasMoreElements()) {
......@@ -210,49 +89,14 @@ public class LdapUserIDProvider implements UserIDProvider {
public LongList getUserIDs(int startIndex, int numResults) {
LongList users = new LongList();
if (manager.getMode() == LdapManager.LDAP_DB_MODE) { // if in mixed mode, get id's from DB.
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
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;
}
// else, in LDAP-only mode
DirContext ctx = null;
try {
ctx = manager.getContext();
// Search for the dn based on the username.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[]{"jiveUserID"});
String filter = "(jiveUserID=*)";
constraints.setReturningAttributes(new String[]{manager.getUsernameField()});
String filter = "(" + manager.getUsernameField() + " + =*)";
NamingEnumeration answer = ctx.search("", filter, constraints);
for (int i = 0; i < startIndex; i++) {
answer.next();
......@@ -278,183 +122,6 @@ public class LdapUserIDProvider implements UserIDProvider {
return users;
}
/**
* This is used when operating in mixed mode -- generate a new user ID for a
* user stored in our database.
*
* @param username the username.
* @return id corresponding to that username
* @throws UserNotFoundException if an error occured generating the user ID.
*/
private long generateNewUserIDLocally(String username) throws UserNotFoundException {
long id = -1;
Connection con = null;
PreparedStatement pstmt = null;
try {
id = SequenceManager.nextID(JiveConstants.USER);
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(INSERT_USERID);
pstmt.setString(1, username);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
pstmt.setLong(3, DbUserIDProvider.USER_TYPE);
pstmt.setLong(4, id);
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.error(e);
throw new UserNotFoundException(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;
}
/**
* This is used when operating in mixed mode -- get user ID for a user stored locally.
*
* @param username
* @return user id corresponding to that username.
* @throws UserNotFoundException
*/
private long getUserIDLocally(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, DEFAULT_DOMAIN);
pstmt.setLong(3, USER_TYPE);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
id = rs.getLong(1);
}
rs.close();
}
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;
}
/**
* This method is used when operating in pure LDAP mode. Get user ID from the LDAP store.
*
* @param username the username.
* @return user id corresponding to that username.
* @throws UserNotFoundException if ther was an error loading the username
* from LDAP.
*/
private long getUserIDFromLdap(String username) throws UserNotFoundException {
DirContext ctx = null;
try {
String userDN = manager.findUserDN(username);
ctx = manager.getContext();
String[] attributes = new String[]{"jiveUserID"};
Attributes attrs = ctx.getAttributes(userDN, attributes);
return Long.parseLong((String)attrs.get("jiveUserID").get());
}
catch (Exception e) {
Log.error(e);
throw new UserNotFoundException(e);
}
finally {
try { if (ctx != null) { ctx.close(); } }
catch (Exception e) { Log.error(e); }
}
}
/**
* This method is used in mixed mode. Get the username that corresponds to a given ID.
*
* @param id the user ID.
* @return username for that user id.
* @throws UserNotFoundException if there was an error loading the username.
*/
private String getUsernameFromDb(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, DEFAULT_DOMAIN);
pstmt.setLong(3, USER_TYPE);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
name = rs.getString(1);
}
rs.close();
}
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;
}
/**
* This method is used when operating in pure LDAP mode. Get the username
* that corresponds to a given ID.
*
* @param id the userID.
* @return ther username.
* @throws UserNotFoundException
*/
private String getUsernameFromLdap(long id) throws UserNotFoundException {
DirContext ctx = null;
try {
ctx = manager.getContext();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[]{"jiveUserID"});
StringBuffer filter = new StringBuffer();
filter.append("(").append("jiveUserID").append("=");
filter.append(id).append(")");
NamingEnumeration answer = ctx.search("", filter.toString(), constraints);
if (answer == null || !answer.hasMoreElements()) {
throw new UserNotFoundException("User not found: " + id);
}
String userDN = ((SearchResult)answer.next()).getName();
return getUsernameFromUserDN(userDN);
}
catch (NamingException e) {
Log.error(e);
throw new UserNotFoundException(e);
}
catch (UserNotFoundException e) {
Log.error(e);
throw new UserNotFoundException(e);
}
finally {
try { if (ctx != null) { ctx.close(); } }
catch (Exception e) { Log.error(e); }
}
}
/**
* Helper function to retrieve username from userDN.
*
......
......@@ -11,21 +11,12 @@
package org.jivesoftware.messenger.ldap;
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.user.UserInfo;
import org.jivesoftware.messenger.user.UserInfoProvider;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.spi.BasicUserInfo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import javax.naming.NamingEnumeration;
import javax.naming.directory.*;
/**
......@@ -39,18 +30,6 @@ import javax.naming.directory.*;
*/
public class LdapUserInfoProvider implements UserInfoProvider {
private static final String LOAD_USER_BY_ID =
"SELECT name, nameVisible, email, emailVisible, " +
"creationDate, modificationDate FROM jiveUser WHERE userID=?";
private static final String INSERT_USER =
"INSERT INTO jiveUser (userID, password, name, nameVisible, " +
"email, emailVisible, creationDate, modificationDate) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SAVE_USER =
"UPDATE jiveUser SET name=?, nameVisible=?, email=?," +
"emailVisible=?, creationDate=?, modificationDate=? WHERE " +
"userID=?";
private LdapManager manager;
/**
......@@ -63,107 +42,49 @@ public class LdapUserInfoProvider implements UserInfoProvider {
/**
* <p>Obtain the UserInfo of a user. Will retrieve either from LDAP or locally, depending on mode of operation.</p>
*
* @param id
* @param username the username.
* @return a user info object.
* @throws UserNotFoundException
*/
public UserInfo getInfo(long id) throws UserNotFoundException {
if (manager.getMode() == LdapManager.ALL_LDAP_MODE) {
return getInfoFromLdap(id);
}
UserInfo info = null;
try {
info = getInfoFromDb(id);
}
catch (UserNotFoundException e) {
info = generateNewUserInfoInDb(id);
}
return info;
public UserInfo getInfo(String username) throws UserNotFoundException {
return getInfoFromLdap(username);
}
/**
* <p>Sets the user's info. In pure LDAP mode, this is unsupported.</p>
*
* @param id user ID for setting info.
* @param username username for setting info.
* @param info to set.
* @throws UserNotFoundException
* @throws UnauthorizedException
* @throws UnsupportedOperationException
*/
public void setInfo(long id, UserInfo info)
public void setInfo(String username, UserInfo info)
throws UserNotFoundException, UnauthorizedException, UnsupportedOperationException {
if (manager.getMode() == LdapManager.ALL_LDAP_MODE) { // can't do this in LDAP
throw new UnsupportedOperationException("All LDAP mode: Cannot modify data in LDAP.");
}
// in mixed mode, update the database.
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(SAVE_USER);
pstmt.setString(1, info.getName());
pstmt.setInt(2, info.isNameVisible() ? 1 : 0);
pstmt.setString(3, info.getEmail());
pstmt.setInt(4, info.isEmailVisible() ? 1 : 0);
pstmt.setString(5, StringUtils.dateToMillis(info.getCreationDate()));
pstmt.setString(6, StringUtils.dateToMillis(info.getModificationDate()));
pstmt.setLong(7, 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); }
}
throw new UnsupportedOperationException("All LDAP mode: Cannot modify data in LDAP.");
}
/**
* Pure LDAP method for getting info for a given userID.
*
* @param id of user.
* @param username the username.
* @return UserInfo for that user.
* @throws UserNotFoundException
*/
private UserInfo getInfoFromLdap(long id) throws UserNotFoundException {
private UserInfo getInfoFromLdap(String username) throws UserNotFoundException {
BasicUserInfo userInfo = null;
DirContext ctx = null;
try {
String userDN = null;
ctx = manager.getContext();
// Search for the dn based on the username.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[]{"jiveUserID"});
StringBuffer filter = new StringBuffer();
filter.append("(").append("jiveUserID").append("=");
filter.append(id).append(")");
NamingEnumeration answer = ctx.search("", filter.toString(), constraints);
if (answer == null || !answer.hasMoreElements()) {
throw new UserNotFoundException("User not found: " + id);
}
userDN = ((SearchResult)answer.next()).getName();
String userDN = manager.findUserDN(username);
// Load record.
String[] attributes = new String[]{
"jiveUserID", manager.getUsernameField(), manager.getNameField(),
manager.getEmailField(), "jiveNameVisible",
"jiveEmailVisible", "jiveCDate", "jiveMDate", "jiveProps"
manager.getUsernameField(), manager.getNameField(),
manager.getEmailField()
};
ctx = manager.getContext();
Attributes attrs = ctx.getAttributes(userDN, attributes);
id = Long.parseLong((String)attrs.get("jiveUserID").get());
String username = (String)attrs.get(manager.getUsernameField()).get();
String name = null;
String email = null;
boolean nameVisible = false;
boolean emailVisible = false;
Date creationDate, modificationDate;
Attribute nameField = attrs.get(manager.getNameField());
if (nameField != null) {
name = (String)nameField.get();
......@@ -172,11 +93,7 @@ public class LdapUserInfoProvider implements UserInfoProvider {
if (emailField != null) {
email = (String)emailField.get();
}
nameVisible = new Boolean((String)attrs.get("jiveNameVisible").get()).booleanValue();
emailVisible = new Boolean((String)attrs.get("jiveEmailVisible").get()).booleanValue();
creationDate = new Date(Long.parseLong((String)attrs.get("jiveCDate").get()));
modificationDate = new Date(Long.parseLong((String)attrs.get("jiveMDate").get()));
userInfo = new BasicUserInfo(id, name, email, nameVisible, emailVisible, creationDate, modificationDate);
userInfo = new BasicUserInfo(username, name, email, new Date(), new Date());
}
catch (Exception e) {
throw new UserNotFoundException(e);
......@@ -190,96 +107,4 @@ public class LdapUserInfoProvider implements UserInfoProvider {
}
return userInfo;
}
/**
* Mixed mode method for retrieving User Info for a given user ID.
*
* @param id for user.
* @return UserInfo for user.
* @throws UserNotFoundException
*/
private UserInfo getInfoFromDb(long id) throws UserNotFoundException {
BasicUserInfo userInfo = null;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_USER_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 BasicUserInfo(id,
rs.getString(1), // name
rs.getString(3), // email
rs.getInt(2) == 1, // name visible
rs.getInt(4) == 1, // email visible
new java.util.Date(Long.parseLong(rs.getString(5).trim())), // creation date
new java.util.Date(Long.parseLong(rs.getString(6).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;
}
/**
* Mixed mode method for creating default UserInfo locally for a new user.
*
* @param id
* @return UserInfo for that user.
*/
private UserInfo generateNewUserInfoInDb(long id) {
Connection con = null;
PreparedStatement pstmt = null;
Date now = new Date();
try {
// Add the user record in jiveUser
pstmt = con.prepareStatement(INSERT_USER);
pstmt.setLong(1, id);
pstmt.setString(2, "");
pstmt.setString(3, "");
pstmt.setInt(4, 1); // name visible
pstmt.setString(5, "");
pstmt.setInt(6, 0); // email visible
pstmt.setString(7, StringUtils.dateToMillis(now));
pstmt.setString(8, 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 new BasicUserInfo(id,
"", // name
"", // email
true, // name visible
false, // email visible
now, // creation date
now);
}
}
\ No newline at end of file
......@@ -25,34 +25,34 @@ public class LdapUserPropertiesProvider implements UserPropertiesProvider {
/**
* Delete Vcard property. Currently unimplemented.
*
* @param id
* @param username
* @param name
* @throws UnsupportedOperationException
*/
public void deleteVcardProperty(long id, String name) throws UnsupportedOperationException {
public void deleteVcardProperty(String username, String name) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Delete user property. Currently unimplemented.
*
* @param id
* @param username
* @param name
* @throws UnsupportedOperationException
*/
public void deleteUserProperty(long id, String name) throws UnsupportedOperationException {
public void deleteUserProperty(String username, String name) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Insert new vCard property. Currently unimplemented.
*
* @param id
* @param username
* @param name
* @param value
* @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();
}
......@@ -60,56 +60,56 @@ public class LdapUserPropertiesProvider implements UserPropertiesProvider {
/**
* Insert new user property. Currently unimplemented.
*
* @param id
* @param username
* @param name
* @param value
* @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();
}
/**
* Update vCard. Currently unimplemented.
*
* @param id
* @param username
* @param name
* @param value
* @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();
}
/**
* Update user property. Currently unimplemented.
*
* @param id
* @param username
* @param name
* @param value
* @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();
}
/**
* Get vCard properties. Unimplemented.
*
* @param id
* @param username
* @return empty Map
*/
public Map getVcardProperties(long id) {
public Map getVcardProperties(String username) {
return Collections.EMPTY_MAP;
}
/**
* Get user properties. Unimplemented.
*
* @param id
* @param username
* @return empty Map.
*/
public Map getUserProperties(long id) {
public Map getUserProperties(String username) {
return Collections.EMPTY_MAP;
}
}
......@@ -17,9 +17,7 @@ import java.util.LinkedList;
import javax.xml.stream.XMLStreamException;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotManager;
import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.messenger.container.ServiceLookupFactory;
import org.jivesoftware.messenger.container.TrackInfo;
import org.jivesoftware.messenger.handler.IQHandler;
import org.jivesoftware.util.LocaleUtils;
......@@ -37,7 +35,6 @@ public class IQRouterImpl extends BasicModule implements IQRouter {
public RoutingTable routingTable;
public LinkedList iqHandlers = new LinkedList();
private HashMap namespace2Handlers = new HashMap();
private ChatbotManager chatBotManager;
/**
* Creates a packet router.
......@@ -72,24 +69,9 @@ public class IQRouterImpl extends BasicModule implements IQRouter {
}
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.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) {
......
/**
* $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 {
}
}
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)) {
return store.getSize(userName);
return store.getSize(username);
}
else {
throw new org.jivesoftware.messenger.auth.UnauthorizedException();
}
}
}
}
\ No newline at end of file
......@@ -34,7 +34,7 @@ import org.dom4j.Element;
*/
public class PresenceImpl extends AbstractPacket implements Presence, Cacheable {
private long userID = -1;
private String username;
private String uid = "";
private Date loginTime;
private Date updateTime;
......@@ -46,7 +46,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable
public PresenceImpl(User user, String uid) {
this();
if (user != null) {
this.userID = user.getID();
this.username = user.getUsername();
}
this.uid = uid;
......@@ -140,8 +140,8 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable
}
}
public long getUserID() {
return userID;
public String getUsername() {
return username;
}
public Date getLoginTime() {
......@@ -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.
int size = 0;
size += CacheSizes.sizeOfObject(); // overhead of object
size += CacheSizes.sizeOfLong(); // userID
size += CacheSizes.sizeOfString(username); // username
size += CacheSizes.sizeOfString(uid); // uid
size += CacheSizes.sizeOfDate(); // login date
size += CacheSizes.sizeOfDate(); // last update date
......@@ -250,7 +250,7 @@ public class PresenceImpl extends AbstractPacket implements Presence, Cacheable
public XMPPFragment createDeepCopy() {
PresenceImpl presence = new PresenceImpl();
deepCopy(presence);
presence.userID = userID;
presence.username = username;
presence.uid = uid;
presence.loginTime = loginTime;
presence.updateTime = updateTime;
......
......@@ -18,11 +18,11 @@ import org.jivesoftware.util.Cache;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotManager;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserManager;
import org.jivesoftware.messenger.user.UserNotFoundException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Simple in memory implementation of the PresenceManager interface.
......@@ -31,21 +31,15 @@ import java.util.*;
*/
public class PresenceManagerImpl extends BasicModule implements PresenceManager {
/**
* table: key Presence ID (Long); value Presence
*/
private Cache onlineGuestCache;
/**
* table: key User ID (Long); value Presence
*/
private Cache onlineUserCache;
private Map<String,Presence> onlineGuests;
private Map<String,Presence> onlineUsers;
/**
* table: key jid.getUserJid().toLowerCase() (String); value Presence
*/
private Cache foreignUserCache;
public UserManager userManager;
public ChatbotManager chatbotManager;
public SessionManager sessionManager;
public RoutingTable routingTable;
public XMPPServer server;
......@@ -60,8 +54,8 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
// create caches - no size limit and never expire for presence caches
long HOUR = JiveConstants.HOUR;
onlineGuestCache = new Cache("Online Guests", -1, -1);
onlineUserCache = new Cache("Online Users", -1, -1);
onlineGuests = new ConcurrentHashMap<String,Presence>();
onlineUsers = new ConcurrentHashMap<String,Presence>();
foreignUserCache = new Cache("Foreign Users", foreignCacheSize, HOUR);
}
......@@ -69,60 +63,37 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
return sessionManager.getSessionCount(user.getUsername()) > 0;
}
public int getOnlineUserCount() {
Iterator iter = getOnlineUsers();
int count = 0;
while (iter.hasNext()) {
iter.next();
count++;
}
return count;
}
public int getOnlineGuestCount() {
Iterator iter = onlineGuestCache.values().iterator();
int count = 0;
while (iter.hasNext()) {
Presence presence = (Presence)iter.next();
for (Presence presence : onlineGuests.values()) {
if (presence.isAvailable()) {
count++;
}
}
return count;
}
public Iterator getOnlineUsers() {
Iterator iter = onlineUserCache.values().iterator();
List users = new ArrayList();
while (iter.hasNext()) {
Presence presence = (Presence)iter.next();
public Collection<User> getOnlineUsers() {
List<User> users = new ArrayList<User>();
for (Presence presence : onlineUsers.values()) {
if (presence.isAvailable()) {
try {
users.add(userManager.getUser(presence.getUserID()));
users.add(userManager.getUser(presence.getUsername()));
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
return Collections.unmodifiableList(getOnlineUserList()).iterator();
return Collections.unmodifiableCollection(users);
}
public Iterator getOnlineUsers(boolean ascending, int sortField) {
public Collection<User> getOnlineUsers(boolean ascending, int sortField) {
return getOnlineUsers(ascending, sortField, Integer.MAX_VALUE);
}
public Iterator getOnlineUsers(final boolean ascending,
int sortField,
int numResults) {
Iterator iter = onlineUserCache.values().iterator();
public Collection<User> getOnlineUsers(final boolean ascending, int sortField, int numResults) {
Iterator iter = onlineUsers.values().iterator();
List presences = new ArrayList();
while (iter.hasNext()) {
......@@ -134,61 +105,58 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
}
switch (sortField) {
case PresenceManager.SORT_ONLINE_TIME:
{
Collections.sort(presences, new Comparator() {
public int compare(Object object1, Object object2) {
Presence presence1 = (Presence)object1;
Presence presence2 = (Presence)object2;
if (ascending) {
return presence1.getLoginTime().compareTo(presence2.getLoginTime());
}
else {
return presence2.getLoginTime().compareTo(presence1.getLoginTime());
}
case PresenceManager.SORT_ONLINE_TIME: {
Collections.sort(presences, new Comparator() {
public int compare(Object object1, Object object2) {
Presence presence1 = (Presence)object1;
Presence presence2 = (Presence)object2;
if (ascending) {
return presence1.getLoginTime().compareTo(presence2.getLoginTime());
}
});
break;
}
case PresenceManager.SORT_USERNAME:
{
Collections.sort(presences, new Comparator() {
public int compare(Object object1, Object object2) {
Presence presence1 = (Presence)object1;
Presence presence2 = (Presence)object2;
String presenceUser1 = "";
String presenceUser2 = "";
try {
presenceUser1 =
userManager.getUser(presence1.getUserID()).getUsername();
presenceUser2 =
userManager.getUser(presence2.getUserID()).getUsername();
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
if (ascending) {
return presenceUser1.compareTo(presenceUser2);
}
else {
return presenceUser2.compareTo(presenceUser1);
}
else {
return presence2.getLoginTime().compareTo(presence1.getLoginTime());
}
});
break;
}
default:
{
// ignore invalid sort field
}
}
});
break;
}
case PresenceManager.SORT_USERNAME: {
Collections.sort(presences, new Comparator() {
public int compare(Object object1, Object object2) {
Presence presence1 = (Presence)object1;
Presence presence2 = (Presence)object2;
String presenceUser1 = "";
String presenceUser2 = "";
try {
presenceUser1 =
userManager.getUser(presence1.getUsername()).getUsername();
presenceUser2 =
userManager.getUser(presence2.getUsername()).getUsername();
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
if (ascending) {
return presenceUser1.compareTo(presenceUser2);
}
else {
return presenceUser2.compareTo(presenceUser1);
}
}
});
break;
}
default: {
// ignore invalid sort field
}
}
List users = new ArrayList();
List<User> users = new ArrayList<User>();
for (int i = 0; i < presences.size(); i++) {
Presence presence = (Presence)presences.get(i);
try {
users.add(userManager.getUser(presence.getUserID()));
users.add(userManager.getUser(presence.getUsername()));
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
......@@ -196,53 +164,50 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
}
if (numResults > users.size()) {
return Collections.unmodifiableList(users).iterator();
return Collections.unmodifiableCollection(users);
}
else {
return Collections.unmodifiableList(users.subList(0, numResults - 1)).iterator();
return Collections.unmodifiableCollection(users.subList(0, numResults - 1));
}
}
public Presence createPresence(User user, String uid) {
Presence presence = null;
presence = new PresenceImpl(user, uid);
setOnline(presence);
return presence;
}
public void setOnline(Presence presence) {
User user = null;
try {
user = userManager.getUser(presence.getUserID());
user = userManager.getUser(presence.getUsername());
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
if (user != null) {
synchronized (onlineUserCache) {
onlineUserCache.put(new Long(user.getID()), presence);
synchronized (onlineUsers) {
onlineUsers.put(user.getUsername(), presence);
}
}
else {
synchronized (onlineGuestCache) {
onlineGuestCache.put(presence.getID(), presence);
synchronized (onlineGuests) {
onlineGuests.put(presence.getID(), presence);
}
}
}
public void setOffline(Presence presence) {
if (presence.getUserID() != -1) {
synchronized (onlineUserCache) {
Long id = new Long(presence.getUserID());
onlineUserCache.remove(id);
if (presence.getUsername() != null) {
synchronized (onlineUsers) {
onlineUsers.remove(presence.getUsername());
}
}
else {
synchronized (onlineGuestCache) {
onlineGuestCache.remove(presence.getID());
synchronized (onlineGuests) {
onlineGuests.remove(presence.getID());
}
}
}
......@@ -254,13 +219,10 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
if (user == null) {
return false;
}
Presence presence = (Presence)onlineUserCache.get(new Long(user.getID()));
Presence presence = (Presence)onlineUsers.get(user.getUsername());
if (presence != null) {
return presence.isAvailable();
}
return false;
}
......@@ -269,7 +231,7 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
return null;
}
// try getting the presence obj from the online user cache:
Presence userPresence = (Presence)onlineUserCache.get(new Long(user.getID()));
Presence userPresence = (Presence)onlineUsers.get(user.getUsername());
if (userPresence != null) {
return userPresence;
}
......@@ -283,9 +245,8 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
if (presenceID == null) {
return null;
}
// search the current lists for the presence
Iterator onlineUsers = onlineUserCache.values().iterator();
Iterator onlineUsers = this.onlineUsers.values().iterator();
while (onlineUsers.hasNext()) {
Presence presence = (Presence)onlineUsers.next();
......@@ -293,8 +254,7 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
return presence;
}
}
Iterator guestUsers = onlineGuestCache.values().iterator();
Iterator guestUsers = onlineGuests.values().iterator();
while (guestUsers.hasNext()) {
Presence presence = (Presence)guestUsers.next();
......@@ -302,46 +262,12 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
return presence;
}
}
return null;
}
private List getOnlineUserList() {
Iterator iter = onlineUserCache.values().iterator();
List users = new ArrayList();
while (iter.hasNext()) {
Presence presence = (Presence)iter.next();
if (presence.isAvailable()) {
try {
users.add(userManager.getUser(presence.getUserID()));
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
return users;
}
public void probePresence(String prober, XMPPAddress probee) {
try {
if (chatbotManager.isChatbot(probee)) {
try {
RoutableChannelHandler handler = routingTable.getRoute(probee);
Presence presence = new PresenceImpl();
presence.setType(Presence.PROBE);
presence.setSender(server.createAddress(prober, ""));
presence.setRecipient(handler.getAddress());
handler.process(presence);
}
catch (NoSuchRouteException e) {
Log.info(prober + " probing presence of unavailable chatbot " + probee);
}
}
else if (server.isLocal(probee)) {
if (server.isLocal(probee)) {
if (probee.getNamePrep() != null && !"".equals(probee.getNamePrep())) {
Iterator sessionIter =
sessionManager.getSessions(probee.getNamePrep());
......@@ -381,20 +307,7 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
public void probePresence(XMPPAddress prober, XMPPAddress probee) {
try {
if (chatbotManager.isChatbot(probee)) {
try {
RoutableChannelHandler handler = routingTable.getRoute(probee);
Presence presence = new PresenceImpl();
presence.setType(Presence.PROBE);
presence.setSender(prober);
presence.setRecipient(handler.getAddress());
handler.process(presence);
}
catch (NoSuchRouteException e) {
Log.info(prober + " probing presence of unavailable chatbot " + probee);
}
}
else if (server.isLocal(probee)) {
if (server.isLocal(probee)) {
Iterator sessionIter =
sessionManager.getSessions(probee.getName().toLowerCase());
while (sessionIter.hasNext()) {
......@@ -443,7 +356,6 @@ public class PresenceManagerImpl extends BasicModule implements PresenceManager
TrackInfo trackInfo = new TrackInfo();
trackInfo.getTrackerClasses().put(SessionManager.class, "sessionManager");
trackInfo.getTrackerClasses().put(UserManager.class, "userManager");
trackInfo.getTrackerClasses().put(ChatbotManager.class, "chatbotManager");
trackInfo.getTrackerClasses().put(XMPPServer.class, "server");
trackInfo.getTrackerClasses().put(PacketDeliverer.class, "deliverer");
trackInfo.getTrackerClasses().put(RoutingTable.class, "routingTable");
......
......@@ -18,9 +18,7 @@ import org.jivesoftware.messenger.auth.AuthToken;
import org.jivesoftware.messenger.auth.Permissions;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.spi.UserIteratorProxy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collection;
/**
* Enforces security constraints.
......@@ -44,65 +42,20 @@ public class PresenceManagerProxy implements PresenceManager {
return manager.isAvailable(user);
}
public int getOnlineUserCount() {
Iterator iter = getOnlineUsers();
int count = 0;
while (iter.hasNext()) {
iter.next();
count++;
}
return count;
}
public int getOnlineGuestCount() {
return manager.getOnlineGuestCount();
}
public Iterator getOnlineUsers() {
Iterator iter = 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 Collection<User> getOnlineUsers() {
return manager.getOnlineUsers();
}
public Iterator getOnlineUsers(boolean ascending, int sortField) {
Iterator iter = 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 Collection<User> getOnlineUsers(boolean ascending, int sortField) {
return manager.getOnlineUsers(ascending, sortField);
}
public Iterator getOnlineUsers(boolean ascending, int sortField, int numResults) {
Iterator iter = 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 Collection<User> getOnlineUsers(boolean ascending, int sortField, int numResults) {
return manager.getOnlineUsers(ascending, sortField, numResults);
}
public Presence createPresence(User user, String uid) throws UnauthorizedException {
......@@ -115,7 +68,7 @@ public class PresenceManagerProxy implements PresenceManager {
}
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)) {
manager.setOffline(presence);
}
......
......@@ -36,7 +36,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
}
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)) {
presence.setAvailable(online);
}
......@@ -50,7 +50,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
}
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)) {
presence.setVisible(visible);
}
......@@ -63,8 +63,8 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
return presence.getID();
}
public long getUserID() {
return presence.getUserID();
public String getUsername() {
return presence.getUsername();
}
public Date getLoginTime() {
......@@ -76,7 +76,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
}
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)) {
presence.setLastUpdateTime(time);
}
......@@ -90,7 +90,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
}
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)) {
presence.setShow(status);
}
......@@ -104,7 +104,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
}
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)) {
presence.setStatus(status);
}
......@@ -118,7 +118,7 @@ public class PresenceProxy extends AbstractPacketProxy implements Presence {
}
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)) {
presence.setPriority(priority);
}
......
......@@ -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)) {
store.add(userID, data);
store.add(username, data);
}
else {
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)) {
return store.get(userID, data);
return store.get(username, data);
}
else {
throw new UnauthorizedException();
......
......@@ -92,11 +92,11 @@ public class SessionImpl implements Session {
}
}
public long getUserID() throws UserNotFoundException {
public String getUsername() throws UserNotFoundException {
if (authToken == null) {
throw new UserNotFoundException();
}
return authToken.getUserID();
return authToken.getUsername();
}
public String getServerName() {
......@@ -104,7 +104,7 @@ public class SessionImpl implements Session {
}
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);
authToken = auth;
......
......@@ -471,22 +471,16 @@ public class SessionManagerImpl extends BasicModule implements SessionManager,
// Grab all the possible matching sessions by user
LinkedList results = new LinkedList();
if (filter.getUserID() == SessionResultFilter.ALL_USER_ID) {
if (filter.getUsername() == null) {
// No user id filtering
copyAnonSessions(results);
copyUserSessions(results);
}
else {
// user id filtering
if (filter.getUserID() == SessionResultFilter.ANONYMOUS_USER_ID) {
copyAnonSessions(results);
try {
copyUserSessions(userManager.getUser(filter.getUsername()).getUsername(), results);
}
else {
try {
copyUserSessions(userManager.getUser(filter.getUserID()).getUsername(), results);
}
catch (UserNotFoundException e) {
}
catch (UserNotFoundException e) {
}
}
......
......@@ -28,11 +28,11 @@ import org.jivesoftware.util.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>
......
......@@ -36,35 +36,35 @@ public interface RosterItemProvider {
* <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 item The settings for the roster item to create
* @param username the username of the user/chatbot that owns the roster item
* @param item the settings for the roster item to create
* @return The created roster item
* @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/>
* <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
* @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)
*/
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/>
* <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
* @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>
......@@ -74,18 +74,18 @@ public interface RosterItemProvider {
* <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)
*/
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>
*
* @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
*/
int getItemCount(long userID);
int getItemCount(String username);
/**
* <p>Retrieve an iterator of RosterItems for the given user.</p>
......@@ -94,8 +94,8 @@ public interface RosterItemProvider {
* 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.
*
* @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
*/
Iterator getItems(long userID);
Iterator getItems(String username);
}
......@@ -24,11 +24,11 @@ package org.jivesoftware.messenger.user;
*/
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
* @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 @@
package org.jivesoftware.messenger.user;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.AuthToken;
import org.jivesoftware.messenger.auth.Group;
import org.jivesoftware.messenger.auth.Permissions;
......@@ -29,7 +28,16 @@ import java.util.Iterator;
*
* @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>
......
/**
* $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.user;
import org.jivesoftware.messenger.auth.UnauthorizedException;
/**
* <p>Defines the provider methods required for creating and deleting user accounts.</p>
* <p/>
* <p>Creating and deleting user accounts 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 user
* accounts.</p>
*
* @author Iain Shigeoka
*/
public interface UserAccountProvider {
/**
* <p>Called to create a new user account (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
* @param password The plain-text password for the user
* @param email The email address of the new user
* @return The user ID for the new user
* @throws UnauthorizedException If users can't be created because of caller permissions (no new account created)
* @throws 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 createUser(String username, String password, String email)
throws UnauthorizedException, UserAlreadyExistsException, UnsupportedOperationException;
/**
* <p>Called to delete an existing user account (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 deleteUser(long id) throws 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.user;
import org.jivesoftware.util.LongList;
/**
* <p>The essential interface to implement when creating a user 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 yoru 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>
* <p/>
* <p>The other user management service plug-in that is commonly overridden is UserInfoProvider.</p>
*
* @author Iain Shigeoka
* @see UserInfoProvider
*/
public interface UserIDProvider {
/**
* <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 getUserID(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 getUserCount();
/**
* <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 getUserIDs();
/**
* <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 getUserIDs(int startIndex, int numResults);
}
......@@ -33,13 +33,6 @@ import java.util.Date;
*/
public interface UserInfo extends Cacheable {
/**
* <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 name. The user's name does not have to be to be unique in the system. Some
* users may opt to not let others see their name for privacy reasons. In that case, the user
......@@ -57,23 +50,6 @@ public interface UserInfo extends Cacheable {
*/
void setName(String name) throws UnauthorizedException;
/**
* Returns true if the user has chosen to make her name visible to other users. If the name is
* not visible, calling getName() will throw an UnauthorizedException.
*
* @return true if the name is visible to other users.
*/
boolean isNameVisible();
/**
* Sets whether a user's name is visible to other users. If the field is set to not be visible,
* calling getName() will throw an UnauthorizedException.
*
* @param visible boolean value to determin if the name should be visible.
* @throws UnauthorizedException if does not have administrator permissions.
*/
void setNameVisible(boolean visible) throws UnauthorizedException;
/**
* Returns the user's email address. Email should be considered to be a required field of a user
* account since it is critical to many user operations performing. If the user sets
......@@ -92,23 +68,6 @@ public interface UserInfo extends Cacheable {
*/
void setEmail(String email) throws UnauthorizedException;
/**
* Returns true if the user has chosen to make her email visible to other users. If the email
* field is not visible, calling getEmail() will throw an UnauthorizedException.
*
* @return true if the name is visible to other users.
*/
boolean isEmailVisible();
/**
* Sets whether a user's email is visible to other users. If the field is set to not be visible,
* calling getEmail() will throw an UnauthorizedException.
*
* @param visible boolean value to determin if the name should be visible.
* @throws UnauthorizedException if does not have administrator permissions.
*/
void setEmailVisible(boolean visible) throws UnauthorizedException;
/**
* Returns the date that the user was created.
*
......
......@@ -34,21 +34,21 @@ public interface UserInfoProvider {
* <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
* @param username the username of the user.
* @return The user's info
* @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>
*
* @param id The ID of the user
* @param username the username of the user.
* @param info The user's new info
* @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 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;
}
......@@ -51,15 +51,6 @@ public interface UserManager extends Module {
*/
public void deleteUser(User user) throws UnauthorizedException, UnsupportedOperationException;
/**
* Returns a User specified by their ID.
*
* @param userID the id of the User to lookup.
* @return the User specified by <tt>userID</tt>.
* @throws UserNotFoundException if the user does not exist.
*/
public User getUser(long userID) throws UserNotFoundException;
/**
* Returns the User specified by username.
*
......@@ -69,25 +60,6 @@ public interface UserManager extends Module {
*/
public User getUser(String username) throws UserNotFoundException;
/**
* Returns the userID specified by the username. This method is only useful in specialized
* cases, as its generally easier to call <tt>getUser(username).getID()</tt> instead of this
* method.
*
* @param username the username of the user.
* @return the userID that matches username.
* @throws UserNotFoundException if the user does not exist.
*/
public long getUserID(String username) throws UserNotFoundException;
/**
* <p>Deletes a user.</p>
*
* @param userID the ID of the user to delete.
* @throws UnauthorizedException
*/
public void deleteUser(long userID) throws UnauthorizedException, UserNotFoundException;
/**
* Returns the number of users in the system.
*
......
......@@ -29,84 +29,85 @@ public interface UserPropertiesProvider {
/**
* <p>Delete a user's vcard property (optional operation).</p>
*
* @param id The ID of the user
* @param username the username of the user
* @param name The name of the property to delete
* @throws UnauthorizedException If the caller does not have permission to carry out the operation
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public void deleteVcardProperty(long id, String name) throws UnauthorizedException, UnsupportedOperationException;
public void deleteVcardProperty(String username, String name) throws UnauthorizedException, UnsupportedOperationException;
/**
* <p>Delete a user's user property (optional operation).</p>
*
* @param id The ID of the user
* @param username the username of the user
* @param name The name of the property to delete
* @throws UnauthorizedException If the caller does not have permission to carry out the operation
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public void deleteUserProperty(long id, String name) throws UnauthorizedException, UnsupportedOperationException;
public void deleteUserProperty(String username, String name) throws UnauthorizedException, UnsupportedOperationException;
/**
* <p>Insert a new vcard property (optional operation).</p>
*
* @param id The ID of the user
* @param username the username of the user
* @param name The name of the property
* @param value The value of the property
* @throws UnauthorizedException If the caller does not have permission to carry out the operation
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public void insertVcardProperty(long id, String name, String value) throws UnauthorizedException, UnsupportedOperationException;
public void insertVcardProperty(String username, String name, String value) throws UnauthorizedException, UnsupportedOperationException;
/**
* <p>Insert a new user property (optional operation).</p>
*
* @param id The ID of the user
* @param username the username of the user
* @param name The name of the property
* @param value The value of the property
* @throws UnauthorizedException If the caller does not have permission to carry out the operation
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public void insertUserProperty(long id, String name, String value) throws UnauthorizedException, UnsupportedOperationException;
public void insertUserProperty(String username, String name, String value) throws UnauthorizedException, UnsupportedOperationException;
/**
* <p>Update a vcard property (optional operation).</p>
*
* @param id The ID of the user
* @param name The name of the property
* @param value The value of the property
* @throws UnauthorizedException If the caller does not have permission to carry out the operation
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
* @param username the username of the user.
* @param name The name of the property.
* @param value The value of the property.
* @throws UnauthorizedException if the caller does not have permission to carry out the operation
* @throws UnsupportedOperationException if the provider does not support the operation (this is an optional operation).
*/
public void updateVcardProperty(long id, String name, String value) throws UnauthorizedException, UnsupportedOperationException;
public void updateVcardProperty(String username, String name, String value)
throws UnauthorizedException, UnsupportedOperationException;
/**
* <p>Update an Existing user property (optional operation).</p>
*
* @param id The ID of the user
* @param username the username of the user
* @param name The name of the property
* @param value The value of the property
* @throws UnauthorizedException If the caller does not have permission to carry out the operation
* @throws UnsupportedOperationException If the provider does not support the operation (this is an optional operation)
*/
public void updateUserProperty(long id, String name, String value) throws UnauthorizedException, UnsupportedOperationException;
public void updateUserProperty(String username, String name, String value) throws UnauthorizedException, UnsupportedOperationException;
/**
* <p>Obtain a map containing all vcard properties for a user.</p>
* <p/>
* <p>If the provider doesn't support vcard properties, return an empty map.</p>
*
* @param id The id of the user to retrieve the vcard properties
* @param username the username of the user to retrieve the vcard properties
* @return A map of property name-value pairs
*/
public Map getVcardProperties(long id);
public Map getVcardProperties(String username);
/**
* <p>Obtain a map containing all user properties for a user.</p>
* <p/>
* <p>If the provider doesn't support user properties, return an empty map.</p>
*
* @param id The id of the user to retrieve the user properties
* @param username the username of the user to retrieve the user properties
* @return A map of property name-value pairs
*/
public Map getUserProperties(long id);
public Map getUserProperties(String username);
}
......@@ -42,19 +42,15 @@ import org.jivesoftware.messenger.JiveGlobals;
*/
public class UserProviderFactory {
private static UserIDProvider userIDProvider;
private static UserPropertiesProvider userPropertiesProvider;
private static UserInfoProvider userInfoProvider;
private static UserAccountProvider userAccountProvider;
private static RosterItemProvider rosterItemProvider;
/**
* The default class to instantiate is database implementation.
*/
private static String[] classNames = {"org.jivesoftware.messenger.user.spi.DbUserIDProvider",
"org.jivesoftware.messenger.user.spi.DbUserPropertiesProvider",
private static String[] classNames = {"org.jivesoftware.messenger.user.spi.DbUserPropertiesProvider",
"org.jivesoftware.messenger.user.spi.DbUserInfoProvider",
"org.jivesoftware.messenger.user.spi.DbUserAccountProvider",
"org.jivesoftware.messenger.user.spi.DbRosterItemProvider"};
private static String[] propNames = {"UserProvider.id.className",
......@@ -64,18 +60,11 @@ public class UserProviderFactory {
"UserProvider.roster.className"};
private static void setProviders(Class[] providers) throws IllegalAccessException, InstantiationException {
userIDProvider = (UserIDProvider)providers[0].newInstance();
userPropertiesProvider = (UserPropertiesProvider)providers[1].newInstance();
userInfoProvider = (UserInfoProvider)providers[2].newInstance();
userAccountProvider = (UserAccountProvider)providers[3].newInstance();
rosterItemProvider = (RosterItemProvider)providers[4].newInstance();
}
public static UserIDProvider getUserIDProvider() {
loadProviders();
return userIDProvider;
}
public static UserPropertiesProvider getUserPropertiesProvider() {
loadProviders();
return userPropertiesProvider;
......@@ -86,21 +75,16 @@ public class UserProviderFactory {
return userInfoProvider;
}
public static UserAccountProvider getUserAccountProvider() {
loadProviders();
return userAccountProvider;
}
public static RosterItemProvider getRosterItemProvider() {
loadProviders();
return rosterItemProvider;
}
private static void loadProviders() {
if (userIDProvider == null) {
if (userInfoProvider == null) {
// Use className as a convenient object to get a lock on.
synchronized (classNames) {
if (userIDProvider == null) {
if (userInfoProvider == null) {
try {
Class[] providers = new Class[classNames.length];
for (int i = 0; i < classNames.length; i++) {
......
......@@ -13,7 +13,6 @@ package org.jivesoftware.messenger.user.spi;
import org.jivesoftware.util.CacheSizes;
import org.jivesoftware.util.StringUtils;
import org.jivesoftware.util.CacheSizes;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserInfo;
......@@ -28,25 +27,19 @@ import org.jivesoftware.messenger.user.UserInfo;
*/
public class BasicUserInfo implements UserInfo {
/**
* User id of -2 means no user id has been set yet. -1 is reserved for "anonymous user" and 0 is
* reserved for "all users".
*/
private long id = -2;
private String username = null;
private String name = " ";
private boolean nameVisible = true;
private String email;
private boolean emailVisible = false; // Hide email addresses by default
private java.util.Date creationDate;
private java.util.Date modificationDate;
/**
* <p>Create a new UserInfo with default fields.</p>
* Create a new UserInfo with default fields.
*
* @param id The user's id this info belongs to
* @param username the username.
*/
public BasicUserInfo(long id) {
this.id = id;
public BasicUserInfo(String username) {
this.username = username;
creationDate = new java.util.Date();
modificationDate = new java.util.Date();
}
......@@ -54,15 +47,14 @@ public class BasicUserInfo implements UserInfo {
/**
* <p>Create a new UserInfo given field values.</p>
*
* @param id The user's id this info belongs to
* @param username The username
* @param name The user's full name
* @param email The user's email address
* @param nameVisible True if the user's name should be visible to other users of the system
* @param emailVisible True if the user's email should be visible to other users of the system
*/
public BasicUserInfo(long id, String name, String email,
boolean nameVisible, boolean emailVisible, java.util.Date creationDate, java.util.Date modificationDate) {
this.id = id;
public BasicUserInfo(String username, String name, String email,
java.util.Date creationDate, java.util.Date modificationDate)
{
this.username = username;
this.creationDate = creationDate;
this.modificationDate = modificationDate;
if (email == null || "".equals(email)) {
......@@ -74,12 +66,10 @@ public class BasicUserInfo implements UserInfo {
if (name != null) {
this.name = name;
}
this.nameVisible = nameVisible;
this.emailVisible = emailVisible;
}
public long getId() {
return id;
public String getUsername() {
return username;
}
public String getName() {
......@@ -96,16 +86,6 @@ public class BasicUserInfo implements UserInfo {
modificationDate.setTime(System.currentTimeMillis());
}
public boolean isNameVisible() {
return nameVisible;
}
public void setNameVisible(boolean visible) throws UnauthorizedException {
nameVisible = visible;
// Update modification date
modificationDate.setTime(System.currentTimeMillis());
}
public String getEmail() {
return StringUtils.escapeHTMLTags(email);
}
......@@ -120,16 +100,6 @@ public class BasicUserInfo implements UserInfo {
modificationDate.setTime(System.currentTimeMillis());
}
public boolean isEmailVisible() {
return emailVisible;
}
public void setEmailVisible(boolean visible) throws UnauthorizedException {
emailVisible = visible;
// Update modification date
modificationDate.setTime(System.currentTimeMillis());
}
public java.util.Date getCreationDate() {
return creationDate;
}
......@@ -180,7 +150,7 @@ public class BasicUserInfo implements UserInfo {
}
public int hashCode() {
return (int)id;
return username.hashCode();
}
public boolean equals(Object object) {
......@@ -188,10 +158,10 @@ public class BasicUserInfo implements UserInfo {
return true;
}
if (object != null && object instanceof User) {
return id == ((User)object).getID();
return username.equals(((User)object).getUsername());
}
else {
return false;
}
}
}
}
\ No newline at end of file
......@@ -17,7 +17,6 @@ import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.chatbot.ChatbotManager;
import org.jivesoftware.messenger.user.*;
import java.util.Iterator;
import java.util.List;
......@@ -35,44 +34,27 @@ import javax.xml.stream.XMLStreamException;
*/
public class CachedRosterImpl extends BasicRoster implements CachedRoster {
/**
* <p>ID of the user that owns this roster.</p>
*/
private long userID;
/**
* <p>Backend storage provider for rosters.</p>
*/
private RosterItemProvider rosterItemProvider;
// TODO: we should move all routing to a single place, doing routing logic here sucks
/**
* <p>Chatbot manager used for routing roster broadcasts.</p>
*/
private ChatbotManager chatbotManager;
/**
* <p>User name of the user/chatbot that owns this roster.</p>
*/
private String username;
/**
* <p>Create a roster for the given user, pulling the existing roster items
* out of the backend storage provider.</p>
*
* @param id ID of the user that owns this roster
* @param username The username of the user that owns this roster
*/
public CachedRosterImpl(long id, String username) {
this.userID = id;
public CachedRosterImpl(String username) {
this.username = username;
rosterItemProvider = UserProviderFactory.getRosterItemProvider();
Iterator items = rosterItemProvider.getItems(userID);
Iterator items = rosterItemProvider.getItems(username);
while (items.hasNext()) {
RosterItem item = (RosterItem)items.next();
rosterItems.put(item.getJid().toBareStringPrep(), item);
}
}
public long getUserID() {
return userID;
public String getUsername() {
return username;
}
public IQRoster getReset() throws UnauthorizedException {
......@@ -137,7 +119,7 @@ public class CachedRosterImpl extends BasicRoster implements CachedRoster {
protected RosterItem provideRosterItem(RosterItem item)
throws UserAlreadyExistsException, UnauthorizedException {
item = rosterItemProvider.createItem(userID, new BasicRosterItem(item));
item = rosterItemProvider.createItem(username, new BasicRosterItem(item));
// Broadcast the roster push to the user
IQRoster roster = new IQRosterImpl();
......@@ -167,7 +149,7 @@ public class CachedRosterImpl extends BasicRoster implements CachedRoster {
// already exist
super.updateRosterItem(cachedItem);
// Update the backend data store
rosterItemProvider.updateItem(userID, cachedItem);
rosterItemProvider.updateItem(username, cachedItem);
// broadcast roster update
if (!(cachedItem.getSubStatus() == RosterItem.SUB_NONE
&& cachedItem.getAskStatus() == RosterItem.ASK_NONE)) {
......@@ -198,7 +180,7 @@ public class CachedRosterImpl extends BasicRoster implements CachedRoster {
CachedRosterItem item = (CachedRosterItem)super.deleteRosterItem(user);
if (item != null) {
// If removing the user was successful, remove the user from the backend store
rosterItemProvider.deleteItem(userID, item.getID());
rosterItemProvider.deleteItem(username, item.getID());
try {
// broadcast the update to the user
......@@ -227,27 +209,10 @@ public class CachedRosterImpl extends BasicRoster implements CachedRoster {
XMPPAddress recipient = server.createAddress(username, null);
roster.setRecipient(recipient);
roster.setOriginatingSession(server.getSession());
if (chatbotManager == null) {
chatbotManager = (ChatbotManager)ServiceLookupFactory.getLookup().lookup(ChatbotManager.class);
}
if (chatbotManager.isChatbot(recipient)) {
if (routingTable == null) {
routingTable = (RoutingTable)ServiceLookupFactory.getLookup().lookup(RoutingTable.class);
}
try {
ChannelHandler handler = routingTable.getRoute(recipient);
handler.process(roster);
}
catch (NoSuchRouteException e) {
Log.warn("Chatbot unreachable " + recipient, e);
}
}
else {
if (sessionManager == null) {
sessionManager = (SessionManager)ServiceLookupFactory.getLookup().lookup(SessionManager.class);
}
sessionManager.userBroadcast(username, roster);
if (sessionManager == null) {
sessionManager = (SessionManager)ServiceLookupFactory.getLookup().lookup(SessionManager.class);
}
sessionManager.userBroadcast(username, roster);
}
catch (XMLStreamException e) {
// We couldn't send to the user, no big deal
......@@ -259,7 +224,7 @@ public class CachedRosterImpl extends BasicRoster implements CachedRoster {
// of each field.
int size = 0;
size += CacheSizes.sizeOfObject(); // overhead of object
size += CacheSizes.sizeOfLong(); // userID
size += CacheSizes.sizeOfString(username); // username
try {
Iterator itemIter = getRosterItems();
while (itemIter.hasNext()) {
......
......@@ -24,8 +24,8 @@ public class CachedRosterProxy extends RosterProxy implements CachedRoster {
super(roster, authToken, permissions);
}
public long getUserID() {
return ((CachedRoster)roster).getUserID();
public String getUsername() {
return ((CachedRoster)roster).getUsername();
}
public IQRoster getReset() throws UnauthorizedException {
......
......@@ -21,9 +21,6 @@ import org.jivesoftware.messenger.OfflineMessageStore;
import org.jivesoftware.messenger.PacketFactory;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserManager;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
......@@ -39,14 +36,14 @@ import java.util.Iterator;
public class DbOfflineMessageStore extends BasicModule implements OfflineMessageStore {
private static final String INSERT_OFFLINE =
"INSERT INTO jiveOffline (userID, messageID, creationDate, messageSize, message) " +
"VALUES (?, ?, ?, ?, ?)";
"INSERT INTO jiveOffline (username, messageID, creationDate, messageSize, message) " +
"VALUES (?, ?, ?, ?, ?)";
private static final String LOAD_OFFLINE =
"SELECT message FROM jiveOffline WHERE userID=?";
"SELECT message FROM jiveOffline WHERE username=?";
private static final String SELECT_SIZE_OFFLINE =
"SELECT SUM(messageSize) FROM jiveOffline WHERE userID=?";
"SELECT SUM(messageSize) FROM jiveOffline WHERE username=?";
private static final String DELETE_OFFLINE =
"DELETE FROM jiveOffline WHERE userID=?";
"DELETE FROM jiveOffline WHERE username=?";
public DbOfflineMessageStore() {
super("Offline Message Store");
......@@ -58,137 +55,92 @@ public class DbOfflineMessageStore extends BasicModule implements OfflineMessage
Connection con = null;
PreparedStatement pstmt = null;
long messageID = SequenceManager.nextID(JiveConstants.OFFLINE);
String user = message.getRecipient().getNamePrep();
String username = message.getRecipient().getNamePrep();
try {
long userID = userManager.getUserID(user);
StringXMLStreamWriter serMsg = new StringXMLStreamWriter();
message.send(serMsg, 0);
String msg = serMsg.toString();
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(INSERT_OFFLINE);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
pstmt.setLong(2, messageID);
pstmt.setString(3, StringUtils.dateToMillis(new Date()));
pstmt.setInt(4, msg.length());
pstmt.setString(5, msg);
pstmt.executeUpdate();
}
catch (UserNotFoundException e) {
Log.warn("Could not store offline message for " + user +
" address " + message.getRecipient(), e);
}
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);
}
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { Log.error(e); }
}
}
}
public Iterator getMessages(String userName)
throws UnauthorizedException, UserNotFoundException {
return getMessages(userManager.getUserID(userName));
}
public Iterator getMessages(long userID) throws UnauthorizedException {
public Iterator getMessages(String username) throws UnauthorizedException {
java.util.LinkedList msgs = new java.util.LinkedList();
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_OFFLINE);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String msg = rs.getString(1);
msgs.add(packetFactory.getMessage(msg));
}
rs.close();
pstmt.close();
pstmt = con.prepareStatement(DELETE_OFFLINE);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
pstmt.executeUpdate();
}
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);
}
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 msgs.iterator();
}
public int getSize(long userID) {
public int getSize(String username) {
int size = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(SELECT_SIZE_OFFLINE);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
size = rs.getInt(1);
}
rs.close();
}
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);
}
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 size;
}
public int getSize(String userName) throws UserNotFoundException {
return getSize(userManager.getUserID(userName));
}
public PacketFactory packetFactory;
public UserManager userManager;
......
......@@ -46,11 +46,11 @@ import org.dom4j.Element;
public class DbPrivateStore extends BasicModule implements PrivateStore {
private static final String LOAD_PRIVATE =
"SELECT value FROM jivePrivate WHERE userID=? AND namespace=?";
"SELECT value FROM jivePrivate WHERE username=? AND namespace=?";
private static final String INSERT_PRIVATE =
"INSERT INTO jivePrivate (value,name,userID,namespace) VALUES (?,?,?,?)";
"INSERT INTO jivePrivate (value,name,username,namespace) VALUES (?,?,?,?)";
private static final String UPDATE_PRIVATE =
"UPDATE jivePrivate SET value=?, name=? WHERE userID=? AND namespace=?";
"UPDATE jivePrivate SET value=?, name=? WHERE username=? AND namespace=?";
// currently no delete supported, we can detect an add of an empty element and use that to
// signal a delete but that optimization doesn't seem necessary.
......@@ -73,7 +73,7 @@ public class DbPrivateStore extends BasicModule implements PrivateStore {
JiveGlobals.setProperty("xmpp.private", Boolean.toString(enabled));
}
public void add(long userID, Element data) throws UnauthorizedException {
public void add(String username, Element data) throws UnauthorizedException {
if (enabled) {
Connection con = null;
PreparedStatement pstmt = null;
......@@ -82,10 +82,17 @@ public class DbPrivateStore extends BasicModule implements PrivateStore {
data.write(writer);
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_PRIVATE);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
pstmt.setString(2, data.getNamespaceURI());
ResultSet rs = pstmt.executeQuery();
boolean update = false;
if (rs.next()) {
update = true;
}
rs.close();
pstmt.close();
if (update) {
pstmt = con.prepareStatement(UPDATE_PRIVATE);
}
else {
......@@ -93,7 +100,7 @@ public class DbPrivateStore extends BasicModule implements PrivateStore {
}
pstmt.setString(1, writer.toString());
pstmt.setString(2, data.getName());
pstmt.setLong(3, userID);
pstmt.setString(3, username);
pstmt.setString(4, data.getNamespaceURI());
pstmt.executeUpdate();
}
......@@ -101,27 +108,15 @@ public class DbPrivateStore extends BasicModule implements PrivateStore {
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);
}
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { Log.error(e); }
}
}
}
public Element get(long userID, Element data) throws UnauthorizedException {
public Element get(String username, Element data) throws UnauthorizedException {
data.clearContent();
if (enabled) {
Connection con = null;
......@@ -129,7 +124,7 @@ public class DbPrivateStore extends BasicModule implements PrivateStore {
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_PRIVATE);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
pstmt.setString(2, data.getNamespaceURI());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
......@@ -142,22 +137,10 @@ public class DbPrivateStore extends BasicModule implements PrivateStore {
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);
}
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 data;
......
......@@ -19,8 +19,6 @@ import org.jivesoftware.util.Log;
import org.jivesoftware.util.LongList;
import org.jivesoftware.messenger.XMPPAddress;
import org.jivesoftware.messenger.user.*;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
......@@ -38,10 +36,10 @@ import java.util.LinkedList;
public class DbRosterItemProvider implements RosterItemProvider {
private static final String CREATE_ROSTER_ITEM =
"INSERT INTO jiveRoster (userID, rosterID, jid, sub, ask, recv, nick) " +
"INSERT INTO jiveRoster (username, rosterID, jid, sub, ask, recv, nick) " +
"VALUES (?, ?, ?, ?, ?, ?, ?)";
public CachedRosterItem createItem(long userID, RosterItem item)
public CachedRosterItem createItem(String username, RosterItem item)
throws UserAlreadyExistsException, UnsupportedOperationException {
Connection con = null;
PreparedStatement pstmt = null;
......@@ -51,7 +49,7 @@ public class DbRosterItemProvider implements RosterItemProvider {
long rosterID = SequenceManager.nextID(JiveConstants.ROSTER);
pstmt = con.prepareStatement(CREATE_ROSTER_ITEM);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
pstmt.setLong(2, rosterID);
pstmt.setString(3, item.getJid().toBareString());
pstmt.setInt(4, item.getSubStatus().getValue());
......@@ -69,14 +67,13 @@ public class DbRosterItemProvider implements RosterItemProvider {
// Otherwise, just create a coyy of the item with the new roster ID
cachedItem = new CachedRosterItemImpl(rosterID, item);
}
insertGroups(rosterID, item.getGroups().iterator(), pstmt, con);
}
catch (SQLException e) {
throw new UserAlreadyExistsException(item.getJid().toStringPrep());
}
finally {
try { if (pstmt != null) { pstmt.close(); } }
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { Log.error(e); }
......@@ -89,7 +86,7 @@ public class DbRosterItemProvider implements RosterItemProvider {
private static final String DELETE_ROSTER_ITEM_GROUPS =
"DELETE FROM jiveRosterGroups WHERE rosterID=?";
public void updateItem(long userID, CachedRosterItem item)
public void updateItem(String username, CachedRosterItem item)
throws UserNotFoundException, UnsupportedOperationException {
Connection con = null;
PreparedStatement pstmt = null;
......@@ -162,7 +159,7 @@ public class DbRosterItemProvider implements RosterItemProvider {
private static final String DELETE_ROSTER_ITEM =
"DELETE FROM jiveRoster WHERE rosterID=?";
public void deleteItem(long userID, long rosterItemID)
public void deleteItem(String username, long rosterItemID)
throws UnsupportedOperationException {
// Only try to remove the user if they exist in the roster already:
Connection con = null;
......@@ -193,12 +190,12 @@ public class DbRosterItemProvider implements RosterItemProvider {
}
private static final String LOAD_ROSTER_IDS =
"DELETE from jiveRosterGroups WHERE userID=?";
"DELETE from jiveRosterGroups WHERE username=?";
private static final String DELETE_ROSTER =
"DELETE FROM jiveRoster WHERE userID=?";
"DELETE FROM jiveRoster WHERE username=?";
public void deleteItems(long userID) throws UnsupportedOperationException {
public void deleteItems(String username) throws UnsupportedOperationException {
Connection con = null;
PreparedStatement pstmt = null;
......@@ -206,7 +203,7 @@ public class DbRosterItemProvider implements RosterItemProvider {
LongList list = new LongList();
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_ROSTER_IDS);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(rs.getLong(1));
......@@ -217,7 +214,7 @@ public class DbRosterItemProvider implements RosterItemProvider {
pstmt.executeUpdate();
}
pstmt = con.prepareStatement(DELETE_ROSTER);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
pstmt.executeUpdate();
}
......@@ -233,17 +230,16 @@ public class DbRosterItemProvider implements RosterItemProvider {
}
private static final String COUNT_ROSTER_ITEMS =
"SELECT COUNT(rosterID) FROM jiveRoster WHERE userID=?";
"SELECT COUNT(rosterID) FROM jiveRoster WHERE username=?";
public int getItemCount(long userID) {
public int getItemCount(String username) {
int count = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(COUNT_ROSTER_ITEMS);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
......@@ -262,19 +258,18 @@ public class DbRosterItemProvider implements RosterItemProvider {
}
private static final String LOAD_ROSTER =
"SELECT jid, rosterID, sub, ask, recv, nick FROM jiveRoster WHERE userID=?";
"SELECT jid, rosterID, sub, ask, recv, nick FROM jiveRoster WHERE username=?";
private static final String LOAD_ROSTER_ITEM_GROUPS =
"SELECT groupName FROM jiveRosterGroups WHERE rosterID=? ORDER BY rank";
"SELECT groupName FROM jiveRosterGroups WHERE rosterID=? ORDER BY rank";
public Iterator getItems(long userID) {
public Iterator getItems(String username) {
LinkedList itemList = new LinkedList();
Connection con = null;
PreparedStatement pstmt = null;
LinkedList itemList = new LinkedList();
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_ROSTER);
pstmt.setLong(1, userID);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
CachedRosterItem item = new CachedRosterItemImpl(rs.getLong(2),
......@@ -314,4 +309,4 @@ public class DbRosterItemProvider implements RosterItemProvider {
}
return itemList.iterator();
}
}
}
\ 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.user.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.user.UserAccountProvider;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.database.DbConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
public class DbUserAccountProvider implements UserAccountProvider {
private static final String INSERT_USERID = "INSERT INTO jiveUserID (username,domainID,objectType,objectID) VALUES (?,?,?,?)";
private static final String INSERT_USER =
"INSERT INTO jiveUser (userID, password, name, nameVisible," +
"email, emailVisible, creationDate, modificationDate) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
public long createUser(String username, String password, String email)
throws UnauthorizedException, UserAlreadyExistsException {
if (email == null || email.length() == 0) {
email = " ";
}
long id = -1;
Connection con = null;
PreparedStatement pstmt = null;
boolean abortTransaction = false;
try {
// Reserve the name in the jiveUserID
id = SequenceManager.nextID(JiveConstants.USER);
con = DbConnectionManager.getTransactionConnection();
pstmt = con.prepareStatement(INSERT_USERID);
pstmt.setString(1, username);
pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
pstmt.setLong(3, DbUserIDProvider.USER_TYPE);
pstmt.setLong(4, id);
pstmt.executeUpdate();
// Add the user record in jiveUser
pstmt = con.prepareStatement(INSERT_USER);
pstmt.setLong(1, id);
pstmt.setString(2, password);
pstmt.setString(3, "");
pstmt.setInt(4, 1); // name visible
pstmt.setString(5, email);
pstmt.setInt(6, 0); // email visible
Date now = new Date();
pstmt.setString(7, StringUtils.dateToMillis(now));
pstmt.setString(8, StringUtils.dateToMillis(now));
pstmt.executeUpdate();
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
abortTransaction = true;
}
finally {
try {
if (pstmt != null) {
pstmt.close();
}
}
catch (Exception e) {
Log.error(e);
}
DbConnectionManager.closeTransactionConnection(con, abortTransaction);
}
if (id == -1) {
throw new UnauthorizedException("Failed to create user, please " +
"check Jive error logs for details");
}
return id;
}
private static final String DELETE_USER_ID =
"DELETE FROM jiveUserID WHERE objectID=? AND objectType=? and domainID=?";
private static final String DELETE_USER_GROUPS =
"DELETE FROM jiveGroupUser WHERE userID=?";
private static final String DELETE_USER_PROPS =
"DELETE FROM jiveUserProp WHERE userID=?";
private static final String DELETE_VCARD_PROPS =
"DELETE FROM jiveVCard WHERE userID=?";
private static final String DELETE_USER =
"DELETE FROM jiveUser WHERE userID=?";
public void deleteUser(long userID) throws UnauthorizedException {
Connection con = null;
PreparedStatement pstmt = null;
boolean abortTransaction = false;
try {
con = DbConnectionManager.getTransactionConnection();
// Remove user from all groups
pstmt = con.prepareStatement(DELETE_USER_GROUPS);
pstmt.setLong(1, userID);
pstmt.executeUpdate();
// Delete all of the users's extended properties
pstmt = con.prepareStatement(DELETE_USER_PROPS);
pstmt.setLong(1, userID);
pstmt.executeUpdate();
// Delete all of the users's vcard properties
pstmt = con.prepareStatement(DELETE_VCARD_PROPS);
pstmt.setLong(1, userID);
pstmt.executeUpdate();
// Delete the actual user entry
pstmt = con.prepareStatement(DELETE_USER);
pstmt.setLong(1, userID);
pstmt.executeUpdate();
// Delete the actual user ID entry
pstmt = con.prepareStatement(DELETE_USER_ID);
pstmt.setLong(1, userID);
pstmt.setInt(2, DbUserIDProvider.USER_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.user.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.user.UserIDProvider;
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;
/**
* <p>Implements default Jive user id lookup out of the jiveUserID table.</p>
* <p>The implementation currently hard codes the default domain since messenger only supports one domain
* (default domain means to use the Messenger domain name).</p>
*
* @author Iain Shiegoka
*/
public class DbUserIDProvider implements UserIDProvider {
/**
* <p>Object type for users.</p>
*/
public static final int USER_TYPE = 0;
/**
* <p>Object type for chatbots.</p>
*/
public static final int CHATBOT_TYPE = 1;
/**
* <p>The default domain id - the messenger domain.</p>
*/
public static final long DEFAULT_DOMAIN = 1;
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, DEFAULT_DOMAIN);
pstmt.setLong(3, USER_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 getUserID(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, DEFAULT_DOMAIN);
pstmt.setLong(3, USER_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 jiveUser";
private static final String ALL_USERS =
"SELECT userID from jiveUser";
public int getUserCount() {
int count = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(USER_COUNT);
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;
}
public LongList getUserIDs() {
LongList users = new LongList(500);
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
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 getUserIDs(int startIndex, int numResults) {
LongList users = new LongList();
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
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;
}
}
......@@ -20,7 +20,6 @@ import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserInfo;
import org.jivesoftware.messenger.user.UserInfoProvider;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.database.DbConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
......@@ -39,17 +38,16 @@ import java.sql.SQLException;
public class DbUserInfoProvider implements UserInfoProvider {
private static final String LOAD_USER_BY_ID =
"SELECT name, nameVisible, email, emailVisible, " +
"creationDate, modificationDate FROM jiveUser WHERE userID=?";
"SELECT name, email, creationDate, modificationDate FROM jiveUser WHERE username=?";
public UserInfo getInfo(long id) throws UserNotFoundException {
public UserInfo getInfo(String username) throws UserNotFoundException {
BasicUserInfo userInfo = null;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_USER_BY_ID);
pstmt.setLong(1, id);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) {
......@@ -57,64 +55,47 @@ public class DbUserInfoProvider implements UserInfoProvider {
}
// We trim() the dates before trying to parse them because some
// databases pad with extra characters when returning the data.
userInfo = new BasicUserInfo(id,
userInfo = new BasicUserInfo(username,
rs.getString(1), // name
rs.getString(3), // email
rs.getInt(2) == 1, // name visible
rs.getInt(4) == 1, // email visible
new java.util.Date(Long.parseLong(rs.getString(5).trim())), // creation date
new java.util.Date(Long.parseLong(rs.getString(6).trim()))); // modification date
}
catch (SQLException e) {
throw new UserNotFoundException("Failed to read user " + id + " from database.", e);
throw new UserNotFoundException("Failed to read user " + username + " 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.");
throw new UserNotFoundException("User "
+ username + " 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);
}
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 SAVE_USER =
"UPDATE jiveUser SET name=?, nameVisible=?, email=?," +
"emailVisible=?, creationDate=?, modificationDate=? WHERE " +
"userID=?";
"UPDATE jiveUser SET name=?,email=?,creationDate=?,modificationDate=? " +
"WHERE username=?";
public void setInfo(long id, UserInfo info) throws UserNotFoundException, UnauthorizedException {
public void setInfo(String username, UserInfo info) throws UserNotFoundException, UnauthorizedException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(SAVE_USER);
pstmt.setString(1, info.getName());
pstmt.setInt(2, info.isNameVisible() ? 1 : 0);
pstmt.setString(3, info.getEmail());
pstmt.setInt(4, info.isEmailVisible() ? 1 : 0);
pstmt.setString(5, StringUtils.dateToMillis(info.getCreationDate()));
pstmt.setString(6, StringUtils.dateToMillis(info.getModificationDate()));
pstmt.setLong(7, id);
pstmt.setString(2, info.getEmail());
pstmt.setString(3, StringUtils.dateToMillis(info.getCreationDate()));
pstmt.setString(4, StringUtils.dateToMillis(info.getModificationDate()));
pstmt.setString(5, username);
pstmt.executeUpdate();
}
catch (SQLException e) {
......@@ -122,22 +103,10 @@ public class DbUserInfoProvider implements UserInfoProvider {
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);
}
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { Log.error(e); }
}
}
}
......@@ -15,7 +15,6 @@ import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.util.Log;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserPropertiesProvider;
import org.jivesoftware.database.DbConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
......@@ -36,21 +35,21 @@ import java.util.Map;
public class DbUserPropertiesProvider implements UserPropertiesProvider {
private static final String LOAD_PROPERTIES =
"SELECT name, propValue FROM jiveUserProp WHERE userID=?";
"SELECT name, propValue FROM jiveUserProp WHERE username=?";
private static final String DELETE_PROPERTY =
"DELETE FROM jiveUserProp WHERE userID=? AND name=?";
"DELETE FROM jiveUserProp WHERE username=? AND name=?";
private static final String UPDATE_PROPERTY =
"UPDATE jiveUserProp SET propValue=? WHERE name=? AND userID=?";
"UPDATE jiveUserProp SET propValue=? WHERE name=? AND username=?";
private static final String INSERT_PROPERTY =
"INSERT INTO jiveUserProp (userID, name, propValue) VALUES (?, ?, ?)";
"INSERT INTO jiveUserProp (username, name, propValue) VALUES (?, ?, ?)";
private static final String LOAD_VPROPERTIES =
"SELECT name, propValue FROM jiveVCard WHERE userID=?";
"SELECT name, propValue FROM jiveVCard WHERE username=?";
private static final String DELETE_VPROPERTY =
"DELETE FROM jiveVCard WHERE userID=? AND name=?";
"DELETE FROM jiveVCard WHERE username=? AND name=?";
private static final String UPDATE_VPROPERTY =
"UPDATE jiveVCard SET propValue=? WHERE name=? AND userID=?";
"UPDATE jiveVCard SET propValue=? WHERE name=? AND username=?";
private static final String INSERT_VPROPERTY =
"INSERT INTO jiveVCard (userID, name, propValue) VALUES (?, ?, ?)";
"INSERT INTO jiveVCard (username, name, propValue) VALUES (?, ?, ?)";
/**
* Create a new DbUserPropertiesProvider.
......@@ -61,7 +60,7 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
/**
* Loads properties from the database.
*/
private synchronized Map loadPropertiesFromDb(long id, boolean isVcard) {
private synchronized Map loadPropertiesFromDb(String username, boolean isVcard) {
Map props = new Hashtable();
Connection con = null;
PreparedStatement pstmt = null;
......@@ -74,7 +73,7 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
else {
pstmt = con.prepareStatement(LOAD_PROPERTIES);
}
pstmt.setLong(1, id);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
props.put(rs.getString(1), rs.getString(2));
......@@ -84,22 +83,10 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
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);
}
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 props;
}
......@@ -107,7 +94,7 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
/**
* Inserts a new property into the datatabase.
*/
private void insertPropertyIntoDb(long id, String name, String value, boolean isVcard) {
private void insertPropertyIntoDb(String username, String name, String value, boolean isVcard) {
Connection con = null;
PreparedStatement pstmt = null;
......@@ -119,7 +106,7 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
else {
pstmt = con.prepareStatement(INSERT_PROPERTY);
}
pstmt.setLong(1, id);
pstmt.setString(1, username);
pstmt.setString(2, name);
pstmt.setString(3, value);
pstmt.executeUpdate();
......@@ -128,32 +115,19 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
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);
}
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { Log.error(e); }
}
}
/**
* Updates a property value in the database.
*/
private void updatePropertyInDb(long id, String name, String value, boolean isVcard) {
private void updatePropertyInDb(String username, String name, String value, boolean isVcard) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
if (isVcard) {
......@@ -164,39 +138,26 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
}
pstmt.setString(1, value);
pstmt.setString(2, name);
pstmt.setLong(3, id);
pstmt.setString(3, username);
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.error(e);
}
finally {
try {
if (pstmt != null) {
pstmt.close();
}
}
catch (Exception e) {
Log.error(e);
}
try {
if (con != null) {
con.close();
}
}
catch (Exception e) {
Log.error(e);
}
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { Log.error(e); }
}
}
/**
* Deletes a property from the db.
*/
private void deletePropertyFromDb(long id, String name, boolean isVcard) {
private void deletePropertyFromDb(String username, String name, boolean isVcard) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
if (isVcard) {
......@@ -205,7 +166,7 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
else {
pstmt = con.prepareStatement(DELETE_PROPERTY);
}
pstmt.setLong(1, id);
pstmt.setString(1, username);
pstmt.setString(2, name);
pstmt.executeUpdate();
}
......@@ -213,54 +174,42 @@ public class DbUserPropertiesProvider implements UserPropertiesProvider {
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);
}
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { Log.error(e); }
}
}
public void deleteVcardProperty(long id, String name) {
deletePropertyFromDb(id, name, true);
public void deleteVcardProperty(String username, String name) {
deletePropertyFromDb(username, name, true);
}
public void deleteUserProperty(long id, String name) {
deletePropertyFromDb(id, name, false);
public void deleteUserProperty(String username, String name) {
deletePropertyFromDb(username, name, false);
}
public void insertVcardProperty(long id, String name, String value) {
insertPropertyIntoDb(id, name, value, true);
public void insertVcardProperty(String username, String name, String value) {
insertPropertyIntoDb(username, name, value, true);
}
public void insertUserProperty(long id, String name, String value) {
insertPropertyIntoDb(id, name, value, false);
public void insertUserProperty(String username, String name, String value) {
insertPropertyIntoDb(username, name, value, false);
}
public void updateVcardProperty(long id, String name, String value) {
updatePropertyInDb(id, name, value, true);
public void updateVcardProperty(String username, String name, String value) {
updatePropertyInDb(username, name, value, true);
}
public void updateUserProperty(long id, String name, String value) {
updatePropertyInDb(id, name, value, false);
public void updateUserProperty(String username, String name, String value) {
updatePropertyInDb(username, name, value, false);
}
public Map getVcardProperties(long id) {
return loadPropertiesFromDb(id, true);
public Map getVcardProperties(String username) {
return loadPropertiesFromDb(username, true);
}
public Map getUserProperties(long id) {
return loadPropertiesFromDb(id, false);
public Map getUserProperties(String username) {
return loadPropertiesFromDb(username, false);
}
}
......@@ -14,12 +14,6 @@ package org.jivesoftware.messenger.user.spi;
import org.jivesoftware.util.Cache;
import org.jivesoftware.util.CacheManager;
import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.messenger.container.ServiceLookupFactory;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.CacheManager;
import org.jivesoftware.messenger.NameIDManager;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.CachedRoster;
import org.jivesoftware.messenger.user.RosterManager;
import org.jivesoftware.messenger.user.UserNotFoundException;
......@@ -27,39 +21,27 @@ import org.jivesoftware.messenger.user.UserNotFoundException;
public class RosterManagerImpl extends BasicModule implements RosterManager {
private Cache rosterCache = null;
private NameIDManager nameIDManager = null;
public RosterManagerImpl() {
super("Roster Manager");
}
public CachedRoster getRoster(long id) throws UserNotFoundException {
public CachedRoster getRoster(String username) throws UserNotFoundException {
if (rosterCache == null) {
rosterCache = CacheManager.getCache("userid2roster");
rosterCache = CacheManager.getCache("username2roster");
}
if (rosterCache == null) {
throw new UserNotFoundException("Could not load caches");
}
CachedRoster roster = (CachedRoster)rosterCache.get(new Long(id));
CachedRoster roster = (CachedRoster)rosterCache.get(username);
if (roster == null) {
if (nameIDManager == null) {
try {
nameIDManager =
(NameIDManager)ServiceLookupFactory.getLookup().lookup(NameIDManager.class);
}
catch (UnauthorizedException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
if (nameIDManager != null) {
// Not in cache so load a new one:
roster = new CachedRosterImpl(id, nameIDManager.getUsername(id));
rosterCache.put(new Long(id), roster);
}
// Not in cache so load a new one:
roster = new CachedRosterImpl(username);
rosterCache.put(username, roster);
}
if (roster == null) {
throw new UserNotFoundException(Long.toHexString(id));
throw new UserNotFoundException(username);
}
return roster;
}
}
}
\ No newline at end of file
......@@ -47,7 +47,6 @@ public class UserImpl implements User, Cacheable {
/**
* User id of -1 is reserved for "anonymous user" and 0 is reserved for "all users".
*/
private long id = -2;
private String username = null;
private UserInfo userInfo;
private Map properties;
......@@ -57,17 +56,11 @@ public class UserImpl implements User, Cacheable {
* Create a new DbUser with all required fields.
*
* @param username the username for the user.
* @param id the id for the user.
*/
protected UserImpl(long id, String username) {
this.id = id;
protected UserImpl(String username) {
this.username = username;
}
public long getID() {
return id;
}
public String getUsername() {
return username;
}
......@@ -83,7 +76,7 @@ public class UserImpl implements User, Cacheable {
public UserInfo getInfo() throws UserNotFoundException {
if (userInfo == null) {
userInfo = infoProvider.getInfo(id);
userInfo = infoProvider.getInfo(username);
}
return userInfo;
}
......@@ -91,7 +84,7 @@ public class UserImpl implements User, Cacheable {
public void saveInfo() throws UnauthorizedException {
if (userInfo != null) {
try {
infoProvider.setInfo(id, userInfo);
infoProvider.setInfo(username, userInfo);
}
catch (UserNotFoundException e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
......@@ -118,10 +111,10 @@ public class UserImpl implements User, Cacheable {
private void loadPropertiesFromDb(boolean isVcard) {
if (isVcard) {
vcardProps = propertiesProvider.getVcardProperties(id);
vcardProps = propertiesProvider.getVcardProperties(username);
}
else {
properties = propertiesProvider.getUserProperties(id);
properties = propertiesProvider.getUserProperties(username);
}
}
......@@ -155,7 +148,7 @@ public class UserImpl implements User, Cacheable {
updatePropertyInDb(name, value, isVcard);
// Re-add user to cache.
CacheManager.getCache("userid2user").put(new Long(id), this);
CacheManager.getCache("userCache").put(username, this);
}
}
else {
......@@ -163,25 +156,25 @@ public class UserImpl implements User, Cacheable {
insertPropertyIntoDb(name, value, isVcard);
// Re-add user to cache.
CacheManager.getCache("userid2user").put(new Long(id), this);
CacheManager.getCache("userCache").put(username, this);
}
}
private void insertPropertyIntoDb(String name, String value, boolean vcard) throws UnauthorizedException {
if (vcard) {
propertiesProvider.insertVcardProperty(id, name, value);
propertiesProvider.insertVcardProperty(username, name, value);
}
else {
propertiesProvider.insertUserProperty(id, name, value);
propertiesProvider.insertUserProperty(username, name, value);
}
}
private void updatePropertyInDb(String name, String value, boolean vcard) throws UnauthorizedException {
if (vcard) {
propertiesProvider.updateVcardProperty(id, name, value);
propertiesProvider.updateVcardProperty(username, name, value);
}
else {
propertiesProvider.updateUserProperty(id, name, value);
propertiesProvider.updateUserProperty(username, name, value);
}
}
......@@ -208,16 +201,16 @@ public class UserImpl implements User, Cacheable {
deletePropertyFromDb(name, isVcard);
// Re-add user to cache.
CacheManager.getCache("userid2user").put(new Long(id), this);
CacheManager.getCache("userCache").put(username, this);
}
}
private void deletePropertyFromDb(String name, boolean vcard) throws UnauthorizedException {
if (vcard) {
propertiesProvider.deleteVcardProperty(id, name);
propertiesProvider.deleteVcardProperty(username, name);
}
else {
propertiesProvider.deleteUserProperty(id, name);
propertiesProvider.deleteUserProperty(username, name);
}
}
......@@ -239,20 +232,20 @@ public class UserImpl implements User, Cacheable {
public CachedRoster getRoster() throws UnauthorizedException {
CachedRoster roster = null;
if (CacheManager.getCache("userid2roster").get(new Long(this.id)) != null) {
if (CacheManager.getCache("username2roster").get(username) != null) {
// Check for a cached roster:
roster = (CachedRoster)CacheManager.getCache("userid2roster").get(new Long(this.id));
roster = (CachedRoster)CacheManager.getCache("username2roster").get(username);
}
else {
// Not in cache so load a new one:
roster = new CachedRosterImpl(id, username);
CacheManager.getCache("userid2roster").put(new Long(this.id), roster);
roster = new CachedRosterImpl(username);
CacheManager.getCache("userame2roster").put(username, roster);
}
return roster;
}
public Permissions getPermissions(AuthToken auth) {
if (auth.getUserID() == id) {
if (auth.getUsername() == username) {
return USER_ADMIN_PERMS;
}
else {
......@@ -305,7 +298,7 @@ public class UserImpl implements User, Cacheable {
}
public int hashCode() {
return (int)id;
return username.hashCode();
}
public boolean equals(Object object) {
......@@ -313,7 +306,7 @@ public class UserImpl implements User, Cacheable {
return true;
}
if (object != null && object instanceof User) {
return id == ((User)object).getID();
return username.equals(((User)object).getUsername());
}
else {
return false;
......
......@@ -39,18 +39,8 @@ public class UserInfoProxy implements UserInfo {
this.permissions = permissions;
}
public long getId() {
return info.getId();
}
public String getName() {
if (isNameVisible() || permissions.hasPermission(Permissions.SYSTEM_ADMIN |
Permissions.USER_ADMIN)) {
return info.getName();
}
else {
return null;
}
return info.getName();
}
public void setName(String name) throws UnauthorizedException {
......@@ -62,27 +52,8 @@ public class UserInfoProxy implements UserInfo {
}
}
public boolean isNameVisible() {
return info.isNameVisible();
}
public void setNameVisible(boolean visible) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
info.setNameVisible(visible);
}
else {
throw new UnauthorizedException();
}
}
public String getEmail() {
if (isEmailVisible() || permissions.hasPermission(Permissions.SYSTEM_ADMIN |
Permissions.USER_ADMIN)) {
return info.getEmail();
}
else {
return null;
}
return info.getEmail();
}
public void setEmail(String email) throws UnauthorizedException {
......@@ -94,19 +65,6 @@ public class UserInfoProxy implements UserInfo {
}
}
public boolean isEmailVisible() {
return info.isEmailVisible();
}
public void setEmailVisible(boolean visible) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
info.setEmailVisible(visible);
}
else {
throw new UnauthorizedException();
}
}
public Date getCreationDate() {
return info.getCreationDate();
}
......
......@@ -11,13 +11,11 @@
package org.jivesoftware.messenger.user.spi;
import org.jivesoftware.database.DatabaseObjectFactory;
import org.jivesoftware.messenger.container.ServiceLookupFactory;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserManager;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.database.DatabaseObjectFactory;
import java.util.Iterator;
import java.util.NoSuchElementException;
......@@ -43,16 +41,16 @@ import java.util.NoSuchElementException;
*/
public class UserIterator implements Iterator {
private long[] elements;
private String[] elements;
private int currentIndex = -1;
private Object nextElement = null;
private DatabaseObjectFactory objectFactory;
private UserDOFactory objectFactory;
/**
* Creates a new UserIterator.
*/
public UserIterator(long[] elements)
public UserIterator(String[] elements)
throws UnauthorizedException {
this.elements = elements;
......@@ -60,7 +58,7 @@ public class UserIterator implements Iterator {
this.objectFactory = new UserDOFactory();
}
private class UserDOFactory implements DatabaseObjectFactory {
private class UserDOFactory {
private UserManager userManager;
public UserDOFactory() throws UnauthorizedException {
......@@ -68,9 +66,9 @@ public class UserIterator implements Iterator {
(UserManager)ServiceLookupFactory.getLookup().lookup(UserManager.class);
}
public Object loadObject(long id) {
public Object loadObject(String username) {
try {
User user = userManager.getUser(id);
User user = userManager.getUser(username);
return user;
}
catch (UserNotFoundException e) { /* ignore */
......
......@@ -11,15 +11,22 @@
package org.jivesoftware.messenger.user.spi;
import org.jivesoftware.util.Cache;
import org.jivesoftware.util.CacheManager;
import org.jivesoftware.messenger.container.BasicModule;
import org.jivesoftware.messenger.container.Container;
import org.jivesoftware.util.StringUtils;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.NodePrep;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.*;
import org.jivesoftware.database.DbConnectionManager;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Database implementation of the UserManager interface.
......@@ -39,24 +46,30 @@ import java.util.Iterator;
*/
public class UserManagerImpl extends BasicModule implements UserManager {
private Cache id2userCache;
private Cache name2idCache;
private static final String USER_COUNT = "SELECT count(*) FROM jiveUser";
private static final String ALL_USERS = "SELECT username from jiveUser";
private static final String INSERT_USER =
"INSERT INTO jiveUser (username,password,name,email,creationDate,modificationDate) " +
"VALUES (?,?,?,?,?,?)";
private static final String DELETE_USER_GROUPS =
"DELETE FROM jiveGroupUser WHERE username=?";
private static final String DELETE_USER_PROPS =
"DELETE FROM jiveUserProp WHERE username=?";
private static final String DELETE_VCARD_PROPS =
"DELETE FROM jiveVCard WHERE username=?";
private static final String DELETE_USER =
"DELETE FROM jiveUser WHERE username=?";
private UserIDProvider userIDProvider = UserProviderFactory.getUserIDProvider();
private UserAccountProvider userAccountProvider =
UserProviderFactory.getUserAccountProvider();
private Cache userCache;
public UserManagerImpl() {
super("User Manager");
}
private void initializeCaches() {
CacheManager.initializeCache("username2userid", 128 * 1024); // 1/8 MB
CacheManager.initializeCache("userid2user", 521 * 1024); // 1/2 MB
CacheManager.initializeCache("userid2roster", 521 * 1024); // 1/2 MB
id2userCache = CacheManager.getCache("userid2user");
name2idCache = CacheManager.getCache("username2userid");
CacheManager.initializeCache("userCache", 512*1024);
CacheManager.initializeCache("username2roster", 512*1024);
userCache = CacheManager.getCache("userCache");
}
public User createUser(String username, String password, String email)
......@@ -75,7 +88,34 @@ public class UserManagerImpl extends BasicModule implements UserManager {
catch (UserNotFoundException unfe) {
// The user doesn't already exist so we can create a new user
try {
newUser = getUser(userAccountProvider.createUser(username, password, email));
if (email == null || email.length() == 0) {
email = " ";
}
Connection con = null;
PreparedStatement pstmt = null;
boolean abortTransaction = false;
try {
con = DbConnectionManager.getTransactionConnection();
pstmt = con.prepareStatement(INSERT_USER);
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.setString(3, "");
pstmt.setString(5, email);
Date now = new Date();
pstmt.setString(7, StringUtils.dateToMillis(now));
pstmt.setString(8, StringUtils.dateToMillis(now));
pstmt.execute();
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
abortTransaction = true;
}
finally {
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { Log.error(e); }
DbConnectionManager.closeTransactionConnection(con, abortTransaction);
}
newUser = getUser(username);
}
catch (UserNotFoundException e) {
throw new UnauthorizedException("Created an account but could not load it. username: "
......@@ -85,30 +125,17 @@ public class UserManagerImpl extends BasicModule implements UserManager {
return newUser;
}
public User getUser(long userID) throws UserNotFoundException {
User user = (User)id2userCache.get(userID);
if (user == null) {
String username = userIDProvider.getUsername(userID);
user = loadUser(userID, username);
}
return user;
}
public User getUser(String username) throws UserNotFoundException {
if (username == null) {
throw new UserNotFoundException("Username with null value is not valid.");
}
username = NodePrep.prep(username);
User user = null;
Long userIDLong = (Long)name2idCache.get(username);
if (userIDLong == null) {
long userID = userIDProvider.getUserID(username);
user = loadUser(userID, username);
User user = (User)userCache.get(username);
if (user == null) {
user = loadUser(username);
}
else {
user = (User)id2userCache.get(userIDLong);
user = (User)userCache.get(username);
}
if (user == null) {
throw new UserNotFoundException();
......@@ -117,49 +144,139 @@ public class UserManagerImpl extends BasicModule implements UserManager {
return user;
}
public long getUserID(String username) throws UserNotFoundException {
username = NodePrep.prep(username);
Long userIDLong = (Long)name2idCache.get(username);
// If ID wan't found in cache, load it up and put it there.
if (userIDLong == null) {
long userID = userIDProvider.getUserID(username);
User user = loadUser(userID, username);
return user.getID();
}
return userIDLong;
}
private User loadUser(long userID, String username) {
User user = new UserImpl(userID, username);
Long userIDLong = userID;
id2userCache.put(userIDLong, user);
name2idCache.put(username, userIDLong);
private User loadUser(String username) {
User user = new UserImpl(username);
userCache.put(username, user);
return user;
}
public void deleteUser(User user) throws UnauthorizedException {
userAccountProvider.deleteUser(user.getID());
// Expire user caches.
id2userCache.remove(user.getID());
name2idCache.remove(user.getUsername());
}
public void deleteUser(long userID)
throws UnauthorizedException, UserNotFoundException {
deleteUser((User)id2userCache.get(userID));
String username = user.getUsername();
Connection con = null;
PreparedStatement pstmt = null;
boolean abortTransaction = false;
try {
con = DbConnectionManager.getTransactionConnection();
// Remove user from all groups
pstmt = con.prepareStatement(DELETE_USER_GROUPS);
pstmt.setString(1, username);
pstmt.execute();
pstmt.close();
// Delete all of the users's extended properties
pstmt = con.prepareStatement(DELETE_USER_PROPS);
pstmt.setString(1, username);
pstmt.execute();
pstmt.close();
// Delete all of the users's vcard properties
pstmt = con.prepareStatement(DELETE_VCARD_PROPS);
pstmt.setString(1, username);
pstmt.execute();
pstmt.close();
// Delete the actual user entry
pstmt = con.prepareStatement(DELETE_USER);
pstmt.setString(1, username);
pstmt.execute();
}
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);
}
// Expire user cache.
userCache.remove(user.getUsername());
}
public int getUserCount() {
return userIDProvider.getUserCount();
int count = 0;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(USER_COUNT);
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;
}
public Iterator users() throws UnauthorizedException {
return new UserIterator(userIDProvider.getUserIDs().toArray());
List<String> users = new ArrayList<String>(500);
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
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.getString(1));
}
rs.close();
}
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 new UserIterator((String [])users.toArray());
}
public Iterator users(int startIndex, int numResults) throws UnauthorizedException {
return new UserIterator(userIDProvider.getUserIDs(startIndex, numResults).toArray());
List<String> users = new ArrayList<String>();
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(ALL_USERS);
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.getString(1));
}
else {
break;
}
}
rs.close();
}
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 new UserIterator((String [])users.toArray());
}
// #####################################################################
......
......@@ -49,14 +49,6 @@ public class UserManagerProxy implements UserManager {
return userManager.createUser(username, password, email);
}
public User getUser(long userID) throws UserNotFoundException {
User user = userManager.getUser(userID);
Permissions userPermissions = user.getPermissions(auth);
Permissions newPermissions = new Permissions(permissions, userPermissions);
return new UserProxy(user, auth, newPermissions);
}
public User getUser(String username) throws UserNotFoundException {
User user = userManager.getUser(username.toLowerCase());
Permissions userPermissions = user.getPermissions(auth);
......@@ -65,10 +57,6 @@ public class UserManagerProxy implements UserManager {
return new UserProxy(user, auth, newPermissions);
}
public long getUserID(String username) throws UserNotFoundException {
return userManager.getUserID(username);
}
public void deleteUser(User user) throws UnauthorizedException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
userManager.deleteUser(user);
......@@ -78,15 +66,6 @@ public class UserManagerProxy implements UserManager {
}
}
public void deleteUser(long userID) throws UnauthorizedException, UserNotFoundException {
if (permissions.hasPermission(Permissions.SYSTEM_ADMIN | Permissions.USER_ADMIN)) {
userManager.deleteUser(userID);
}
else {
throw new UnauthorizedException();
}
}
public int getUserCount() {
return userManager.getUserCount();
}
......
......@@ -30,24 +30,22 @@ final public class UserPrivateData {
private final Map settings = new HashMap();
private List elementList = new ArrayList();
private PrivateStore privateStore;
private long ID;
private String username;
final String settingsNamespace = "jive:user:settings";
final String settingsElementName = "personal_settings";
final Namespace NS = Namespace.get(settingsNamespace);
final QName namespace = DocumentHelper.createQName(settingsElementName, NS);
public UserPrivateData() {
}
public void setState(long id, PrivateStore privateStore) {
public void setState(String username, PrivateStore privateStore) {
this.privateStore = privateStore;
this.ID = id;
this.username = username;
try {
final Element element = privateStore.get(this.ID, DocumentHelper.createElement(namespace));
final Element element = privateStore.get(username, DocumentHelper.createElement(namespace));
final List list = element.elements();
final Iterator iter = list.iterator();
......@@ -106,7 +104,7 @@ final public class UserPrivateData {
}
try {
privateStore.add(this.ID, element);
privateStore.add(username, element);
}
catch (Exception ex) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), ex);
......
......@@ -41,10 +41,6 @@ public class UserProxy implements User {
this.permissions = permissions;
}
public long getID() {
return user.getID();
}
public String getUsername() {
return user.getUsername();
}
......
......@@ -128,7 +128,7 @@ public class WebManager extends WebBean {
public User getUser() {
User pageUser = null;
try {
pageUser = getUserManager().getUser(getAuthToken().getUserID());
pageUser = getUserManager().getUser(getAuthToken().getUsername());
}
catch (UserNotFoundException ex) {
Log.error(ex);
......
......@@ -27,16 +27,12 @@
</p>
<% } else if (exception instanceof UserNotFoundException) {
String userID = ParamUtils.getParameter(request,"userID");
String username = ParamUtils.getParameter(request,"username");
if (userID == null) {
userID = username;
}
%>
<p>
The requested user
<% if (userID != null) { %>
(id: <%= userID %>)
<% if (username != null) { %>
(username: <%= username %>)
<% } %>
was not found.
</p>
......
......@@ -58,7 +58,7 @@
UserManager userManager = (UserManager)lookup.lookup(UserManager.class);
User pageUser = null;
try {
pageUser = userManager.getUser(authToken.getUserID());
pageUser = userManager.getUser(authToken.getUsername());
}
catch (UserNotFoundException ignored) {}
......
......@@ -49,7 +49,7 @@
// Handle a "message" click:
if (request.getParameter("message") != null) {
response.sendRedirect("user-message.jsp?userID=" + user.getID());
response.sendRedirect("user-message.jsp?username=" + user.getUsername());
return;
}
......
......@@ -18,14 +18,14 @@
<% // Get parameters
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
// Load user object
User user = admin.getUserManager().getUser(userID);
User user = admin.getUserManager().getUser(username);
// Handle button clicks:
if (request.getParameter("details") != null) {
response.sendRedirect("user-properties.jsp?userID=" + userID);
response.sendRedirect("user-properties.jsp?username=" + username);
return;
}
......@@ -51,7 +51,7 @@ User created successfully!
</p>
<form action="user-create-success.jsp">
<input type="hidden" name="userID" value="<%= userID %>">
<input type="hidden" name="username" value="<%= username %>">
<center>
<input type="submit" name="details" value="Go to User Details">
......
......@@ -47,8 +47,6 @@
String email = ParamUtils.getParameter(request,"email");
String password = ParamUtils.getParameter(request,"password");
String passwordConfirm = ParamUtils.getParameter(request,"passwordConfirm");
boolean nameVisible = ParamUtils.getBooleanParameter(request,"nameVisible",true);
boolean emailVisible = ParamUtils.getBooleanParameter(request,"emailVisible",false);
// Handle a cancel
if (cancel) {
......@@ -79,12 +77,10 @@
if (name != null) {
newUser.getInfo().setName(name);
}
newUser.getInfo().setNameVisible(nameVisible);
newUser.getInfo().setEmailVisible(emailVisible);
newUser.saveInfo();
// Successful, so redirect
response.sendRedirect("user-create-success.jsp?userID=" + newUser.getID());
response.sendRedirect("user-create-success.jsp?username=" + newUser.getUsername());
return;
}
catch (UserAlreadyExistsException e) {
......@@ -209,47 +205,6 @@ Use the form below to create a new user in the system.
<% } %>
</td>
</tr>
<tr class="jive-odd" valign="top">
<td>
Privacy:
</td>
<td>
<table style="border-width:0px;" cellspacing="2" cellpadding="0" border="0" width="100%">
<tr>
<td width="1%" nowrap>
Show Name:
</td>
<td width="1%" nowrap>
<input type="radio" name="nameVisible" value="true" <%= ((nameVisible) ? "checked" : "") %> id="nv01">
<label for="nv01">Yes</label> &nbsp;
</td>
<td width="1%" nowrap>
<input type="radio" name="nameVisible" value="false" <%= ((!nameVisible) ? "checked" : "") %> id="nv02">
<label for="nv02">No</label> &nbsp;
</td>
<td width="97%">
&nbsp;
</td>
</tr>
<tr>
<td width="1%" nowrap>
Show Email:
</td>
<td width="1%" nowrap>
<input type="radio" name="emailVisible" value="true" <%= ((emailVisible) ? "checked" : "") %> id="ev01">
<label for="ev01">Yes</label> &nbsp;
</td>
<td width="1%" nowrap>
<input type="radio" name="emailVisible" value="false" <%= ((!emailVisible) ? "checked" : "") %> id="ev02">
<label for="ev02">No</label> &nbsp;
</td>
<td width="97%">
&nbsp;
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
......
......@@ -15,22 +15,22 @@
<% // Get parameters //
boolean cancel = request.getParameter("cancel") != null;
boolean delete = request.getParameter("delete") != null;
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
// Handle a cancel
if (cancel) {
response.sendRedirect("user-properties.jsp?userID=" + userID);
response.sendRedirect("user-properties.jsp?username=" + username);
return;
}
// Load the user object
User user = admin.getUserManager().getUser(userID);
User user = admin.getUserManager().getUser(username);
// Handle a user delete:
if (delete) {
admin.getUserManager().deleteUser(user);
// Deleted your own user account, force login
if (userID == admin.getAuthToken().getUserID()){
if (username.equals(admin.getAuthToken().getUsername())){
session.removeAttribute("jive.admin.authToken");
response.sendRedirect("login.jsp");
}
......@@ -63,7 +63,7 @@
<p>
Are you sure you want to delete the user
<b><a href="user-properties.jsp?userID=<%= user.getID() %>"><%= user.getUsername() %></a></b>
<b><a href="user-properties.jsp?username=<%= user.getUsername() %>"><%= user.getUsername() %></a></b>
from the system?
</p>
......@@ -75,7 +75,7 @@ from the system?
</c:if>
<form action="user-delete.jsp">
<input type="hidden" name="userID" value="<%= userID %>">
<input type="hidden" name="username" value="<%= username %>">
<input type="submit" name="delete" value="Delete User">
<input type="submit" name="cancel" value="Cancel">
</form>
......
......@@ -17,24 +17,22 @@
<% // Get parameters
boolean save = ParamUtils.getBooleanParameter(request,"save");
boolean success = ParamUtils.getBooleanParameter(request,"success");
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
String name = ParamUtils.getParameter(request,"name");
String email = ParamUtils.getParameter(request,"email");
boolean nameVisible = ParamUtils.getBooleanParameter(request,"nameVisible");
boolean emailVisible = ParamUtils.getBooleanParameter(request,"emailVisible");
// Handle a cancel
if (request.getParameter("cancel") != null) {
response.sendRedirect("user-properties.jsp?userID=" + userID);
response.sendRedirect("user-properties.jsp?username=" + username);
return;
}
// Load the user object
User user = admin.getUserManager().getUser(userID);
User user = admin.getUserManager().getUser(username);
// Get a private data manager //
final PrivateStore privateStore = admin.getPrivateStore();
userData.setState( user.getID(), privateStore );
userData.setState( user.getUsername(), privateStore );
// Handle a save
Map errors = new HashMap();
......@@ -49,12 +47,10 @@
if (errors.size() == 0) {
user.getInfo().setEmail(email);
user.getInfo().setName(name);
user.getInfo().setNameVisible(nameVisible);
user.getInfo().setEmailVisible(emailVisible);
user.saveInfo();
// Changes good, so redirect
response.sendRedirect("user-edit-form.jsp?success=true&userID=" + userID);
response.sendRedirect("user-edit-form.jsp?success=true&username=" + username);
return;
}
}
......@@ -62,11 +58,9 @@
<c:set var="sbar" value="users" scope="page" />
<!-- Define BreadCrumbs -->
<c:set var="title" value="Edit User Properties" />
<c:set var="breadcrumbs" value="${admin.breadCrumbs}" />
......@@ -93,18 +87,10 @@
Use the form below to edit user properties.
</td></tr>
<input type="hidden" name="userID" value="<%= userID %>">
<input type="hidden" name="username" value="<%= username %>">
<input type="hidden" name="save" value="true">
<tr class="jive-even">
<td class="jive-label">
User ID:
</td>
<td>
<%= user.getID() %>
</td>
</tr>
<tr class="jive-odd">
<td>
Username:
......@@ -147,47 +133,6 @@ Use the form below to edit user properties.
<% } %>
</td>
</tr>
<tr class="jive-odd" valign="top">
<td class="jive-label">
Privacy:
</td>
<td>
<table style="border-width:0px;" cellpadding="2" cellspacing="0" border="0" width="100%">
<tr>
<td width="1%" nowrap>
Show Name:
</td>
<td width="1%" nowrap>
<input type="radio" name="nameVisible" value="true" <%= ((user.getInfo().isNameVisible()) ? "checked" : "") %> id="nv01">
<label for="nv01">Yes</label> &nbsp;
</td>
<td width="1%" nowrap>
<input type="radio" name="nameVisible" value="false" <%= ((!user.getInfo().isNameVisible()) ? "checked" : "") %> id="nv02">
<label for="nv02">No</label> &nbsp;
</td>
<td width="97%">
&nbsp;
</td>
</tr>
<tr>
<td width="1%" nowrap>
Show Email:
</td>
<td width="1%" nowrap>
<input type="radio" name="emailVisible" value="true" <%= ((user.getInfo().isEmailVisible()) ? "checked" : "") %> id="ev01">
<label for="ev01">Yes</label> &nbsp;
</td>
<td width="1%" nowrap>
<input type="radio" name="emailVisible" value="false" <%= ((!user.getInfo().isEmailVisible()) ? "checked" : "") %> id="ev02">
<label for="ev02">No</label> &nbsp;
</td>
<td width="97%">
&nbsp;
</td>
</td>
</table>
</td>
</tr>
</table>
<br>
......
......@@ -14,16 +14,16 @@
<% // Get parameters //
boolean cancel = request.getParameter("cancel") != null;
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
// Handle a cancel
if (cancel) {
response.sendRedirect("user-edit-form.jsp?userID=" + userID);
response.sendRedirect("user-edit-form.jsp?username=" + username);
return;
}
// Load the user object
User user = userManager.getUser(userID);
User user = userManager.getUser(username);
%>
<jsp:include page="header.jsp" flush="true" />
......@@ -33,8 +33,8 @@
String[][] breadcrumbs = {
{ "Home", "main.jsp" },
{ "User Summary", "user-summary.jsp" },
{ "Edit User", "user-edit-form.jsp?userID="+userID },
{ title, "user-email.jsp?userID="+userID }
{ "Edit User", "user-edit-form.jsp?username="+username },
{ title, "user-email.jsp?username="+username }
};
%>
<jsp:include page="title.jsp" flush="true" />
......@@ -44,7 +44,7 @@ Use the form below to send an email to the user.
</p>
<form action="user-email.jsp" name="emailform">
<input type="hidden" name="userID" value="<%= userID %>">
<input type="hidden" name="username" value="<%= username %>">
<div class="jive-table">
<table cellpadding="3" cellspacing="1" border="0" width="100%">
......@@ -59,7 +59,7 @@ Use the form below to send an email to the user.
</td>
<td>
<%= pageUser.getUsername() %> &lt;<%= pageUser.getInfo().getEmail() %>&gt;
(<a href="user-edit-form.jsp?userID=<%= user.getID() %>">Edit User</a>)
(<a href="user-edit-form.jsp?username=<%= user.getUsername() %>">Edit User</a>)
</td>
</tr>
<tr>
......
......@@ -18,7 +18,7 @@
<c:set var="sbar" value="session" scope="page" />
<% // Get parameters
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
boolean send = ParamUtils.getBooleanParameter(request,"send");
boolean success = ParamUtils.getBooleanParameter(request,"success");
boolean sendToAll = ParamUtils.getBooleanParameter(request,"sendToAll");
......@@ -47,20 +47,20 @@
// Handle a cancel
if (request.getParameter("cancel") != null) {
if (userID == -1L) {
if (username == null) {
response.sendRedirect("session-summary.jsp");
return;
}
else {
response.sendRedirect("user-properties.jsp?userID=" + userID);
response.sendRedirect("user-properties.jsp?username=" + username);
return;
}
}
// Get the user - a user might not be passed in if this is a system-wide message
User user = null;
if (userID != -1L) {
user = admin.getUserManager().getUser(userID);
if (username != null) {
user = admin.getUserManager().getUser(username);
}
// Get the session manager
......@@ -96,7 +96,7 @@
sessionManager.sendServerMessage(XMPPAddress.parseJID(jid),null,message);
}
}
response.sendRedirect("user-message.jsp?success=true&userID=" + userID + "&tabs=" + tabs);
response.sendRedirect("user-message.jsp?success=true&username=" + username + "&tabs=" + tabs);
return;
}
}
......@@ -154,7 +154,7 @@ function updateSelect(el) {
</script>
<form action="user-message.jsp" method="post" name="f">
<input type="hidden" name="userID" value="<%= userID %>">
<input type="hidden" name="username" value="<%= username %>">
<input type="hidden" name="tabs" value="<%= tabs %>">
<input type="hidden" name="send" value="true">
<% if (sess != null) { %>
......
......@@ -29,10 +29,10 @@
<% // Get parameters //
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
// Load the user object
User user = admin.getUserManager().getUser(userID);
User user = admin.getUserManager().getUser(username);
%>
......@@ -46,7 +46,7 @@ User password updated successfully.
</p>
<form action="user-properties.jsp">
<input type="hidden" name="userID" value="<%= user.getID() %>">
<input type="hidden" name="username" value="<%= user.getUsername() %>">
<input type="submit" value="Back to user properties">
</form>
......
......@@ -16,18 +16,18 @@
<% // Get parameters //
boolean cancel = request.getParameter("cancel") != null;
boolean update = request.getParameter("update") != null;
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
String password = ParamUtils.getParameter(request,"password");
String passwordConfirm = ParamUtils.getParameter(request,"passwordConfirm");
// Handle a cancel
if (cancel) {
response.sendRedirect("user-properties.jsp?userID=" + userID);
response.sendRedirect("user-properties.jsp?username=" + username);
return;
}
// Load the user object
User user = admin.getUserManager().getUser(userID);
User user = admin.getUserManager().getUser(username);
// Handle a password update:
boolean errors = false;
......@@ -36,7 +36,7 @@
if (password != null && passwordConfirm != null && password.equals(passwordConfirm)) {
user.setPassword(password);
// Done, so redirect
response.sendRedirect("user-password-success.jsp?userID=" + userID);
response.sendRedirect("user-password-success.jsp?username=" + username);
return;
}
else {
......@@ -80,7 +80,7 @@ Use the form below to change the user's password
</td></tr>
<input type="hidden" name="userID" value="<%= userID %>">
<input type="hidden" name="username" value="<%= username %>">
<tr class="jive-even">
......@@ -88,7 +88,7 @@ Use the form below to change the user's password
User ID:
</td>
<td>
<%= user.getID() %>
<%= user.getUsername() %>
</td>
</tr>
<tr class="jive-odd">
......
......@@ -20,7 +20,6 @@
boolean delete = request.getParameter("delete") != null;
boolean email = request.getParameter("email") != null;
boolean password = request.getParameter("password") != null;
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
// Handle a cancel
......@@ -31,26 +30,26 @@
// Handle a delete
if (delete) {
response.sendRedirect("user-delete.jsp?userID=" + userID);
response.sendRedirect("user-delete.jsp?username=" + username);
return;
}
// Handle an email
if (email) {
response.sendRedirect("user-email.jsp?userID=" + userID);
response.sendRedirect("user-email.jsp?username=" + username);
return;
}
// Handle an email
if (password) {
response.sendRedirect("user-password.jsp?userID=" + userID);
response.sendRedirect("user-password.jsp?username=" + username);
return;
}
// Load the user object
User user = null;
try {
user = admin.getUserManager().getUser(userID);
user = admin.getUserManager().getUser(username);
}
catch (UserNotFoundException unfe) {
user = admin.getUserManager().getUser(username);
......@@ -64,7 +63,7 @@
<%
// Get a private data manager //
final PrivateStore privateStore = admin.getPrivateStore();
userData.setState( user.getID(), privateStore );
userData.setState( user.getUsername(), privateStore );
String nickname = userData.getProperty( "nickname" );
if(nickname == null){
nickname = "";
......@@ -90,14 +89,6 @@
Below is a summary of user properties. Use the tabs above to do things like edit user properties,
send the user a message (if they're online) or delete the user.
</td></tr>
<tr class="jive-even">
<td wrap width="1%">
User ID:
</td>
<td>
<%= user.getID() %>
</td>
</tr>
<tr class="jive-odd">
<td wrap width="1%">
Username:
......@@ -147,16 +138,8 @@ send the user a message (if they're online) or delete the user.
<% } else { %>
<% if (user.getInfo().isNameVisible()) { %>
<%= user.getInfo().getName() %>
<% } else { %>
<i><%= user.getInfo().getName() %></i>
<% } %>
<% } %>
</td>
</tr>
......@@ -173,28 +156,11 @@ send the user a message (if they're online) or delete the user.
<% } else { %>
<% if (user.getInfo().isEmailVisible()) { %>
<a href="mailto:<%= user.getInfo().getEmail() %>"><%= user.getInfo().getEmail() %></a>
<% } else { %>
<i><a href="mailto:<%= user.getInfo().getEmail() %>"><%= user.getInfo().getEmail() %></a></i>
<% } %>
<% } %>
</td>
</tr>
<tr class="jive-odd">
<td wrap>
Privacy:
</td>
<td>
Show Name: <b><%= ((user.getInfo().isNameVisible()) ? "Yes" : "No") %></b>,
Show Email: <b><%= ((user.getInfo().isEmailVisible()) ? "Yes" : "No") %></b>
</td>
</tr>
<tr class="jive-even">
<td wrap width="1%">
Registered:
......
......@@ -24,7 +24,6 @@
// Get parameters
boolean search = ParamUtils.getBooleanParameter(request,"search");
long userID = ParamUtils.getLongParameter(request,"userID",-1L);
String username = ParamUtils.getParameter(request,"username");
// Handle a cancel
......@@ -38,20 +37,14 @@
if (search) {
User user = null;
try {
user = admin.getUserManager().getUser(userID);
user = admin.getUserManager().getUser(username);
}
catch (UserNotFoundException e1) {
errors.put("userID","userID");
try {
user = admin.getUserManager().getUser(username);
}
catch (Exception e2) {
errors.put("username","username");
}
catch (Exception e2) {
errors.put("username","username");
}
if (user != null) {
// found the user, so redirect to the user properties page:
response.sendRedirect("user-properties.jsp?userID=" + user.getID());
response.sendRedirect("user-properties.jsp?username=" + user.getUsername());
return;
}
}
......@@ -74,14 +67,6 @@ or username.
<input type="hidden" name="search" value="true">
<tr class="jive-even">
<td>
User ID:
</td>
<td>
<input type="text" name="userID" value="<%= ((userID!=-1L) ? ""+userID : "") %>" size="5" maxlength="10">
</td>
</tr>
<tr class="">
<td align="center">
or
......
......@@ -126,7 +126,7 @@ Sorted by User ID
<% } %>
</td>
<td width="30%">
<a href="user-properties.jsp?userID=<%= user.getID() %>"><%= user.getUsername() %></a>
<a href="user-properties.jsp?username=<%= user.getUsername() %>"><%= user.getUsername() %></a>
</td>
<td width="40%">
<%= user.getInfo().getName() %>
......@@ -135,12 +135,12 @@ Sorted by User ID
<%= dateFormatter.format(user.getInfo().getCreationDate()) %>
</td>
<td width="1%" align="center">
<a href="user-edit-form.jsp?userID=<%= user.getID() %>"
<a href="user-edit-form.jsp?username=<%= user.getUsername() %>"
title="Click to edit..."
><img src="images/edit-16x16.gif" width="17" height="17" border="0"></a>
</td>
<td width="1%" align="center">
<a href="user-delete.jsp?userID=<%= user.getID() %>"
<a href="user-delete.jsp?username=<%= user.getUsername() %>"
title="Click to delete..."
><img src="images/button_delete.gif" width="17" height="17" border="0"></a>
</td>
......
......@@ -15,16 +15,16 @@
<% ad.init(request, response, session, application, out ); %>
<c:set var="userID" value="${param.userID}" />
<c:set var="username" value="${param.username}" />
<c:set var="tabName" value="${pageScope.tab}" />
<jsp:useBean id="tabName" type="java.lang.String" />
<% // Get params
long ui = ParamUtils.getLongParameter(request,"userID",-1L);
String uname = ParamUtils.getParameter(request,"username");
// Load the user
User foundUser = ad.getUserManager().getUser(ui);
User foundUser = ad.getUserManager().getUser(uname);
// Get a presence manager
PresenceManager presenceManager = ad.getPresenceManager();
......@@ -35,14 +35,14 @@
<c:set var="tabCount" value="1" />
<td class="jive-<%= (("props".equals(tabName)) ? "selected-" : "") %>tab" width="1%" nowrap>
<a href="user-properties.jsp?userID=<c:out value="${userID}"/>">User Properties</a>
<a href="user-properties.jsp?username=<c:out value="${username}"/>">User Properties</a>
</td>
<td class="jive-tab-spacer" width="1%"><img src="images/blank.gif" width="5" height="1" border="0"></td>
<c:set var="tabCount" value="${tabCount + 1}" />
<td class="jive-<%= (("edit".equals(tabName)) ? "selected-" : "") %>tab" width="1%" nowrap>
<a href="user-edit-form.jsp?userID=<c:out value="${userID}"/>">Edit User</a>
<a href="user-edit-form.jsp?username=<c:out value="${username}"/>">Edit User</a>
</td>
<td class="jive-tab-spacer" width="1%"><img src="images/blank.gif" width="5" height="1" border="0"></td>
......@@ -53,7 +53,7 @@
%>
<td class="jive-<%= (("message".equals(tabName)) ? "selected-" : "") %>tab" width="1%" nowrap>
<a href="user-message.jsp?userID=<c:out value="${userID}"/>">Send Message</a>
<a href="user-message.jsp?username=<c:out value="${username}"/>">Send Message</a>
</td>
<td class="jive-tab-spacer" width="1%"><img src="images/blank.gif" width="5" height="1" border="0"></td>
......@@ -63,14 +63,14 @@
<% } %>
<td class="jive-<%= (("pass".equals(tabName)) ? "selected-" : "") %>tab" width="1%" nowrap>
<a href="user-password.jsp?userID=<c:out value="${userID}"/>">Change Password</a>
<a href="user-password.jsp?username=<c:out value="${username}"/>">Change Password</a>
</td>
<td class="jive-tab-spacer" width="1%"><img src="images/blank.gif" width="5" height="1" border="0"></td>
<c:set var="tabCount" value="${tabCount + 1}" />
<td class="jive-<%= (("delete".equals(tabName)) ? "selected-" : "") %>tab" width="1%" nowrap>
<a href="user-delete.jsp?userID=<c:out value="${userID}"/>">Delete User</a>
<a href="user-delete.jsp?username=<c:out value="${username}"/>">Delete User</a>
</td>
<td class="jive-tab-spacer" width="1%"><img src="images/blank.gif" width="5" height="1" border="0"></td>
<c:set var="width" value="${100-(tabCount*2)}" />
......
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