ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/i-scream/projects/cms/source/server/uk/org/iscream/cms/server/client/alerters/IRC__Alerter.java
(Generate patch)

Comparing projects/cms/source/server/uk/org/iscream/cms/server/client/alerters/IRC__Alerter.java (file contents):
Revision 1.15 by ajm, Mon Mar 5 12:45:51 2001 UTC vs.
Revision 1.25 by ajm, Fri Mar 23 01:09:51 2001 UTC

# Line 1 | Line 1
1   //---PACKAGE DECLARATION---
2 < package uk.ac.ukc.iscream.client.alerters;
2 > package uk.org.iscream.client.alerters;
3  
4   //---IMPORTS---
5 < import uk.ac.ukc.iscream.client.*;
6 < import uk.ac.ukc.iscream.core.*;
7 < import uk.ac.ukc.iscream.util.*;
8 < import uk.ac.ukc.iscream.componentmanager.*;
9 <
5 > import uk.org.iscream.client.*;
6 > import uk.org.iscream.core.*;
7 > import uk.org.iscream.util.*;
8 > import uk.org.iscream.componentmanager.*;
9   import java.io.*;
10   import java.net.*;
11   import java.util.*;
12 < import java.text.*;
12 > import java.text.DateFormat;
13  
14   /**
15   * This Alert sends an IRC message.
# Line 21 | Line 20 | import java.text.*;
20   * @author  $Author$
21   * @version $Id$
22   */
23 < public class IRC__Alerter implements PluginAlerter {
23 > public class IRC__Alerter extends AlerterSkeleton {
24  
25   //---FINAL ATTRIBUTES---
26  
# Line 45 | Line 44 | public class IRC__Alerter implements PluginAlerter {
44   //---CONSTRUCTORS---
45  
46      public IRC__Alerter() {
47 <                        
47 >        super();
48          // connect to the IRC server
49          _ircbot = new IRCBot();
50 +        // set it's name and start it
51 +        _ircbot.setName("client.IRC__Alerter$IRCBot");
52          _ircbot.start();
53          _startTime = System.currentTimeMillis();
53        
54          _logger.write(toString(), Logger.SYSINIT, "IRC Alerter started");
55      }
56  
57   //---PUBLIC METHODS---
58  
59 +    /**
60 +     * Implements the abstract method from the skeleton class.
61 +     * This method will attempt to send an alert
62 +     * message over the IRC channel.
63 +     *
64 +     * @param alert the alert to send
65 +     */
66      public void sendAlert(Alert alert) {
67          // only send alerts if we're active
68          if(_active) {
69 <            ConfigurationProxy cp = ConfigurationProxy.getInstance();
70 <            String levelName = cp.getProperty(_name, "Alerter.IRC.level");
71 <            int level = StringUtils.getStringPos(levelName, Alert.alertLevels);
72 <            // only send if it's equal (or above) our level
73 <            if(((alert.getLevel() == 0) && (alert.getLastLevel() >= level)) || (alert.getLevel() >= level)) {
74 <                String alertType = Alert.alertLevels[alert.getLevel()];
75 <                String thresholdType = Alert.thresholdLevels[alert.getThreshold()];
76 <                // sort out the message
70 <                String message = cp.getProperty(_name, "Alerter.IRC.message");
71 <                message = StringUtils.replaceText(message, "%level%", alertType);
72 <                message = StringUtils.replaceText(message, "%threshold%", thresholdType);
73 <                message = StringUtils.replaceText(message, "%source%", alert.getSource());
74 <                message = StringUtils.replaceText(message, "%value%", alert.getValue());
75 <                message = StringUtils.replaceText(message, "%thresholdValue%", alert.getThresholdValue());
76 <                message = StringUtils.replaceText(message, "%attributeName%", alert.getAttributeName());
77 <                message = StringUtils.replaceText(message, "%timeTillNextAlert%",  getTimeString(Long.parseLong(alert.getTimeTillNextAlert())));
78 <                
79 <                // send the message
80 <                _logger.write(toString(), Logger.DEBUG, "Sending " + _name + " at "+ alertType + " level");
81 <                _ircbot.sendMsg(message);
82 <                _lastAlert = message;
83 <                _lastAlertTime = System.currentTimeMillis();
84 <                _alertCount ++;
69 >            // sort out the message      
70 >            String alertType = Alert.alertLevels[alert.getLevel()];        
71 >            String message;
72 >            try {
73 >                message = _cp.getProperty(_name, "Alerter.IRC.message");
74 >            } catch (PropertyNotFoundException e) {
75 >                message = NOT_CONFIGURED;
76 >                _logger.write(toString(), Logger.WARNING, "Alerter.IRC.message value unavailable using default of " + message);
77              }
78 +            message = processAlertMessage(message, alert);                
79 +            
80 +            // send the message
81 +            _logger.write(toString(), Logger.DEBUG, "Sending " + _name + " at "+ alertType + " level");
82 +            _ircbot.sendMsg(message);
83 +            _lastAlert = message;
84 +            _lastAlertTime = System.currentTimeMillis();
85 +            _alertCount ++;
86 +        } else {
87 +            _ignoredCount ++;
88          }
89      }
90  
# Line 90 | Line 92 | public class IRC__Alerter implements PluginAlerter {
92       * Overrides the {@link java.lang.Object#toString() Object.toString()}
93       * method to provide clean logging (every class should have this).
94       *
95 <     * This uses the uk.ac.ukc.iscream.util.NameFormat class
95 >     * This uses the uk.org.iscream.util.NameFormat class
96       * to format the toString()
97       *
98       * @return the name of this class and its CVS revision
# Line 102 | Line 104 | public class IRC__Alerter implements PluginAlerter {
104              REVISION);
105      }
106  
107 <    /**
108 <     * return the String representation of what the filter does
107 >    /**
108 >     * Return the String representation of what the alerter does
109 >     *
110 >     * @return the description
111       */
112      public String getDescription(){
113          return DESC;
# Line 111 | Line 115 | public class IRC__Alerter implements PluginAlerter {
115  
116   //---PRIVATE METHODS---
117  
114    private String getTimeString(long time) {
115        String timeString = null;
116        if (time >= 60) {
117            timeString = (time / 60) + " minute(s)";
118        } else if (time >= 3600) {
119            timeString = ((time/60) / 60) + " hour(s)";
120        } else {
121            timeString = time + " second(s)";
122        }
123        return timeString;
124    }
125
118   //---ACCESSOR/MUTATOR METHODS---
119  
120   //---ATTRIBUTES---
# Line 150 | Line 142 | public class IRC__Alerter implements PluginAlerter {
142      /**
143       * Number of alerts sent
144       */
145 <    private long _alertCount = 0;
145 >    private int _alertCount = 0;
146      
147      /**
148 +     * Number of alerts ignored when in "stopped" mode
149 +     */
150 +    private int _ignoredCount = 0;
151 +    
152 +    /**
153       * Time of IRCBot startup
154       */
155      private long _startTime;
# Line 166 | Line 163 | public class IRC__Alerter implements PluginAlerter {
163       * can be placed here.  This name could also
164       * be changed to null for utility classes.
165       */
166 <    private String _name = "IRC Alert";
166 >    private String _name = "IRC";
167  
171    /**
172     * This holds a reference to the
173     * system logger that is being used.
174     */
175    private Logger _logger = ReferenceManager.getInstance().getLogger();
176
168   //---STATIC ATTRIBUTES---
169  
170   //---INNER CLASSES---
# Line 186 | Line 177 | public class IRC__Alerter implements PluginAlerter {
177       */
178      class IRCBot extends Thread {
179          
180 +        public static final String DEFAULT_STARTUP_NOTICE = "i-scream ircbot starting...";
181 +        
182          /**
183           * Main thread loop, this part of the class listens for
184           * messages from the server, and acts accordingly. At the
# Line 197 | Line 190 | public class IRC__Alerter implements PluginAlerter {
190              while(run) {
191                  // flag so we can stop the loop
192                  boolean doRead = true;
193 +                // get the startup notice
194 +                String startupNotice;
195 +                try {
196 +                    startupNotice = ConfigurationProxy.getInstance().getProperty(_name, "Alerter.IRC.startupNotice");
197 +                } catch (PropertyNotFoundException e) {
198 +                    startupNotice = DEFAULT_STARTUP_NOTICE;
199 +                    _logger.write(this.toString(), Logger.WARNING, "Configuration error: "+e);
200 +                }
201                  // connect to the IRC server
202                  try {
203                      connect();
204 <                    sendNotice(ConfigurationProxy.getInstance().getProperty(_name, "Alerter.IRC.startupNotice"));
204 >                    sendNotice(startupNotice);
205                  } catch(IOException e) {
206                      doRead=false;
207                      _logger.write(this.toString(), Logger.ERROR, "Error connecting: "+e);
# Line 236 | Line 237 | public class IRC__Alerter implements PluginAlerter {
237                  } catch (NumberFormatException e) {
238                      delayTime = DEFAULT_RECONNECT_DELAY;
239                      _logger.write(this.toString(), Logger.WARNING, "Erronous Alerter.IRC.reconnectDelay value in configuration using default of " + delayTime + " seconds");
240 <                } catch (org.omg.CORBA.MARSHAL e2) {
240 >                } catch (PropertyNotFoundException e) {
241                      delayTime = DEFAULT_RECONNECT_DELAY;
242                      _logger.write(this.toString(), Logger.WARNING, "Alerter.IRC.reconnectDelay value unavailable using default of " + delayTime + " seconds");
243                  }
# Line 306 | Line 307 | public class IRC__Alerter implements PluginAlerter {
307          public void connect() throws IOException {
308              ConfigurationProxy cp = ConfigurationProxy.getInstance();
309              // setup the socket, reader and writer
310 <            String server = cp.getProperty(_name, "Alerter.IRC.IRCServer");
311 <            int port = Integer.parseInt(cp.getProperty(_name, "Alerter.IRC.IRCPort"));
310 >            String server;
311 >            int port;
312 >            try {
313 >                server = cp.getProperty(_name, "Alerter.IRC.IRCServer");
314 >                port = Integer.parseInt(cp.getProperty(_name, "Alerter.IRC.IRCPort"));
315 >            } catch (PropertyNotFoundException e) {
316 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
317 >                throw new IOException("Can't get irc server details due to configuration error");
318 >            } catch (NumberFormatException e) {
319 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
320 >                throw new IOException("Can't get irc server details due to malformed configuration");
321 >            }
322              _socket = new Socket(server, port);
323              _socketIn = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
324              _socketOut = new PrintWriter(_socket.getOutputStream(), true);
325              //_socketOut.println("PASS");
326              // send USER details
327 <            String user = cp.getProperty(_name, "Alerter.IRC.user");
328 <            String comment = cp.getProperty(_name, "Alerter.IRC.comment");
327 >            String user, comment;
328 >            try {
329 >                user = cp.getProperty(_name, "Alerter.IRC.user");
330 >                comment = cp.getProperty(_name, "Alerter.IRC.comment");
331 >            } catch (PropertyNotFoundException e) {
332 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
333 >                throw new IOException("Can't get user details due to configuration error");
334 >            }
335              _socketOut.println("USER "+user+" 8 * :"+comment);
336              // attempt to get a nick
337 <            String nickList = cp.getProperty(_name, "Alerter.IRC.nickList");
337 >            String nickList;
338 >            try {
339 >                nickList = cp.getProperty(_name, "Alerter.IRC.nickList");
340 >            } catch (PropertyNotFoundException e) {
341 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
342 >                throw new IOException("Can't get nickname due to configuration error");
343 >            }
344              StringTokenizer st = new StringTokenizer(nickList, ";");
345              boolean ok = false;
346              // try until we exhaust our list
# Line 349 | Line 372 | public class IRC__Alerter implements PluginAlerter {
372                  throw new IOException("All nicknames in use");
373              }
374              // join the channel
375 <            _channel = cp.getProperty(_name, "Alerter.IRC.channel");
375 >            try {
376 >                _channel = cp.getProperty(_name, "Alerter.IRC.channel");
377 >            } catch (PropertyNotFoundException e) {
378 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
379 >                throw new IOException("Can't get channel name due to configuration error");
380 >            }
381              _socketOut.println("JOIN "+_channel);
382              // allow alerts
383              _active = true;
# Line 375 | Line 403 | public class IRC__Alerter implements PluginAlerter {
403           * Overrides the {@link java.lang.Object#toString() Object.toString()}
404           * method to provide clean logging (every class should have this).
405           *
406 <         * This uses the uk.ac.ukc.iscream.util.NameFormat class
406 >         * This uses the uk.org.iscream.util.NameFormat class
407           * to format the toString()
408           *
409           * @return the name of this class and its CVS revision
# Line 400 | Line 428 | public class IRC__Alerter implements PluginAlerter {
428                  _socketOut.println("PONG" + line.substring(4));
429              }
430              // see if it's for us
431 <            else if(getMsg(line).startsWith(_nickname+",")
432 <                    || getMsg(line).startsWith(_nickname+":")
433 <                    || getMsg(line).startsWith(_nickname+" ")) {
431 >            else if(getMsg(line).startsWith(_nickname+",") || getMsg(line).startsWith(_nickname+":") || getMsg(line).startsWith(_nickname+" ")) {
432 >                // setup some String's
433 >                String stopCommand, startCommand, timeSinceLastAlertCommand, lastAlertCommand, joinCommand;
434 >                String nickChangeCommand, versionCommand, helpCommand, statCommand, uptimeCommand;
435 >                // get the command set
436 >                try {
437 >                    stopCommand = cp.getProperty(_name, "Alerter.IRC.stopCommand");
438 >                    startCommand = cp.getProperty(_name, "Alerter.IRC.startCommand");
439 >                    timeSinceLastAlertCommand = cp.getProperty(_name, "Alerter.IRC.timeSinceLastAlertCommand");
440 >                    lastAlertCommand = cp.getProperty(_name, "Alerter.IRC.lastAlertCommand");
441 >                    joinCommand = cp.getProperty(_name, "Alerter.IRC.joinCommand");
442 >                    nickChangeCommand = cp.getProperty(_name, "Alerter.IRC.nickChangeCommand");
443 >                    versionCommand = cp.getProperty(_name, "Alerter.IRC.versionCommand");
444 >                    helpCommand = cp.getProperty(_name, "Alerter.IRC.helpCommand");
445 >                    statCommand = cp.getProperty(_name, "Alerter.IRC.statCommand");
446 >                    uptimeCommand = cp.getProperty(_name, "Alerter.IRC.uptimeCommand");
447 >                } catch (PropertyNotFoundException e) {
448 >                    _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
449 >                    // lets bail from handling this line...
450 >                    // ...it's gonna be hard without a command set!
451 >                    return;
452 >                }
453 >                
454                  // we have a message for us
455                  String message = getMsg(line).substring(_nickname.length());
456 <                if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.stopCommand"))!=-1) {
456 >                if(message.indexOf(stopCommand)!=-1) {
457                      _active = false;
458                      sendMsg(getMsgSender(line)+", alerts have been stopped");
459                  }
460 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.startCommand"))!=-1) {
460 >                else if(message.indexOf(startCommand)!=-1) {
461                      _active = true;
462                      sendMsg(getMsgSender(line)+", alerts have been activated");
463                  }
464                  // this needs to go here if it contains the same words as the lastAlertCommand
465 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.timeSinceLastAlertCommand"))!=-1) {
465 >                else if(message.indexOf(timeSinceLastAlertCommand)!=-1) {
466                      if(_lastAlertTime != -1) {
467                          long uptime = (System.currentTimeMillis() - _lastAlertTime) / 1000;
468                          String uptimeText = DateUtils.formatTime(uptime, "%DAYS% days, %HOURS% hours, %MINS% mins, and %SECS% secs");
# Line 424 | Line 472 | public class IRC__Alerter implements PluginAlerter {
472                          sendMsg(getMsgSender(line)+", I've never sent an alert!");
473                      }
474                  }
475 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.lastAlertCommand"))!=-1) {
475 >                else if(message.indexOf(lastAlertCommand)!=-1) {
476                      if(_lastAlertTime != -1) {
477                          String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.UK).format(new Date(_lastAlertTime));
478                          sendMsg(getMsgSender(line)+", last alert was at "+date+"; "+_lastAlert);
# Line 434 | Line 482 | public class IRC__Alerter implements PluginAlerter {
482                      }
483                      
484                  }
485 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.joinCommand"))!=-1) {
486 <                    String joinCmd = cp.getProperty(_name, "Alerter.IRC.joinCommand");
485 >                else if(message.indexOf(joinCommand)!=-1) {
486 >                    String joinCmd = joinCommand;
487                      String newChan = message.substring(message.indexOf(joinCmd) + joinCmd.length() + 1);
488                      int endOfChan = newChan.indexOf(" ");
489                      if(endOfChan == -1) {
490                          endOfChan = newChan.length();
491                      }
492                      newChan = newChan.substring(0, endOfChan);
493 <                    sendMsg(getMsgSender(line)+", okay, I'm off to "+newChan);
494 <                    _socketOut.println("PART "+_channel);
495 <                    _socketOut.println("JOIN "+newChan);
496 <                    _channel = newChan;
493 >                    if(newChan.equals(_channel)) {
494 >                        sendMsg(getMsgSender(line)+", I'm already on "+newChan+"!");
495 >                    } else {
496 >                        sendMsg(getMsgSender(line)+", okay, I'm off to "+newChan);
497 >                        _socketOut.println("PART "+_channel);
498 >                        _socketOut.println("JOIN "+newChan);
499 >                        _channel = newChan;
500 >                    }
501                  }
502 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.nickChangeCommand"))!=-1) {
503 <                    String nickChangeCmd = cp.getProperty(_name, "Alerter.IRC.nickChangeCommand");
502 >                else if(message.indexOf(nickChangeCommand)!=-1) {
503 >                    String nickChangeCmd = nickChangeCommand;
504                      String newNick = message.substring(message.indexOf(nickChangeCmd) + nickChangeCmd.length() + 1);
505                      int endOfNick = newNick.indexOf(" ");
506                      if(endOfNick == -1) {
# Line 459 | Line 511 | public class IRC__Alerter implements PluginAlerter {
511                      _socketOut.println("NICK "+newNick);
512                      _nickname = newNick;
513                  }
514 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.versionCommand"))!=-1) {
514 >                else if(message.indexOf(versionCommand)!=-1) {
515                      sendMsg(getMsgSender(line)+", I am version "+REVISION.substring(11, REVISION.length() -2)+" of the i-scream alerting bot");
516                  }
517 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.helpCommand"))!=-1) {
517 >                else if(message.indexOf(helpCommand)!=-1) {
518                      sendPrivMsg(getMsgSender(line), "Hello, I am the i-scream alerting bot version "+REVISION.substring(11, REVISION.length() -2));
519                      sendPrivMsg(getMsgSender(line), "I understand the following commands;");
520 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.stopCommand"));
521 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.startCommand"));
522 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.lastAlertCommand"));
523 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.joinCommand"));
524 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.nickChangeCommand"));
525 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.statCommand"));
526 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.uptimeCommand"));
527 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.timeSinceLastAlertCommand"));
528 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.helpCommand"));
520 >                    sendPrivMsg(getMsgSender(line), stopCommand);
521 >                    sendPrivMsg(getMsgSender(line), startCommand);
522 >                    sendPrivMsg(getMsgSender(line), lastAlertCommand);
523 >                    sendPrivMsg(getMsgSender(line), joinCommand);
524 >                    sendPrivMsg(getMsgSender(line), nickChangeCommand);
525 >                    sendPrivMsg(getMsgSender(line), statCommand);
526 >                    sendPrivMsg(getMsgSender(line), uptimeCommand);
527 >                    sendPrivMsg(getMsgSender(line), timeSinceLastAlertCommand);
528 >                    sendPrivMsg(getMsgSender(line), helpCommand);
529                  }
530 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.statCommand"))!=-1) {
531 <                    sendMsg(getMsgSender(line)+", I have sent a total of "+_alertCount+" alerts!");
530 >                else if(message.indexOf(statCommand)!=-1) {
531 >                    sendMsg(getMsgSender(line)+", I have sent a total of "+_alertCount+" alerts, and ignored a total of "+_ignoredCount+"!");
532                  }
533 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.uptimeCommand"))!=-1) {
533 >                else if(message.indexOf(uptimeCommand)!=-1) {
534                      long uptime = (System.currentTimeMillis() - _startTime) / 1000;
535                      String uptimeText = DateUtils.formatTime(uptime, "%DAYS% days, %HOURS% hours, %MINS% mins, and %SECS% secs");
536                      sendMsg(getMsgSender(line)+", I have been running for "+uptimeText);
537                  }
538 +                else if(message.indexOf("ping")!=-1) {
539 +                    sendMsg("pong");
540 +                }
541                  else if(message.indexOf("do a jibble dance")!=-1) {
542                      // little joke :)
543                      sendAction("jives to the funky beat shouting \"ii--screeeaaammm\"");
544                  }
545                  else {
546 <                    sendMsg(getMsgSender(line)+", "+cp.getProperty(_name, "Alerter.IRC.rejectMessage"));
546 >                    String rejectMessage = NOT_CONFIGURED;
547 >                    try {
548 >                        rejectMessage = cp.getProperty(_name, "Alerter.IRC.rejectMessage");
549 >                    } catch(PropertyNotFoundException e) {
550 >                        _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
551 >                    }
552 >                    sendMsg(getMsgSender(line)+", "+rejectMessage);
553                  }
554              }
555              else if(line.indexOf(_nickname)!=-1 && line.indexOf(_channel)!=-1 && line.indexOf("KICK")!=-1) {
556                  sendPrivMsg(getMsgSender(line), "That wasn't a nice thing to do...");
557 <                _channel = cp.getProperty(_name, "Alerter.IRC.channel");
557 >                try {
558 >                    _channel = cp.getProperty(_name, "Alerter.IRC.channel");
559 >                } catch(PropertyNotFoundException e) {
560 >                    _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
561 >                }
562                  _socketOut.println("JOIN "+_channel);
563              }
564          }
# Line 559 | Line 624 | public class IRC__Alerter implements PluginAlerter {
624           * A reminder of our current nickname...
625           */
626          private String _nickname;
627 +        
628 +        /**
629 +         * This holds a reference to the
630 +         * system logger that is being used.
631 +         */
632 +        protected Logger _logger = ReferenceManager.getInstance().getLogger();
633          
634      }
635  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines