📄 multiuserchatserverimpl.java
字号:
public void setRoomCreationRestricted(boolean roomCreationRestricted) {
this.roomCreationRestricted = roomCreationRestricted;
JiveGlobals.setProperty("xmpp.muc.create.anyone", Boolean.toString(roomCreationRestricted));
}
public void addUserAllowedToCreate(String userJID) {
// Update the list of allowed JIDs to create MUC rooms. Since we are updating the instance
// variable there is no need to restart the service
allowedToCreate.add(userJID.trim().toLowerCase());
// CopyOnWriteArray does not allow sorting, so do sorting in temp list.
ArrayList<String> tempList = new ArrayList<String>(allowedToCreate);
Collections.sort(tempList);
allowedToCreate = new CopyOnWriteArrayList<String>(tempList);
// Update the config.
String[] jids = new String[allowedToCreate.size()];
jids = allowedToCreate.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.create.jid", fromArray(jids));
}
public void removeUserAllowedToCreate(String userJID) {
// Update the list of allowed JIDs to create MUC rooms. Since we are updating the instance
// variable there is no need to restart the service
allowedToCreate.remove(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[allowedToCreate.size()];
jids = allowedToCreate.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.create.jid", fromArray(jids));
}
public void initialize(XMPPServer server) {
super.initialize(server);
serviceEnabled = JiveGlobals.getBooleanProperty("xmpp.muc.enabled", true);
chatServiceName = JiveGlobals.getProperty("xmpp.muc.service");
// Trigger the strategy to load itself from the context
historyStrategy.setContext("xmpp.muc.history");
// Load the list of JIDs that are sysadmins of the MUC service
String property = JiveGlobals.getProperty("xmpp.muc.sysadmin.jid");
String[] jids;
if (property != null) {
jids = property.split(",");
for (String jid : jids) {
sysadmins.add(jid.trim().toLowerCase());
}
}
allowToDiscoverLockedRooms =
Boolean.parseBoolean(JiveGlobals.getProperty("xmpp.muc.discover.locked", "true"));
roomCreationRestricted =
Boolean.parseBoolean(JiveGlobals.getProperty("xmpp.muc.create.anyone", "false"));
// Load the list of JIDs that are allowed to create a MUC room
property = JiveGlobals.getProperty("xmpp.muc.create.jid");
if (property != null) {
jids = property.split(",");
for (String jid : jids) {
allowedToCreate.add(jid.trim().toLowerCase());
}
}
String value = JiveGlobals.getProperty("xmpp.muc.tasks.user.timeout");
if (value != null) {
try {
user_timeout = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.user.timeout", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.user.idle");
if (value != null) {
try {
user_idle = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.user.idle", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.log.timeout");
if (value != null) {
try {
log_timeout = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.log.timeout", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.log.batchsize");
if (value != null) {
try {
log_batch_size = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.log.batchsize", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.unload.empty_days");
if (value != null) {
try {
emptyLimit = Integer.parseInt(value) * 24;
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.unload.empty_days", e);
}
}
if (chatServiceName == null) {
chatServiceName = "conference";
}
// Run through the users every 5 minutes after a 5 minutes server startup delay (default
// values)
userTimeoutTask = new UserTimeoutTask();
timer.schedule(userTimeoutTask, user_timeout, user_timeout);
// Log the room conversations every 5 minutes after a 5 minutes server startup delay
// (default values)
logConversationTask = new LogConversationTask();
timer.schedule(logConversationTask, log_timeout, log_timeout);
// Remove unused rooms from memory
cleanupTask = new CleanupTask();
timer.schedule(cleanupTask, CLEANUP_FREQUENCY, CLEANUP_FREQUENCY);
routingTable = server.getRoutingTable();
router = server.getPacketRouter();
// Configure the handler of iq:register packets
registerHandler = new IQMUCRegisterHandler(this);
// Configure the handler of jabber:iq:search packets
searchHandler = new IQMUCSearchHandler(this);
// Listen to cluster events
ClusterManager.addListener(this);
}
public void start() {
super.start();
// Add the route to this service
routingTable.addComponentRoute(getAddress(), this);
ArrayList<String> params = new ArrayList<String>();
params.clear();
params.add(getServiceDomain());
Log.info(LocaleUtils.getLocalizedString("startup.starting.muc", params));
// Load all the persistent rooms to memory
for (LocalMUCRoom room : MUCPersistenceManager.loadRoomsFromDB(this, this.getCleanupDate(), router)) {
rooms.put(room.getName().toLowerCase(), room);
}
// Add statistics
addTotalRoomStats();
addTotalOccupantsStats();
addTotalConnectedUsers();
addNumberIncomingMessages();
addNumberOutgoingMessages();
}
public void stop() {
super.stop();
// Remove the route to this service
routingTable.removeComponentRoute(getAddress());
timer.cancel();
logAllConversation();
// Remove the statistics.
StatisticsManager.getInstance().removeStatistic(roomsStatKey);
StatisticsManager.getInstance().removeStatistic(occupantsStatKey);
StatisticsManager.getInstance().removeStatistic(usersStatKey);
StatisticsManager.getInstance().removeStatistic(incomingStatKey);
StatisticsManager.getInstance().removeStatistic(outgoingStatKey);
}
public void enableService(boolean enabled, boolean persistent) {
if (isServiceEnabled() == enabled) {
// Do nothing if the service status has not changed
return;
}
XMPPServer server = XMPPServer.getInstance();
if (!enabled) {
// Disable disco information
server.getIQDiscoItemsHandler().removeServerItemsProvider(this);
// Stop the service/module
stop();
}
if (persistent) {
JiveGlobals.setProperty("xmpp.muc.enabled", Boolean.toString(enabled));
}
serviceEnabled = enabled;
if (enabled) {
// Start the service/module
start();
// Enable disco information
server.getIQDiscoItemsHandler().addServerItemsProvider(this);
}
}
public boolean isServiceEnabled() {
return serviceEnabled;
}
public long getTotalChatTime() {
return totalChatTime;
}
/**
* Retuns the number of existing rooms in the server (i.e. persistent or not,
* in memory or not).
*
* @return the number of existing rooms in the server.
*/
public int getNumberChatRooms() {
return rooms.size();
}
/**
* Retuns the total number of occupants in all rooms in the server.
*
* @param onlyLocal true if only users connected to this JVM will be considered. Otherwise count cluster wise.
* @return the number of existing rooms in the server.
*/
public int getNumberConnectedUsers(boolean onlyLocal) {
int total = 0;
for (LocalMUCUser user : users.values()) {
if (user.isJoined()) {
total = total + 1;
}
}
// Add users from remote cluster nodes
if (!onlyLocal) {
Collection<Object> results =
CacheFactory.doSynchronousClusterTask(new GetNumberConnectedUsers(), false);
for (Object result : results) {
if (result == null) {
continue;
}
total = total + (Integer) result;
}
}
return total;
}
/**
* Retuns the total number of users that have joined in all rooms in the server.
*
* @return the number of existing rooms in the server.
*/
public int getNumberRoomOccupants() {
int total = 0;
for (MUCRoom room : rooms.values()) {
total = total + room.getOccupantsCount();
}
return total;
}
public void logConversation(MUCRoom room, Message message, JID sender) {
// Only log messages that have a subject or body. Otherwise ignore it.
if (message.getSubject() != null || message.getBody() != null) {
logQueue.add(new ConversationLogEntry(new Date(), room, message, sender));
}
}
public void messageBroadcastedTo(int numOccupants) {
// Increment counter of received messages that where broadcasted by one
inMessages.incrementAndGet();
// Increment counter of outgoing messages with the number of room occupants
// that received the message
outMessages.addAndGet(numOccupants);
}
public void joinedCluster() {
if (isServiceEnabled()) {
if (!ClusterManager.isSeniorClusterMember()) {
// Get transient rooms and persistent rooms with occupants from senior
// cluster member and merge with local ones. If room configuration was
// changed in both places then latest configuration will be kept
List<RoomInfo> result = (List<RoomInfo>) CacheFactory.doSynchronousClusterTask(
new SeniorMemberRoomsRequest(), ClusterManager.getSeniorClusterMember().toByteArray());
if (result != null) {
for (RoomInfo roomInfo : result) {
LocalMUCRoom remoteRoom = roomInfo.getRoom();
LocalMUCRoom localRoom = rooms.get(remoteRoom.getName());
if (localRoom == null) {
// Create local room with remote information
localRoom = remoteRoom;
rooms.put(remoteRoom.getName(), localRoom);
}
else {
// Update local room with remote information
localRoom.updateConfiguration(remoteRoom);
}
// Add remote occupants to local room
// TODO Handle conflict of nicknames
for (OccupantAddedEvent event : roomInfo.getOccupants()) {
event.setSendPresence(true);
event.run();
}
}
}
}
}
}
public void joinedCluster(byte[] nodeID) {
if (isServiceEnabled()) {
List<RoomInfo> result =
(List<RoomInfo>) CacheFactory.doSynchronousClusterTask(new GetNewMemberRoomsRequest(), nodeID);
if (result != null) {
for (RoomInfo roomInfo : result) {
LocalMUCRoom remoteRoom = roomInfo.getRoom();
LocalMUCRoom localRoom = rooms.get(remoteRoom.getName());
if (localRoom == null) {
// Create local room with remote information
localRoom = remoteRoom;
rooms.put(remoteRoom.getName(), localRoom);
}
// Add remote occupants to local room
for (OccupantAddedEvent event : roomInfo.getOccupants()) {
event.setSendPresence(true);
event.run();
}
}
}
}
}
public void leftCluster() {
// Do nothing. An unavailable presence will be created for occupants hosted in other cluster nodes.
}
public void leftCluster(byte[] nodeID) {
// Do nothing. An unavailable presence will be created for occupants hosted in the leaving cluster node.
}
public void markedAsSeniorClusterMember() {
// Do nothing
}
public Iterator<DiscoServerItem> getItems() {
// Check if the service is disabled. Info is not available when
// disabled.
if (!isServiceEnabled())
{
return null;
}
final ArrayList<DiscoServerItem> items = new ArrayList<DiscoServerItem>();
final String name;
// Check if there is a system property that overrides the default value
String serviceName = JiveGlobals.getProperty("muc.service-name");
if (serviceName != null && serviceName.trim().length() > 0)
{
name = serviceName;
}
else
{
// Return the default service name based on the current locale
name = LocaleUtils.getLocalizedString("muc.service-name");
}
final DiscoServerItem item = new DiscoServerItem(new JID(
getServiceDomain()), name, null, null, this, this);
items.add(item);
return items.iterator();
}
public Iterator<Element> getIdentities(String name, String node, JID senderJID) {
ArrayList<Element> identities = new ArrayList<Element>();
if (name == null && node == null) {
// Answer the identity of the MUC service
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", "Public Chatrooms");
identity.addAttribute("type", "text");
identities.add(identity);
Element searchId = DocumentHelper.createElement("identity");
searchId.addAttribute("category", "directory");
searchId.addAttribute("name", "Public Chatroom Search");
searchId.addAttribute("type", "chatroom");
identities.add(searchId);
}
else if (name != null && node == null) {
// Answer the identity of a given room
MUCRoom room = getChatRoom(name);
if (room != null && canDiscoverRoom(room)) {
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", room.getNaturalLanguageName());
identity.addAttribute("type", "text");
identities.add(identity);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -