Cleanup XMPP PR

This commit is contained in:
Iaccidentally 2013-10-14 14:19:24 -04:00 committed by KHobbits
parent 27ee587887
commit f53240191f
3 changed files with 539 additions and 545 deletions

View file

@ -16,137 +16,137 @@ import org.bukkit.plugin.java.JavaPlugin;
public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP
{ {
private static final Logger LOGGER = Logger.getLogger("Minecraft"); private static final Logger LOGGER = Logger.getLogger("Minecraft");
private static EssentialsXMPP instance = null; private static EssentialsXMPP instance = null;
private transient UserManager users; private transient UserManager users;
private transient XMPPManager xmpp; private transient XMPPManager xmpp;
private transient IEssentials ess; private transient IEssentials ess;
public static IEssentialsXMPP getInstance() public static IEssentialsXMPP getInstance()
{ {
return instance; return instance;
} }
@Override @Override
public void onEnable() public void onEnable()
{ {
instance = this; instance = this;
final PluginManager pluginManager = getServer().getPluginManager(); final PluginManager pluginManager = getServer().getPluginManager();
ess = (IEssentials)pluginManager.getPlugin("Essentials"); ess = (IEssentials)pluginManager.getPlugin("Essentials");
if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion()))
{ {
LOGGER.log(Level.WARNING, _("versionMismatchAll")); LOGGER.log(Level.WARNING, _("versionMismatchAll"));
} }
if (!ess.isEnabled()) if (!ess.isEnabled())
{ {
this.setEnabled(false); this.setEnabled(false);
return; return;
} }
final EssentialsXMPPPlayerListener playerListener = new EssentialsXMPPPlayerListener(ess); final EssentialsXMPPPlayerListener playerListener = new EssentialsXMPPPlayerListener(ess);
pluginManager.registerEvents(playerListener, this); pluginManager.registerEvents(playerListener, this);
users = new UserManager(this.getDataFolder()); users = new UserManager(this.getDataFolder());
xmpp = new XMPPManager(this); xmpp = new XMPPManager(this);
ess.addReloadListener(users); ess.addReloadListener(users);
ess.addReloadListener(xmpp); ess.addReloadListener(xmpp);
} }
@Override @Override
public void onDisable() public void onDisable()
{ {
if (xmpp != null) if (xmpp != null)
{ {
xmpp.disconnect(); xmpp.disconnect();
} }
instance = null; instance = null;
} }
@Override @Override
public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args)
{ {
return ess.onCommandEssentials(sender, command, commandLabel, args, EssentialsXMPP.class.getClassLoader(), "com.earth2me.essentials.xmpp.Command", "essentials.", null); return ess.onCommandEssentials(sender, command, commandLabel, args, EssentialsXMPP.class.getClassLoader(), "com.earth2me.essentials.xmpp.Command", "essentials.", null);
} }
@Override @Override
public void setAddress(final Player user, final String address) public void setAddress(final Player user, final String address)
{ {
final String username = user.getName().toLowerCase(Locale.ENGLISH); final String username = user.getName().toLowerCase(Locale.ENGLISH);
instance.users.setAddress(username, address); instance.users.setAddress(username, address);
} }
@Override @Override
public String getAddress(final String name) public String getAddress(final String name)
{ {
return instance.users.getAddress(name); return instance.users.getAddress(name);
} }
@Override @Override
public IUser getUserByAddress(final String address) public IUser getUserByAddress(final String address)
{ {
String username = instance.users.getUserByAddress(address); String username = instance.users.getUserByAddress(address);
return username == null ? null : ess.getUser(username); return username == null ? null : ess.getUser(username);
} }
@Override @Override
public boolean toggleSpy(final Player user) public boolean toggleSpy(final Player user)
{ {
final String username = user.getName().toLowerCase(Locale.ENGLISH); final String username = user.getName().toLowerCase(Locale.ENGLISH);
final boolean spy = !instance.users.isSpy(username); final boolean spy = !instance.users.isSpy(username);
instance.users.setSpy(username, spy); instance.users.setSpy(username, spy);
return spy; return spy;
} }
@Override @Override
public String getAddress(final Player user) public String getAddress(final Player user)
{ {
return instance.users.getAddress(user.getName()); return instance.users.getAddress(user.getName());
} }
@Override @Override
public boolean sendMessage(final Player user, final String message) public boolean sendMessage(final Player user, final String message)
{ {
return instance.xmpp.sendMessage(instance.users.getAddress(user.getName()), message); return instance.xmpp.sendMessage(instance.users.getAddress(user.getName()), message);
} }
@Override @Override
public boolean sendMessage(final String address, final String message) public boolean sendMessage(final String address, final String message)
{ {
return instance.xmpp.sendMessage(address, message); return instance.xmpp.sendMessage(address, message);
} }
// @Override // @Override
public static boolean updatePresence() public static boolean updatePresence()
{ {
instance.xmpp.updatePresence(); instance.xmpp.updatePresence();
return true; return true;
} }
@Override @Override
public List<String> getSpyUsers() public List<String> getSpyUsers()
{ {
return instance.users.getSpyUsers(); return instance.users.getSpyUsers();
} }
@Override @Override
public void broadcastMessage(final IUser sender, final String message, final String xmppAddress) public void broadcastMessage(final IUser sender, final String message, final String xmppAddress)
{ {
ess.broadcastMessage(sender, message); ess.broadcastMessage(sender, message);
try try
{ {
for (String address : getSpyUsers()) for (String address : getSpyUsers())
{ {
if (!address.equalsIgnoreCase(xmppAddress)) if (!address.equalsIgnoreCase(xmppAddress))
{ {
sendMessage(address, message); sendMessage(address, message);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
// Ignore exceptions // Ignore exceptions
} }
} }
} }

View file

@ -3,9 +3,6 @@ package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.ess3.api.IUser;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -13,86 +10,84 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.Server;
class EssentialsXMPPPlayerListener implements Listener class EssentialsXMPPPlayerListener implements Listener
{ {
private final transient IEssentials ess; private final transient IEssentials ess;
EssentialsXMPPPlayerListener(final IEssentials ess) EssentialsXMPPPlayerListener(final IEssentials ess)
{ {
super(); super();
this.ess = ess; this.ess = ess;
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(final PlayerJoinEvent event) public void onPlayerJoin(final PlayerJoinEvent event)
{ {
final User user = ess.getUser(event.getPlayer()); final User user = ess.getUser(event.getPlayer());
Bukkit.getScheduler().scheduleSyncDelayedTask(ess, new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(ess, new Runnable()
{ {
@Override @Override
public void run() public void run()
{ {
EssentialsXMPP.updatePresence(); EssentialsXMPP.updatePresence();
} }
}); });
sendMessageToSpyUsers("Player " + user.getDisplayName() + " joined the game"); sendMessageToSpyUsers("Player " + user.getDisplayName() + " joined the game");
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChat(final AsyncPlayerChatEvent event) public void onPlayerChat(final AsyncPlayerChatEvent event)
{ {
final User user = ess.getUser(event.getPlayer()); final User user = ess.getUser(event.getPlayer());
sendMessageToSpyUsers(String.format(event.getFormat(), user.getDisplayName(), event.getMessage())); sendMessageToSpyUsers(String.format(event.getFormat(), user.getDisplayName(), event.getMessage()));
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(final PlayerQuitEvent event) public void onPlayerQuit(final PlayerQuitEvent event)
{ {
final User user = ess.getUser(event.getPlayer()); final User user = ess.getUser(event.getPlayer());
Bukkit.getScheduler().scheduleSyncDelayedTask(ess, new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(ess, new Runnable()
{ {
@Override @Override
public void run() public void run()
{ {
EssentialsXMPP.updatePresence(); EssentialsXMPP.updatePresence();
} }
}); });
sendMessageToSpyUsers("Player " + user.getDisplayName() + " left the game"); sendMessageToSpyUsers("Player " + user.getDisplayName() + " left the game");
} }
private void sendMessageToSpyUsers(final String message) private void sendMessageToSpyUsers(final String message)
{ {
try try
{ {
List<String> users = EssentialsXMPP.getInstance().getSpyUsers(); List<String> users = EssentialsXMPP.getInstance().getSpyUsers();
synchronized (users) synchronized (users)
{ {
for (final String address : users) for (final String address : users)
{ {
Bukkit.getScheduler().scheduleSyncDelayedTask(ess, new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(ess, new Runnable()
{ {
@Override @Override
public void run() public void run()
{ {
EssentialsXMPP.getInstance().sendMessage(address, message); EssentialsXMPP.getInstance().sendMessage(address, message);
} }
});
}); }
}
} }
} catch (Exception ex)
} {
catch (Exception ex) // Ignore exceptions
{ }
// Ignore exceptions }
}
}
} }

View file

@ -1,6 +1,5 @@
package com.earth2me.essentials.xmpp; package com.earth2me.essentials.xmpp;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.EssentialsConf; import com.earth2me.essentials.EssentialsConf;
import com.earth2me.essentials.IConf; import com.earth2me.essentials.IConf;
@ -13,396 +12,396 @@ import java.util.logging.Level;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.logging.SimpleFormatter; import java.util.logging.SimpleFormatter;
import org.bukkit.Server;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jivesoftware.smack.*; import org.jivesoftware.smack.*;
import org.jivesoftware.smack.Roster.SubscriptionMode; import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IConf public class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IConf
{ {
private static final Logger LOGGER = Logger.getLogger("Minecraft"); private static final Logger LOGGER = Logger.getLogger("Minecraft");
private static final SimpleFormatter formatter = new SimpleFormatter(); private static final SimpleFormatter formatter = new SimpleFormatter();
private final transient EssentialsConf config; private final transient EssentialsConf config;
private transient XMPPConnection connection; private transient XMPPConnection connection;
private transient ChatManager chatManager; private transient ChatManager chatManager;
private final transient Map<String, Chat> chats = Collections.synchronizedMap(new HashMap<String, Chat>()); private final transient Map<String, Chat> chats = Collections.synchronizedMap(new HashMap<String, Chat>());
private final transient Set<LogRecord> logrecords = Collections.synchronizedSet(new HashSet<LogRecord>()); private final transient Set<LogRecord> logrecords = Collections.synchronizedSet(new HashSet<LogRecord>());
private final transient IEssentialsXMPP parent; private final transient IEssentialsXMPP parent;
private transient List<String> logUsers; private transient List<String> logUsers;
private transient Level logLevel; private transient Level logLevel;
private transient boolean ignoreLagMessages = true; private transient boolean ignoreLagMessages = true;
private transient Thread loggerThread; private transient Thread loggerThread;
private transient boolean threadrunning = true; private transient boolean threadrunning = true;
public XMPPManager(final IEssentialsXMPP parent) public XMPPManager(final IEssentialsXMPP parent)
{ {
super(); super();
this.parent = parent; this.parent = parent;
config = new EssentialsConf(new File(parent.getDataFolder(), "config.yml")); config = new EssentialsConf(new File(parent.getDataFolder(), "config.yml"));
config.setTemplateName("/config.yml", EssentialsXMPP.class); config.setTemplateName("/config.yml", EssentialsXMPP.class);
reloadConfig(); reloadConfig();
} }
public boolean sendMessage(final String address, final String message) public boolean sendMessage(final String address, final String message)
{ {
if (address != null && !address.isEmpty()) if (address != null && !address.isEmpty())
{ {
try try
{ {
startChat(address); startChat(address);
final Chat chat; final Chat chat;
synchronized (chats) synchronized (chats)
{ {
chat = chats.get(address); chat = chats.get(address);
} }
if (chat != null) if (chat != null)
{ {
if (!connection.isConnected()) if (!connection.isConnected())
{ {
disconnect(); disconnect();
connect(); connect();
} }
chat.sendMessage(FormatUtil.stripFormat(message)); chat.sendMessage(FormatUtil.stripFormat(message));
return true; return true;
} }
} }
catch (XMPPException ex) catch (XMPPException ex)
{ {
disableChat(address); disableChat(address);
} }
} }
return false; return false;
} }
@Override @Override
public void processMessage(final Chat chat, final Message msg) public void processMessage(final Chat chat, final Message msg)
{ {
// Normally we should log the error message // Normally we should log the error message
// But we would create a loop if the connection to a log-user fails. // But we would create a loop if the connection to a log-user fails.
if (msg.getType() != Message.Type.error && msg.getBody().length() > 0) if (msg.getType() != Message.Type.error && msg.getBody().length() > 0)
{ {
final String message = msg.getBody(); final String message = msg.getBody();
switch (message.charAt(0)) switch (message.charAt(0))
{ {
case '@': case '@':
sendPrivateMessage(chat, message); sendPrivateMessage(chat, message);
break; break;
case '/': case '/':
sendCommand(chat, message); sendCommand(chat, message);
break; break;
default: default:
final IUser sender = parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())); final IUser sender = parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant()));
parent.broadcastMessage(sender, "=" + sender.getBase().getDisplayName() + ": " + message, StringUtils.parseBareAddress(chat.getParticipant())); parent.broadcastMessage(sender, "=" + sender.getBase().getDisplayName() + ": " + message, StringUtils.parseBareAddress(chat.getParticipant()));
} }
} }
} }
private boolean connect() private boolean connect()
{ {
final String server = config.getString("xmpp.server"); final String server = config.getString("xmpp.server");
if (server == null || server.equals("example.com")) if (server == null || server.equals("example.com"))
{ {
LOGGER.log(Level.WARNING, "config broken for xmpp"); LOGGER.log(Level.WARNING, "config broken for xmpp");
return false; return false;
} }
final int port = config.getInt("xmpp.port", 5222); final int port = config.getInt("xmpp.port", 5222);
final String serviceName = config.getString("xmpp.servicename", server); final String serviceName = config.getString("xmpp.servicename", server);
final String xmppuser = config.getString("xmpp.user"); final String xmppuser = config.getString("xmpp.user");
final String password = config.getString("xmpp.password"); final String password = config.getString("xmpp.password");
final ConnectionConfiguration connConf = new ConnectionConfiguration(server, port, serviceName); final ConnectionConfiguration connConf = new ConnectionConfiguration(server, port, serviceName);
final StringBuilder stringBuilder = new StringBuilder(); final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Connecting to xmpp server ").append(server).append(":").append(port); stringBuilder.append("Connecting to xmpp server ").append(server).append(":").append(port);
stringBuilder.append(" as user ").append(xmppuser).append("."); stringBuilder.append(" as user ").append(xmppuser).append(".");
LOGGER.log(Level.INFO, stringBuilder.toString()); LOGGER.log(Level.INFO, stringBuilder.toString());
connConf.setSASLAuthenticationEnabled(config.getBoolean("xmpp.sasl-enabled", false)); connConf.setSASLAuthenticationEnabled(config.getBoolean("xmpp.sasl-enabled", false));
connConf.setSendPresence(true); connConf.setSendPresence(true);
connConf.setReconnectionAllowed(true); connConf.setReconnectionAllowed(true);
connConf.setDebuggerEnabled(config.getBoolean("debug", false)); connConf.setDebuggerEnabled(config.getBoolean("debug", false));
connection = new XMPPConnection(connConf); connection = new XMPPConnection(connConf);
try try
{ {
connection.connect(); connection.connect();
connection.login(xmppuser, password, "Essentials-XMPP"); connection.login(xmppuser, password, "Essentials-XMPP");
connection.sendPacket(new Presence(Presence.Type.available, "No one online.", 2, Presence.Mode.available)); connection.sendPacket(new Presence(Presence.Type.available, "No one online.", 2, Presence.Mode.available));
connection.getRoster().setSubscriptionMode(SubscriptionMode.accept_all); connection.getRoster().setSubscriptionMode(SubscriptionMode.accept_all);
chatManager = connection.getChatManager(); chatManager = connection.getChatManager();
chatManager.addChatListener(this); chatManager.addChatListener(this);
return true; return true;
} }
catch (XMPPException ex) catch (XMPPException ex)
{ {
LOGGER.log(Level.WARNING, "Failed to connect to server: " + server, ex); LOGGER.log(Level.WARNING, "Failed to connect to server: " + server, ex);
return false; return false;
} }
} }
public final void disconnect() public final void disconnect()
{ {
if (loggerThread != null) if (loggerThread != null)
{ {
loggerThread.interrupt(); loggerThread.interrupt();
} }
if (chatManager != null) if (chatManager != null)
{ {
chatManager.removeChatListener(this); chatManager.removeChatListener(this);
chatManager = null; chatManager = null;
} }
if (connection != null) if (connection != null)
{ {
connection.disconnect(new Presence(Presence.Type.unavailable)); connection.disconnect(new Presence(Presence.Type.unavailable));
} }
} }
public final void updatePresence() public final void updatePresence()
{ {
final int usercount; final int usercount;
final StringBuilder stringBuilder = new StringBuilder(); final StringBuilder stringBuilder = new StringBuilder();
usercount = parent.getServer().getOnlinePlayers().length; usercount = parent.getServer().getOnlinePlayers().length;
if (usercount == 0) { if (usercount == 0)
final String presenceMsg = "No one online."; {
connection.sendPacket(new Presence(Presence.Type.available, presenceMsg, 2, Presence.Mode.available)); final String presenceMsg = "No one online.";
} connection.sendPacket(new Presence(Presence.Type.available, presenceMsg, 2, Presence.Mode.dnd));
if (usercount == 1) { }
final String presenceMsg = "1 player online."; if (usercount == 1)
connection.sendPacket(new Presence(Presence.Type.available, presenceMsg, 2, Presence.Mode.dnd)); {
} final String presenceMsg = "1 player online.";
if (usercount > 1) { connection.sendPacket(new Presence(Presence.Type.available, presenceMsg, 2, Presence.Mode.available));
stringBuilder.append(usercount).append(" players online."); }
connection.sendPacket(new Presence(Presence.Type.available, stringBuilder.toString(), 2, Presence.Mode.dnd)); if (usercount > 1)
} {
} stringBuilder.append(usercount).append(" players online.");
connection.sendPacket(new Presence(Presence.Type.available, stringBuilder.toString(), 2, Presence.Mode.available));
}
}
@Override @Override
public void chatCreated(final Chat chat, final boolean createdLocally) public void chatCreated(final Chat chat, final boolean createdLocally)
{ {
if (!createdLocally) if (!createdLocally)
{ {
chat.addMessageListener(this); chat.addMessageListener(this);
final Chat old = chats.put(StringUtils.parseBareAddress(chat.getParticipant()), chat); final Chat old = chats.put(StringUtils.parseBareAddress(chat.getParticipant()), chat);
if (old != null) if (old != null)
{ {
old.removeMessageListener(this); old.removeMessageListener(this);
} }
} }
} }
@Override @Override
public final void reloadConfig() public final void reloadConfig()
{ {
LOGGER.removeHandler(this); LOGGER.removeHandler(this);
config.load(); config.load();
synchronized (chats) synchronized (chats)
{ {
disconnect(); disconnect();
chats.clear(); chats.clear();
if (!connect()) if (!connect())
{ {
return; return;
} }
startLoggerThread(); startLoggerThread();
} }
if (config.getBoolean("log-enabled", false)) if (config.getBoolean("log-enabled", false))
{ {
LOGGER.addHandler(this); LOGGER.addHandler(this);
logUsers = config.getStringList("log-users"); logUsers = config.getStringList("log-users");
final String level = config.getString("log-level", "info"); final String level = config.getString("log-level", "info");
try try
{ {
logLevel = Level.parse(level.toUpperCase(Locale.ENGLISH)); logLevel = Level.parse(level.toUpperCase(Locale.ENGLISH));
} }
catch (IllegalArgumentException e) catch (IllegalArgumentException e)
{ {
logLevel = Level.INFO; logLevel = Level.INFO;
} }
ignoreLagMessages = config.getBoolean("ignore-lag-messages", true); ignoreLagMessages = config.getBoolean("ignore-lag-messages", true);
} }
} }
@Override @Override
public void publish(final LogRecord logRecord) public void publish(final LogRecord logRecord)
{ {
try try
{ {
if (ignoreLagMessages && logRecord.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?")) if (ignoreLagMessages && logRecord.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?"))
{ {
return; return;
} }
if (logRecord.getLevel().intValue() >= logLevel.intValue()) if (logRecord.getLevel().intValue() >= logLevel.intValue())
{ {
synchronized (logrecords) synchronized (logrecords)
{ {
logrecords.add(logRecord); logrecords.add(logRecord);
} }
} }
} }
catch (Exception e) catch (Exception e)
{ {
// Ignore all exceptions // Ignore all exceptions
// Otherwise we create a loop. // Otherwise we create a loop.
} }
} }
@Override @Override
public void flush() public void flush()
{ {
// Ignore this // Ignore this
} }
@Override @Override
public void close() throws SecurityException public void close() throws SecurityException
{ {
// Ignore this // Ignore this
} }
private void startLoggerThread() private void startLoggerThread()
{ {
loggerThread = new Thread(new Runnable() loggerThread = new Thread(new Runnable()
{ {
@Override @Override
public void run() public void run()
{ {
final Set<LogRecord> copy = new HashSet<LogRecord>(); final Set<LogRecord> copy = new HashSet<LogRecord>();
final Set<String> failedUsers = new HashSet<String>(); final Set<String> failedUsers = new HashSet<String>();
while (threadrunning) while (threadrunning)
{ {
synchronized (logrecords) synchronized (logrecords)
{ {
if (!logrecords.isEmpty()) if (!logrecords.isEmpty())
{ {
copy.addAll(logrecords); copy.addAll(logrecords);
logrecords.clear(); logrecords.clear();
} }
} }
if (!copy.isEmpty()) if (!copy.isEmpty())
{ {
for (String user : logUsers) for (String user : logUsers)
{ {
try try
{ {
XMPPManager.this.startChat(user); XMPPManager.this.startChat(user);
for (LogRecord logRecord : copy) for (LogRecord logRecord : copy)
{ {
final String message = formatter.format(logRecord); final String message = formatter.format(logRecord);
if (!XMPPManager.this.sendMessage(user, FormatUtil.stripLogColorFormat(message))) if (!XMPPManager.this.sendMessage(user, FormatUtil.stripLogColorFormat(message)))
{ {
failedUsers.add(user); failedUsers.add(user);
break; break;
} }
} }
} }
catch (XMPPException ex) catch (XMPPException ex)
{ {
failedUsers.add(user); failedUsers.add(user);
LOGGER.removeHandler(XMPPManager.this); LOGGER.removeHandler(XMPPManager.this);
LOGGER.log(Level.SEVERE, "Failed to deliver log message! Disabling logging to XMPP.", ex); LOGGER.log(Level.SEVERE, "Failed to deliver log message! Disabling logging to XMPP.", ex);
} }
} }
logUsers.removeAll(failedUsers); logUsers.removeAll(failedUsers);
if (logUsers.isEmpty()) if (logUsers.isEmpty())
{ {
LOGGER.removeHandler(XMPPManager.this); LOGGER.removeHandler(XMPPManager.this);
threadrunning = false; threadrunning = false;
} }
copy.clear(); copy.clear();
} }
try try
{ {
Thread.sleep(2000); Thread.sleep(2000);
} }
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
threadrunning = false; threadrunning = false;
} }
} }
LOGGER.removeHandler(XMPPManager.this); LOGGER.removeHandler(XMPPManager.this);
} }
}); });
loggerThread.start(); loggerThread.start();
} }
private void startChat(final String address) throws XMPPException private void startChat(final String address) throws XMPPException
{ {
if (chatManager == null) if (chatManager == null)
{ {
return; return;
} }
synchronized (chats) synchronized (chats)
{ {
if (!chats.containsKey(address)) if (!chats.containsKey(address))
{ {
final Chat chat = chatManager.createChat(address, this); final Chat chat = chatManager.createChat(address, this);
if (chat == null) if (chat == null)
{ {
throw new XMPPException("Could not start Chat with " + address); throw new XMPPException("Could not start Chat with " + address);
} }
chats.put(address, chat); chats.put(address, chat);
} }
} }
} }
private void sendPrivateMessage(final Chat chat, final String message) private void sendPrivateMessage(final Chat chat, final String message)
{ {
final String[] parts = message.split(" ", 2); final String[] parts = message.split(" ", 2);
if (parts.length == 2) if (parts.length == 2)
{ {
final List<Player> matches = parent.getServer().matchPlayer(parts[0].substring(1)); final List<Player> matches = parent.getServer().matchPlayer(parts[0].substring(1));
if (matches.isEmpty()) if (matches.isEmpty())
{ {
try try
{ {
chat.sendMessage("User " + parts[0] + " not found"); chat.sendMessage("User " + parts[0] + " not found");
} }
catch (XMPPException ex) catch (XMPPException ex)
{ {
LOGGER.log(Level.WARNING, "Failed to send xmpp message.", ex); LOGGER.log(Level.WARNING, "Failed to send xmpp message.", ex);
} }
} }
else else
{ {
final String from = "[" + parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())) + ">"; final String from = "[" + parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())) + ">";
for (Player p : matches) for (Player p : matches)
{ {
p.sendMessage(from + p.getDisplayName() + "] " + message); p.sendMessage(from + p.getDisplayName() + "] " + message);
} }
} }
} }
} }
private void sendCommand(final Chat chat, final String message) private void sendCommand(final Chat chat, final String message)
{ {
if (config.getStringList("op-users").contains(StringUtils.parseBareAddress(chat.getParticipant()))) if (config.getStringList("op-users").contains(StringUtils.parseBareAddress(chat.getParticipant())))
{ {
try try
{ {
parent.getServer().dispatchCommand(Console.getCommandSender(parent.getServer()), message.substring(1)); parent.getServer().dispatchCommand(Console.getCommandSender(parent.getServer()), message.substring(1));
} }
catch (Exception ex) catch (Exception ex)
{ {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex); LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
} }
} }
} }
private void disableChat(final String address) private void disableChat(final String address)
{ {
final Chat chat = chats.get(address); final Chat chat = chats.get(address);
if (chat != null) if (chat != null)
{ {
chat.removeMessageListener(this); chat.removeMessageListener(this);
chats.remove(address); chats.remove(address);
} }
} }
} }