PircBotServer.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.xnap.plugin.pircbot |
![]() |
![]() |
XNap 3 |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* XNap - A P2P framework and client.
*
* See the file AUTHORS for copyright information.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.xnap.plugin.pircbot;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import javax.swing.Action;
import org.apache.log4j.Logger;
import org.jibble.pircbot.DccFileTransfer;
import org.jibble.pircbot.NickAlreadyInUseException;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
import org.xnap.XNap;
import org.xnap.chat.AbstractChatProvider;
import org.xnap.chat.ChannelInfo;
import org.xnap.chat.ChatManager;
import org.xnap.chat.DefaultChannelInfo;
import org.xnap.cmdl.Command;
import org.xnap.cmdl.Console;
import org.xnap.cmdl.Executer;
import org.xnap.cmdl.LocalExecuter;
import org.xnap.event.StateListener;
import org.xnap.event.StateSupport;
import org.xnap.gui.action.AbstractListChannelsAction;
import org.xnap.gui.action.JoinChannelAction;
import org.xnap.net.NetHelper;
import org.xnap.transfer.DccDownload;
import org.xnap.transfer.DownloadManager;
import org.xnap.util.FiniteStateMachine;
import org.xnap.util.IllegalOperationException;
import org.xnap.util.Preferences;
import org.xnap.util.State;
import org.xnap.util.StringHelper;
public class PircBotServer extends AbstractChatProvider {
//--- Constant(s) ---
private static final Hashtable TRANSITION_TABLE;
static {
State[][] table = new State[][] {
{ State.DISCONNECTED,
State.CONNECTING, },
{ State.CONNECTING,
State.CONNECTED, State.DISCONNECTED, },
{ State.CONNECTED,
State.DISCONNECTED, },
};
TRANSITION_TABLE = FiniteStateMachine.createStateTable(table);
}
//--- Data field(s) ---
private static transient Logger logger
= Logger.getLogger(PircBotServer.class);
private transient PropertyChangeSupport pcs
= new PropertyChangeSupport(this);
private PircBotServerData data;
private Server server;
private StateMachine sm = new StateMachine();
private StateSupport listeners = new StateSupport(this);
//--- Constructor(s) ---
public PircBotServer(PircBotServerData data)
{
this.data = data;
}
public PircBotServer()
{
this(new PircBotServerData());
}
//--- Method(s) ---
public void addPropertyChangeListener(PropertyChangeListener l)
{
pcs.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l)
{
pcs.removePropertyChangeListener(l);
}
public void addStateListener(StateListener listener)
{
listeners.addStateListener(listener);
}
public void removeStateListener(StateListener listener)
{
listeners.removeStateListener(listener);
}
/**
* Disconnects the server and removes all channels.
*/
public void close()
{
if (server != null) {
server.removeAllChannels();
server.disconnect();
}
}
public void connect()
{
try {
setState(State.CONNECTING);
}
catch (IllegalOperationException e) {
logger.debug("unexpected state", e);
}
}
public Action[] getActions()
{
return new Action[] { new JoinChannelAction(this),
new ListChannelsAction() };
}
public ChannelInfo[] getChannels()
{
return getBot().getChannelInfos();
}
public boolean getAutoConnect()
{
return data.autoConnect;
}
public String getAutoJoinChannels()
{
return data.autoJoinChannels;
}
public String getConnectCommand()
{
return data.connectCommand;
}
public String getHost()
{
return data.host;
}
public String getLogin()
{
return data.login;
}
public String getName()
{
return data.name;
}
public String getNetwork()
{
return data.network;
}
public String getNick()
{
return data.nick;
}
/**
* Returns the local peer.
*/
public PircBotPeer getLocalPeer()
{
return getBot().getPeerByName(getBot().getNick());
}
public String getPassword()
{
return data.password;
}
public int getPort()
{
return data.port;
}
public String getStatus()
{
return sm.getDescription();
}
public boolean isConnected()
{
return sm.getState() == State.CONNECTED;
}
public boolean isDisconnected()
{
return sm.getState() == State.DISCONNECTED;
}
public void join(String name)
{
PircBotChannel c = getBot().getChannelByName(name);
getBot().joinChannel(name);
c.setJoined(true, null);
}
public void setAutoConnect(boolean autoConnect)
{
boolean oldValue = getAutoConnect();
data.autoConnect = autoConnect;
pcs.firePropertyChange("autoConnect", oldValue, autoConnect);
}
public void setAutoJoinChannels(String autoJoinChannels)
{
String oldValue = getAutoJoinChannels();
data.autoJoinChannels = autoJoinChannels;
pcs.firePropertyChange("autoJoinChannels", oldValue,
autoJoinChannels);
}
/**
* @param string
*/
public void setConnectCommand(String connectCommand)
{
String oldValue = getConnectCommand();
data.connectCommand = connectCommand;
pcs.firePropertyChange("connectCommand", oldValue,
connectCommand);
}
public void setHost(String host)
{
String oldValue = getHost();
data.host = host;
pcs.firePropertyChange("host", oldValue, host);
}
public void setLogin(String login)
{
String oldValue = getLogin();
data.login = login;
pcs.firePropertyChange("login", oldValue, login);
}
public void setName(String name)
{
String oldValue = getName();
data.name = name;
pcs.firePropertyChange("name", oldValue, name);
}
public void setNetwork(String network)
{
String oldValue = getNetwork();
data.network = network;
pcs.firePropertyChange("network", oldValue, network);
}
public void setNick(String nick)
{
String oldValue = getNick();
data.nick = nick;
pcs.firePropertyChange("nick", oldValue, nick);
}
public void setPassword(String password)
{
String oldValue = getPassword();
data.password = password;
pcs.firePropertyChange("password", oldValue, password);
}
public void setPort(int port)
{
int oldValue = getPort();
data.port = port;
pcs.firePropertyChange("port", new Integer(oldValue),
new Integer(port));
}
/**
* Used by classes in this package to access the PircBot instance
* directly.
*/
Server getBot()
{
// lazy instanziation
if (server == null) {
server = new Server();
}
return server;
}
/**
* Used by {@link PircBotPanel} for serialization.
*/
PircBotServerData getData()
{
return data;
}
private void setState(State newState)
{
sm.setState(newState);
listeners.fireStateChanged();
}
private void setState(State newState, String message)
{
sm.setState(newState, message);
listeners.fireStateChanged();
}
//--- Inner Class(es) ---
private class StateMachine extends FiniteStateMachine
{
//--- Constructor(s) ---
public StateMachine()
{
super(State.DISCONNECTED, TRANSITION_TABLE);
}
//--- Method(s) ---
protected synchronized void stateChanged(State oldState,
State newState)
{
if (newState == State.CONNECTING) {
Runnable runner = new Runnable()
{
public void run()
{
connect();
}
};
Thread t
= new Thread(runner, "PircBotServer " + getName());
t.start();
return;
}
else if (newState == State.CONNECTED) {
String connectCommand = PircBotServer.this.getConnectCommand();
if (connectCommand != null && connectCommand.length() > 0) {
Executer.parse(connectCommand, getBot());
}
String autoJoin = PircBotServer.this.getAutoJoinChannels();
if (autoJoin != null && autoJoin.length() > 0) {
// auto join channels
String[] channels = StringHelper.toArray(autoJoin, ";,");
for (int i = 0; i < channels.length; i++) {
PircBotServer.this.join(channels[i]);
}
}
}
}
private void connect()
{
try {
String login = PircBotServer.this.getLogin();
login = (login != null && login.length() > 0)
? login
: Preferences.getInstance().getUsername();
String nick = PircBotServer.this.getNick();
nick = (nick != null && nick.length() > 0)
? nick
: Preferences.getInstance().getUsername();
String password = PircBotServer.this.getPassword();
for (int i = 0; i < 3; i++) {
try {
getBot().setLogin(login, nick);
if (password != null && password.length() > 0) {
getBot().connect(PircBotServer.this.getHost(),
PircBotServer.this.getPort(),
password);
}
else {
getBot().connect(PircBotServer.this.getHost(),
PircBotServer.this.getPort());
}
break;
}
catch (NickAlreadyInUseException e2) {
nick += "_";
}
}
}
catch (Exception e) {
logger.debug("connect failed", e);
String msg = (e instanceof IOException)
? NetHelper.getErrorMessage((IOException)e)
: e.getLocalizedMessage();
PircBotServer.this.setState
(State.DISCONNECTED, XNap.tr("connect failed: {0}", msg));
return;
}
}
}
class Server extends PircBot implements Console {
//--- Constant(s) ---
//--- Data field(s) ---
/**
* Contains {@link ChannelInfo} objects.
*/
private HashSet channels = new HashSet();
/**
* A list of PircBotChannel objects. Contains the channels that have
* been added to the {@link ChatManager}.
*/
private Hashtable channelByName = new Hashtable();
private Hashtable peerByName = new Hashtable();
private LocalExecuter executer;
//--- Constructor(s) ---
public Server()
{
executer = new LocalExecuter(getCommands());
}
//--- Method(s) ---
/**
* Closes all channels.
*/
public void removeAllChannels()
{
for (Iterator i = channelByName.values().iterator(); i.hasNext();) {
PircBotChannel c = (PircBotChannel)i.next();
partChannel(c.getName());
ChatManager.getInstance().remove(c);
}
channelByName.clear();
}
public PircBotChannel getChannelByName(String name)
{
PircBotChannel channel = (PircBotChannel)channelByName.get(name);
if (channel == null) {
channel = new PircBotChannel(PircBotServer.this, name);
channelByName.put(name, channel);
ChatManager.getInstance().add(channel);
}
return channel;
}
public PircBotChannel getPrivateChannelByName(String name)
{
PircBotChannel channel = (PircBotChannel)channelByName.get(name);
if (channel == null) {
channel = new PircBotChannel(PircBotServer.this, name);
channel.add(getPeerByName(this.getNick()));
channel.add(getPeerByName(name));
channelByName.put(name, channel);
ChatManager.getInstance().add(channel);
}
return channel;
}
public void removeChannel(PircBotChannel channel)
{
channelByName.remove(channel.getName());
}
public synchronized ChannelInfo[] getChannelInfos()
{
// add joined channels to list of channels
String[] joinedChannels = this.getChannels();
for (int i = 0; i < joinedChannels.length; i++) {
ChannelInfo ci = new DefaultChannelInfo(joinedChannels[i]);
if (!channels.contains(ci)) {
channels.add(ci);
}
}
return (ChannelInfo[])channels.toArray(new ChannelInfo[0]);
}
public PircBotPeer getPeerByName(String name)
{
PircBotPeer peer = (PircBotPeer)peerByName.get(name);
if (peer == null) {
peer = new PircBotPeer(PircBotServer.this, name);
peerByName.put(name, peer);
}
return peer;
}
protected synchronized void onChannelInfo(String channel,
int userCount, String topic)
{
channels.add(new DefaultChannelInfo(channel, userCount, topic));
channelsUpdated();
}
protected void onAction(String sender, String login,
String hostname, String channel,
String message)
{
PircBotChannel c = getChannelByName(channel);
c.actionMessageReceived(getPeerByName(sender), message);
}
protected void onConnect()
{
PircBotServer.this.setState(State.CONNECTED);
logger.debug("connected to " + PircBotServer.this.getName());
ChatManager.getInstance().add(PircBotServer.this);
}
protected void onDeop(String channel, String sourceNick,
String sourceLogin, String sourceHostname,
String recipient)
{
PircBotPeer p = getPeerByName(recipient);
PircBotChannel c = getChannelByName(channel);
c.setOp(p, false);
}
protected void onDeVoice(String channel, String sourceNick,
String sourceLogin, String sourceHostname,
String recipient)
{
PircBotPeer p = getPeerByName(recipient);
PircBotChannel c = getChannelByName(channel);
c.setVoice(p, false);
}
protected void onDisconnect()
{
for (Iterator i = channelByName.values().iterator(); i.hasNext();) {
PircBotChannel c = (PircBotChannel)i.next();
c.setJoined(false, XNap.tr("client disconnected"));
}
PircBotServer.this.setState(State.DISCONNECTED);
logger.debug("disconnected from " + PircBotServer.this.getName());
ChatManager.getInstance().remove(PircBotServer.this);
}
protected void onIncomingFileTransfer(DccFileTransfer transfer)
{
DccDownload d = new DccDownload
(getPeerByName(transfer.getNick()),
transfer.getFile().getName(),
transfer.getSize(),
transfer.getHostname(),
transfer.getPort());
DownloadManager.getInstance().add(d);
}
protected void onJoin(String channel, String sender, String login,
String hostname)
{
PircBotPeer p = getPeerByName(sender);
p.setHost(hostname);
PircBotChannel c = getChannelByName(channel);
c.add(p);
}
protected void onMessage(String channel, String sender, String login,
String hostname, String message)
{
PircBotChannel c = getChannelByName(channel);
c.messageReceived(getPeerByName(sender), message);
}
protected void onNickChange(String oldNick, String login,
String hostname, String newNick)
{
PircBotPeer peer = getPeerByName(oldNick);
peer.setHost(hostname);
peer.setName(newNick);
for (Iterator i = channelByName.values().iterator();
i.hasNext();) {
((PircBotChannel)i.next()).peerChanged(peer);
}
}
protected void onNotice(String sourceNick, String sourceLogin,
String sourceHostname, String target,
String notice)
{
logger.debug("notice: " + notice);
// try to recognize affected channel like [#xnap]
int i = notice.indexOf("[#");
int j = notice.indexOf("]", i);
if (i != -1 && j != -1) {
target = notice.substring(i + 1, j);
logger.warn("x:" + target);
}
PircBotChannel c = getChannelByName(target);
c.infoReceived(notice);
}
protected void onPart(String channel, String sender,
String login, String hostname)
{
PircBotChannel c = (PircBotChannel)channelByName.get(channel);
if (c != null) {
if (sender.equals(this.getNick())) {
c.setJoined(false, null);
}
c.remove(getPeerByName(sender));
}
}
protected void onPrivateMessage(String sender, String login,
String hostname, String message)
{
PircBotChannel c = getPrivateChannelByName(sender);
c.messageReceived(getPeerByName(sender), message);
}
protected void onOp(String channel, String sourceNick,
String sourceLogin, String sourceHostname,
String recipient)
{
PircBotPeer p = getPeerByName(recipient);
PircBotChannel c = getChannelByName(channel);
c.setOp(p, true);
}
protected void onTopic(String channel, String topic, String setBy, long date, boolean changed)
{
PircBotChannel c = getChannelByName(channel);
c.topicChanged(topic);
}
protected void onServerResponse(int code, String response)
{
logger.debug(code + ": " + response);
String nick = this.getNick();
if (response.startsWith(nick + " :")) {
response = response.substring(nick.length() + 2);
}
if (code >= 400 && code <= 599) {
// error message
messageReceived(response + "\n");
return;
}
switch (code) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 251:
case 254:
case 255:
case RPL_WHOISUSER:
case RPL_WHOISSERVER:
case RPL_WHOISOPERATOR:
case RPL_WHOWASUSER:
case RPL_ENDOFWHO:
case RPL_WHOISIDLE:
case RPL_ENDOFWHOIS:
case RPL_WHOISCHANNELS:
case RPL_MOTD:
messageReceived(response + "\n");
break;
}
}
protected void onUserList(String channel, User[] users)
{
PircBotChannel c = getChannelByName(channel);
for (int i = 0; i < users.length; i++) {
PircBotPeer p = getPeerByName(users[i].getNick());
c.setOp(p, users[i].isOp());
c.add(p);
}
}
protected void onVoice(String channel, String sourceNick,
String sourceLogin, String sourceHostname,
String recipient)
{
PircBotPeer p = getPeerByName(recipient);
PircBotChannel c = getChannelByName(channel);
c.setVoice(p, true);
}
public void setLogin(String login, String nick)
{
super.setFinger("XNap/PircBot");
super.setLogin(login);
super.setName(nick);
}
public void whois(String nick)
{
sendRawLine("WHOIS " + nick);
}
/**
* @see org.xnap.cmdl.Console#getCommand(java.lang.String)
*/
public Command getCommand(String commandName)
{
return executer.getCommand(commandName);
}
/**
* @see org.xnap.cmdl.Console#getCommands()
*/
public Command[] getCommands()
{
return new Command[] { new PircBotMessageCommand(PircBotServer.this) };
}
/**
* @see org.xnap.cmdl.Console#isEchoing()
*/
public boolean isEchoing()
{
return false;
}
/**
* @see org.xnap.cmdl.Console#readln(java.lang.String)
*/
public String readln(String prompt)
{
return null;
}
/**
* @see org.xnap.cmdl.Console#println(java.lang.String)
*/
public void println(String text)
{
messageReceived(text);
}
}
/**
* Queries the list of channels from the server.
*/
private class ListChannelsAction extends AbstractListChannelsAction
{
public void actionPerformed(ActionEvent event)
{
PircBotServer.this.getBot().listChannels();
channelsUpdated();
}
}
}
The table below shows all metrics for PircBotServer.java.




