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.10 by ajm, Sun Mar 4 04:43:29 2001 UTC vs.
Revision 1.18 by tdb, Thu Mar 8 13:43:54 2001 UTC

# Line 10 | Line 10 | import uk.ac.ukc.iscream.componentmanager.*;
10   import java.io.*;
11   import java.net.*;
12   import java.util.*;
13 + import java.text.*;
14  
15   /**
16   * This Alert sends an IRC message.
# Line 39 | Line 40 | public class IRC__Alerter implements PluginAlerter {
40       */
41      public final int DEFAULT_RECONNECT_DELAY = 30;
42      
43 +    public final String DEFAULT_LEVEL = Alert.alertLevels[0];
44 +    
45 +    public final String NOT_CONFIGURED = "<NOT CONFIGURED>";
46 +    
47   //---STATIC METHODS---
48  
49   //---CONSTRUCTORS---
# Line 48 | Line 53 | public class IRC__Alerter implements PluginAlerter {
53          // connect to the IRC server
54          _ircbot = new IRCBot();
55          _ircbot.start();
56 +        _startTime = System.currentTimeMillis();
57          
58          _logger.write(toString(), Logger.SYSINIT, "IRC Alerter started");
59      }
# Line 58 | Line 64 | public class IRC__Alerter implements PluginAlerter {
64          // only send alerts if we're active
65          if(_active) {
66              ConfigurationProxy cp = ConfigurationProxy.getInstance();
67 <            String levelName = cp.getProperty(_name, "Alerter.IRC.level");
67 >            
68 >            String levelName;
69 >            try {
70 >                levelName = cp.getProperty(_name, "Alerter.IRC.level");
71 >            } catch (PropertyNotFoundException e) {
72 >                levelName = DEFAULT_LEVEL;
73 >                _logger.write(toString(), Logger.WARNING, "Alerter.IRC.level value unavailable using default of " + levelName);
74 >            }
75              int level = StringUtils.getStringPos(levelName, Alert.alertLevels);
76              // only send if it's equal (or above) our level
77 <            if(alert.getLevel() >= level) {
77 >            if(((alert.getLevel() == 0) && (alert.getLastLevel() >= level)) || (alert.getLevel() >= level)) {
78                  String alertType = Alert.alertLevels[alert.getLevel()];
79                  String thresholdType = Alert.thresholdLevels[alert.getThreshold()];
80 <                // sort out the message
81 <                String message = cp.getProperty(_name, "Alerter.IRC.message");
80 >                String timeFirstSince = DateUtils.formatTime(System.currentTimeMillis() - alert.getInitialAlertTime(), "%DAYS% days, %HOURS% hours, %MINS% mins, and %SECS% secs");
81 >                String timeFirstOccured = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.UK).format(new Date(alert.getInitialAlertTime()));
82 >                // sort out the message              
83 >                String message;
84 >                try {
85 >                    message = cp.getProperty(_name, "Alerter.IRC.message");
86 >                } catch (PropertyNotFoundException e) {
87 >                    message = NOT_CONFIGURED;
88 >                    _logger.write(toString(), Logger.WARNING, "Alerter.IRC.message value unavailable using default of " + message);
89 >                }
90 >                
91                  message = StringUtils.replaceText(message, "%level%", alertType);
92                  message = StringUtils.replaceText(message, "%threshold%", thresholdType);
93                  message = StringUtils.replaceText(message, "%source%", alert.getSource());
# Line 73 | Line 95 | public class IRC__Alerter implements PluginAlerter {
95                  message = StringUtils.replaceText(message, "%thresholdValue%", alert.getThresholdValue());
96                  message = StringUtils.replaceText(message, "%attributeName%", alert.getAttributeName());
97                  message = StringUtils.replaceText(message, "%timeTillNextAlert%",  getTimeString(Long.parseLong(alert.getTimeTillNextAlert())));
98 +                message = StringUtils.replaceText(message, "%timeSinceFirstAlert%", timeFirstSince);
99 +                message = StringUtils.replaceText(message, "%timeOfFirstAlert%", timeFirstOccured);
100                  
101                  // send the message
102                  _logger.write(toString(), Logger.DEBUG, "Sending " + _name + " at "+ alertType + " level");
103                  _ircbot.sendMsg(message);
104                  _lastAlert = message;
105 +                _lastAlertTime = System.currentTimeMillis();
106 +                _alertCount ++;
107              }
108          }
109 +        else {
110 +            _ignoredCount ++;
111 +        }
112      }
113  
114      /**
# Line 139 | Line 168 | public class IRC__Alerter implements PluginAlerter {
168      private String _lastAlert = "no alerts have been sent";
169      
170      /**
171 +     * The time of the last alert
172 +     */
173 +    private long _lastAlertTime = -1;
174 +    
175 +    /**
176 +     * Number of alerts sent
177 +     */
178 +    private int _alertCount = 0;
179 +    
180 +    /**
181 +     * Number of alerts ignored when in "stopped" mode
182 +     */
183 +    private int _ignoredCount = 0;
184 +    
185 +    /**
186 +     * Time of IRCBot startup
187 +     */
188 +    private long _startTime;
189 +    
190 +    /**
191       * This is the friendly identifier of the
192       * component this class is running in.
193       * eg, a Filter may be called "filter1",
# Line 167 | Line 216 | public class IRC__Alerter implements PluginAlerter {
216       */
217      class IRCBot extends Thread {
218          
219 +        public static final String DEFAULT_STARTUP_NOTICE = "i-scream ircbot starting...";
220 +        
221          /**
222           * Main thread loop, this part of the class listens for
223           * messages from the server, and acts accordingly. At the
# Line 178 | Line 229 | public class IRC__Alerter implements PluginAlerter {
229              while(run) {
230                  // flag so we can stop the loop
231                  boolean doRead = true;
232 +                // get the startup notice
233 +                String startupNotice;
234 +                try {
235 +                    startupNotice = ConfigurationProxy.getInstance().getProperty(_name, "Alerter.IRC.startupNotice");
236 +                } catch (PropertyNotFoundException e) {
237 +                    startupNotice = DEFAULT_STARTUP_NOTICE;
238 +                    _logger.write(this.toString(), Logger.WARNING, "Configuration error: "+e);
239 +                }
240                  // connect to the IRC server
241                  try {
242                      connect();
243 <                    sendNotice(ConfigurationProxy.getInstance().getProperty(_name, "Alerter.IRC.startupNotice"));
243 >                    sendNotice(startupNotice);
244                  } catch(IOException e) {
245                      doRead=false;
246                      _logger.write(this.toString(), Logger.ERROR, "Error connecting: "+e);
# Line 217 | Line 276 | public class IRC__Alerter implements PluginAlerter {
276                  } catch (NumberFormatException e) {
277                      delayTime = DEFAULT_RECONNECT_DELAY;
278                      _logger.write(this.toString(), Logger.WARNING, "Erronous Alerter.IRC.reconnectDelay value in configuration using default of " + delayTime + " seconds");
279 <                } catch (org.omg.CORBA.MARSHAL e2) {
279 >                } catch (PropertyNotFoundException e) {
280                      delayTime = DEFAULT_RECONNECT_DELAY;
281                      _logger.write(this.toString(), Logger.WARNING, "Alerter.IRC.reconnectDelay value unavailable using default of " + delayTime + " seconds");
282                  }
# Line 236 | Line 295 | public class IRC__Alerter implements PluginAlerter {
295           */
296          public void sendMsg(String msg) {
297              _socketOut.println("PRIVMSG "+_channel+" :"+msg);
298 +            // wait a second before returning...
299 +            // this ensures messages can't be sent too fast
300 +            try {Thread.sleep(1000);} catch (InterruptedException e) {}
301          }
302          
303          /**
# Line 246 | Line 308 | public class IRC__Alerter implements PluginAlerter {
308           */
309          public void sendPrivMsg(String user, String msg) {
310              _socketOut.println("PRIVMSG "+user+" :"+msg);
311 +            // wait a second before returning...
312 +            // this ensures messages can't be sent too fast
313 +            try {Thread.sleep(1000);} catch (InterruptedException e) {}
314          }
315          
316          /**
# Line 256 | Line 321 | public class IRC__Alerter implements PluginAlerter {
321          public void sendAction(String msg) {
322              char esc = 001;
323              sendMsg(esc+"ACTION "+msg+esc);
324 +            // wait a second before returning...
325 +            // this ensures messages can't be sent too fast
326 +            try {Thread.sleep(1000);} catch (InterruptedException e) {}
327          }
328          
329          /**
# Line 265 | Line 333 | public class IRC__Alerter implements PluginAlerter {
333           */
334          public void sendNotice(String msg) {
335              _socketOut.println("NOTICE "+_channel+" :"+msg);
336 +            // wait a second before returning...
337 +            // this ensures messages can't be sent too fast
338 +            try {Thread.sleep(1000);} catch (InterruptedException e) {}
339          }
340          
341          /**
# Line 275 | Line 346 | public class IRC__Alerter implements PluginAlerter {
346          public void connect() throws IOException {
347              ConfigurationProxy cp = ConfigurationProxy.getInstance();
348              // setup the socket, reader and writer
349 <            String server = cp.getProperty(_name, "Alerter.IRC.IRCServer");
350 <            int port = Integer.parseInt(cp.getProperty(_name, "Alerter.IRC.IRCPort"));
349 >            String server;
350 >            int port;
351 >            try {
352 >                server = cp.getProperty(_name, "Alerter.IRC.IRCServer");
353 >                port = Integer.parseInt(cp.getProperty(_name, "Alerter.IRC.IRCPort"));
354 >            } catch (PropertyNotFoundException e) {
355 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
356 >                throw new IOException("Can't get irc server details due to configuration error");
357 >            } catch (NumberFormatException e) {
358 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
359 >                throw new IOException("Can't get irc server details due to malformed configuration");
360 >            }
361              _socket = new Socket(server, port);
362              _socketIn = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
363              _socketOut = new PrintWriter(_socket.getOutputStream(), true);
364              //_socketOut.println("PASS");
365              // send USER details
366 <            String user = cp.getProperty(_name, "Alerter.IRC.user");
367 <            String comment = cp.getProperty(_name, "Alerter.IRC.comment");
366 >            String user, comment;
367 >            try {
368 >                user = cp.getProperty(_name, "Alerter.IRC.user");
369 >                comment = cp.getProperty(_name, "Alerter.IRC.comment");
370 >            } catch (PropertyNotFoundException e) {
371 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
372 >                throw new IOException("Can't get user details due to configuration error");
373 >            }
374              _socketOut.println("USER "+user+" 8 * :"+comment);
375              // attempt to get a nick
376 <            String nickList = cp.getProperty(_name, "Alerter.IRC.nickList");
376 >            String nickList;
377 >            try {
378 >                nickList = cp.getProperty(_name, "Alerter.IRC.nickList");
379 >            } catch (PropertyNotFoundException e) {
380 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
381 >                throw new IOException("Can't get nickname due to configuration error");
382 >            }
383              StringTokenizer st = new StringTokenizer(nickList, ";");
384              boolean ok = false;
385              // try until we exhaust our list
# Line 318 | Line 411 | public class IRC__Alerter implements PluginAlerter {
411                  throw new IOException("All nicknames in use");
412              }
413              // join the channel
414 <            _channel = cp.getProperty(_name, "Alerter.IRC.channel");
414 >            try {
415 >                _channel = cp.getProperty(_name, "Alerter.IRC.channel");
416 >            } catch (PropertyNotFoundException e) {
417 >                _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
418 >                throw new IOException("Can't get channel name due to configuration error");
419 >            }
420              _socketOut.println("JOIN "+_channel);
421              // allow alerts
422              _active = true;
# Line 369 | Line 467 | public class IRC__Alerter implements PluginAlerter {
467                  _socketOut.println("PONG" + line.substring(4));
468              }
469              // see if it's for us
470 <            else if(getMsg(line).startsWith(_nickname)) {
470 >            else if(getMsg(line).startsWith(_nickname+",") || getMsg(line).startsWith(_nickname+":") || getMsg(line).startsWith(_nickname+" ")) {
471 >                // setup some String's
472 >                String stopCommand, startCommand, timeSinceLastAlertCommand, lastAlertCommand, joinCommand;
473 >                String nickChangeCommand, versionCommand, helpCommand, statCommand, uptimeCommand;
474 >                // get the command set
475 >                try {
476 >                    stopCommand = cp.getProperty(_name, "Alerter.IRC.stopCommand");
477 >                    startCommand = cp.getProperty(_name, "Alerter.IRC.startCommand");
478 >                    timeSinceLastAlertCommand = cp.getProperty(_name, "Alerter.IRC.timeSinceLastAlertCommand");
479 >                    lastAlertCommand = cp.getProperty(_name, "Alerter.IRC.lastAlertCommand");
480 >                    joinCommand = cp.getProperty(_name, "Alerter.IRC.joinCommand");
481 >                    nickChangeCommand = cp.getProperty(_name, "Alerter.IRC.nickChangeCommand");
482 >                    versionCommand = cp.getProperty(_name, "Alerter.IRC.versionCommand");
483 >                    helpCommand = cp.getProperty(_name, "Alerter.IRC.helpCommand");
484 >                    statCommand = cp.getProperty(_name, "Alerter.IRC.statCommand");
485 >                    uptimeCommand = cp.getProperty(_name, "Alerter.IRC.uptimeCommand");
486 >                } catch (PropertyNotFoundException e) {
487 >                    _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
488 >                    // lets bail from handling this line...
489 >                    // ...it's gonna be hard without a command set!
490 >                    return;
491 >                }
492 >                
493                  // we have a message for us
494                  String message = getMsg(line).substring(_nickname.length());
495 <                if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.stopCommand"))!=-1) {
495 >                if(message.indexOf(stopCommand)!=-1) {
496                      _active = false;
497                      sendMsg(getMsgSender(line)+", alerts have been stopped");
498                  }
499 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.startCommand"))!=-1) {
499 >                else if(message.indexOf(startCommand)!=-1) {
500                      _active = true;
501                      sendMsg(getMsgSender(line)+", alerts have been activated");
502                  }
503 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.lastAlertCommand"))!=-1) {
504 <                    sendMsg(getMsgSender(line)+", last alert was: "+_lastAlert);
503 >                // this needs to go here if it contains the same words as the lastAlertCommand
504 >                else if(message.indexOf(timeSinceLastAlertCommand)!=-1) {
505 >                    if(_lastAlertTime != -1) {
506 >                        long uptime = (System.currentTimeMillis() - _lastAlertTime) / 1000;
507 >                        String uptimeText = DateUtils.formatTime(uptime, "%DAYS% days, %HOURS% hours, %MINS% mins, and %SECS% secs");
508 >                        sendMsg(getMsgSender(line)+", I last sent an alert "+uptimeText+ " ago");
509 >                    }
510 >                    else {
511 >                        sendMsg(getMsgSender(line)+", I've never sent an alert!");
512 >                    }
513                  }
514 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.joinCommand"))!=-1) {
515 <                    String joinCmd = cp.getProperty(_name, "Alerter.IRC.joinCommand");
514 >                else if(message.indexOf(lastAlertCommand)!=-1) {
515 >                    if(_lastAlertTime != -1) {
516 >                        String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.UK).format(new Date(_lastAlertTime));
517 >                        sendMsg(getMsgSender(line)+", last alert was at "+date+"; "+_lastAlert);
518 >                    }
519 >                    else {
520 >                        sendMsg(getMsgSender(line)+", I've never sent an alert!");
521 >                    }
522 >                    
523 >                }
524 >                else if(message.indexOf(joinCommand)!=-1) {
525 >                    String joinCmd = joinCommand;
526                      String newChan = message.substring(message.indexOf(joinCmd) + joinCmd.length() + 1);
527                      int endOfChan = newChan.indexOf(" ");
528                      if(endOfChan == -1) {
# Line 396 | Line 534 | public class IRC__Alerter implements PluginAlerter {
534                      _socketOut.println("JOIN "+newChan);
535                      _channel = newChan;
536                  }
537 <                else if(message.indexOf(cp.getProperty(_name, "Alerter.IRC.helpCommand"))!=-1) {
538 <                    sendPrivMsg(getMsgSender(line), "I am the i-scream alerting bot revision "+REVISION.substring(11, REVISION.length() -2));
537 >                else if(message.indexOf(nickChangeCommand)!=-1) {
538 >                    String nickChangeCmd = nickChangeCommand;
539 >                    String newNick = message.substring(message.indexOf(nickChangeCmd) + nickChangeCmd.length() + 1);
540 >                    int endOfNick = newNick.indexOf(" ");
541 >                    if(endOfNick == -1) {
542 >                        endOfNick = newNick.length();
543 >                    }
544 >                    newNick = newNick.substring(0, endOfNick);
545 >                    sendMsg(getMsgSender(line)+", okay, changing my nickname to "+newNick);
546 >                    _socketOut.println("NICK "+newNick);
547 >                    _nickname = newNick;
548 >                }
549 >                else if(message.indexOf(versionCommand)!=-1) {
550 >                    sendMsg(getMsgSender(line)+", I am version "+REVISION.substring(11, REVISION.length() -2)+" of the i-scream alerting bot");
551 >                }
552 >                else if(message.indexOf(helpCommand)!=-1) {
553 >                    sendPrivMsg(getMsgSender(line), "Hello, I am the i-scream alerting bot version "+REVISION.substring(11, REVISION.length() -2));
554                      sendPrivMsg(getMsgSender(line), "I understand the following commands;");
555 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.stopCommand"));
556 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.startCommand"));
557 <                    sendPrivMsg(getMsgSender(line), cp.getProperty(_name, "Alerter.IRC.lastAlertCommand"));
555 >                    sendPrivMsg(getMsgSender(line), stopCommand);
556 >                    sendPrivMsg(getMsgSender(line), startCommand);
557 >                    sendPrivMsg(getMsgSender(line), lastAlertCommand);
558 >                    sendPrivMsg(getMsgSender(line), joinCommand);
559 >                    sendPrivMsg(getMsgSender(line), nickChangeCommand);
560 >                    sendPrivMsg(getMsgSender(line), statCommand);
561 >                    sendPrivMsg(getMsgSender(line), uptimeCommand);
562 >                    sendPrivMsg(getMsgSender(line), timeSinceLastAlertCommand);
563 >                    sendPrivMsg(getMsgSender(line), helpCommand);
564                  }
565 +                else if(message.indexOf(statCommand)!=-1) {
566 +                    sendMsg(getMsgSender(line)+", I have sent a total of "+_alertCount+" alerts, and ignored a total of "+_ignoredCount+"!");
567 +                }
568 +                else if(message.indexOf(uptimeCommand)!=-1) {
569 +                    long uptime = (System.currentTimeMillis() - _startTime) / 1000;
570 +                    String uptimeText = DateUtils.formatTime(uptime, "%DAYS% days, %HOURS% hours, %MINS% mins, and %SECS% secs");
571 +                    sendMsg(getMsgSender(line)+", I have been running for "+uptimeText);
572 +                }
573 +                else if(message.indexOf("ping")!=-1) {
574 +                    sendMsg("pong");
575 +                }
576                  else if(message.indexOf("do a jibble dance")!=-1) {
577                      // little joke :)
578                      sendAction("jives to the funky beat shouting \"ii--screeeaaammm\"");
579                  }
580                  else {
581 <                    sendMsg(getMsgSender(line)+", "+cp.getProperty(_name, "Alerter.IRC.rejectMessage"));
581 >                    String rejectMessage = NOT_CONFIGURED;
582 >                    try {
583 >                        rejectMessage = cp.getProperty(_name, "Alerter.IRC.rejectMessage");
584 >                    } catch(PropertyNotFoundException e) {
585 >                        _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
586 >                    }
587 >                    sendMsg(getMsgSender(line)+", "+rejectMessage);
588                  }
589              }
590              else if(line.indexOf(_nickname)!=-1 && line.indexOf(_channel)!=-1 && line.indexOf("KICK")!=-1) {
591                  sendPrivMsg(getMsgSender(line), "That wasn't a nice thing to do...");
592 <                _channel = cp.getProperty(_name, "Alerter.IRC.channel");
592 >                try {
593 >                    _channel = cp.getProperty(_name, "Alerter.IRC.channel");
594 >                } catch(PropertyNotFoundException e) {
595 >                    _logger.write(this.toString(), Logger.ERROR, "Configuration error: "+e);
596 >                }
597                  _socketOut.println("JOIN "+_channel);
598              }
599          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines