[Cherbot-commit] SF.net SVN: cherbot: [2] trunk
Status: Alpha
Brought to you by:
christianhujer
|
From: <chr...@us...> - 2006-10-27 08:42:01
|
Revision: 2
http://svn.sourceforge.net/cherbot/?rev=2&view=rev
Author: christianhujer
Date: 2006-10-27 01:40:41 -0700 (Fri, 27 Oct 2006)
Log Message:
-----------
Added original version without network code.
Added Paths:
-----------
trunk/build.number
trunk/build.xml
trunk/src/
trunk/src/cherbot/
trunk/src/cherbot/BlackListManager.java
trunk/src/cherbot/CherBot.java
trunk/src/cherbot/CherBotException.java
trunk/src/cherbot/CherBotLogger.java
trunk/src/cherbot/CherBotPermission.java
trunk/src/cherbot/CherBotSecurityManager.java
trunk/src/cherbot/CollectionsManager.java
trunk/src/cherbot/CommType.java
trunk/src/cherbot/Crime.java
trunk/src/cherbot/CrimeManager.java
trunk/src/cherbot/CronManager.java
trunk/src/cherbot/DeathsManager.java
trunk/src/cherbot/DummyManagerProxy.java
trunk/src/cherbot/EmotesManager.java
trunk/src/cherbot/ExampleTestCase.java
trunk/src/cherbot/ExampleTester.java
trunk/src/cherbot/GreetingsManager.java
trunk/src/cherbot/GroupManager.java
trunk/src/cherbot/LamentsManager.java
trunk/src/cherbot/MailManager.java
trunk/src/cherbot/Manager.java
trunk/src/cherbot/ManagerDocumenter.java
trunk/src/cherbot/NoSuchPlayerException.java
trunk/src/cherbot/NoobManager.java
trunk/src/cherbot/PlayerManager.java
trunk/src/cherbot/PollManager.java
trunk/src/cherbot/RodBabyManager.java
trunk/src/cherbot/RodBabyWannabeManager.java
trunk/src/cherbot/SalesManager.java
trunk/src/cherbot/SmutException.java
trunk/src/cherbot/SmutManager.java
trunk/src/cherbot/TestManager.java
trunk/src/cherbot/TimeManager.java
trunk/src/doc/
trunk/src/doc/commands.xslt
trunk/src/doc/start.xhtml
trunk/src/doc/style.css
trunk/src/doc/transform.xslt
trunk/src/doc/xhtml2html.xslt
Added: trunk/build.number
===================================================================
--- trunk/build.number (rev 0)
+++ trunk/build.number 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,3 @@
+#Build Number for ANT. Do not edit!
+#Wed Oct 26 22:02:15 CEST 2005
+build.number=1638
Property changes on: trunk/build.number
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:eol-style
+ LF
Added: trunk/build.xml
===================================================================
--- trunk/build.xml (rev 0)
+++ trunk/build.xml 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,279 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- $Header: /home/rpgroot/CherBot/build.xml,v 1.4 2005/11/09 20:30:00 chris Exp $ -->
+<!DOCTYPE project [
+ <!ENTITY w3ccatalog SYSTEM "/usr/local/share/dtds/w3c/w3c.catalog">
+]>
+<project default="createJar">
+ &w3ccatalog;
+
+ <xmlcatalog id="xmlcatalog">
+ <!--xmlcatalog refid="itcqiscatalog"/-->
+ <xmlcatalog refid="w3ccatalog"/>
+ </xmlcatalog>
+
+ <property file="ftp.properties" />
+ <property file="project.properties" />
+ <taskdef name="megaxslt" classname="com.hujer.ant.tasks.megaxslt.MegaXsltTask" />
+ <description>
+ CherBot
+ </description>
+
+ &w3ccatalog;
+
+ <target
+ name = "full"
+ description = "Build the whole thing"
+ depends = "init, compile"
+ />
+
+ <target
+ name = "init"
+ description = "Prepare sandbox for work"
+ >
+ <buildnumber/>
+ <tstamp>
+ <format property="build.time" pattern="yyyyMMddHHmmss" />
+ </tstamp>
+ <!--exec executable="ctags">
+ <arg line="-R src" />
+ </exec-->
+ </target>
+
+ <target
+ name = "compile"
+ description = "Compile sandbox"
+ depends = "init"
+ >
+ <mkdir dir="classes" />
+ <javac
+ source="1.5"
+ srcdir="src"
+ destdir="classes"
+ debug="yes"
+ encoding="utf-8"
+ >
+ <compilerarg line="-Xlint:all"/>
+ <compilerarg line="-Xmaxerrs 400"/>
+ <compilerarg line="-Xmaxwarns 4000"/>
+ </javac>
+ </target>
+
+ <target
+ name = "clean"
+ description = "Cleanup sandbox all"
+ depends = "cleanCode, cleanDoc"
+ >
+ <parallel>
+ <delete dir="classes" />
+ <delete dir="doc/api" />
+ </parallel>
+ </target>
+
+ <target
+ name = "cleanCode"
+ description = "Cleanup sandbox generated code"
+ >
+ <parallel>
+ <delete dir="classes" />
+ </parallel>
+ </target>
+
+ <target
+ name = "cleanDoc"
+ description = "Cleanup sandbox generated doc"
+ >
+ <parallel>
+ <delete dir="doc/api" />
+ </parallel>
+ </target>
+
+ <target
+ name = "doc"
+ description = "Create API documentation"
+ >
+ <mkdir dir="doc/api/html" />
+ <javadoc
+ destdir = "doc/api/html"
+ locale = "de_DE"
+ encoding = "utf-8"
+ version = "yes"
+ author = "yes"
+ use = "yes"
+ splitindex = "yes"
+ windowtitle = "CherBot — API Documentation"
+ doctitle = "CherBot<br />API Documentation"
+ header = "CherBot<br />API Documentation"
+ footer = "CherBot<br />API Documentation"
+ bottom = "<div style="text-align:center;">© 2005 Christian Hujer. All rights reserved.</div>"
+ serialwarn = "yes"
+ charset = "utf-8"
+ docencoding = "utf-8"
+ source = "1.5"
+ linksource = "yes"
+ private = "yes"
+ >
+ <!--
+ stylesheetfile = "src/stylesheet.css"
+ overview = "src/overview.html"
+ -->
+ <sourcepath path="src" />
+ <sourcepath path="/dist/opt/sun/j2sdk/se/latest/src" />
+ <packageset
+ dir="src"
+ defaultexcludes="yes"
+ >
+ <include name="**" />
+ </packageset>
+ <tag
+ name="todo"
+ description="Todo:"
+ />
+ <tag
+ name="fixme"
+ description="Fixme:"
+ />
+ <link href="/dist/opt/sun/j2sdk/se/latest/docs/api" />
+ </javadoc>
+ </target>
+
+ <target
+ name = "createJar"
+ description = "creates a jar archive containing the CherBot"
+ depends = "compile"
+ >
+ <copy todir="classes">
+ <fileset dir="src">
+ <include name="icons/**/*.gif"/>
+ </fileset>
+ </copy>
+ <copy todir="classes">
+ <fileset dir="src">
+ <include name="**/*.properties"/>
+ </fileset>
+ </copy>
+ <jar destfile="CherBot.jar">
+ <manifest>
+ <attribute name="Main-Class" value="cherbot.CherBot" />
+ </manifest>
+ <fileset dir="classes">
+ <!--exclude name="**/Test.class" /-->
+ </fileset>
+ </jar>
+ </target>
+
+ <target
+ name = "test"
+ description = "runs tests"
+ depends = "createJar"
+ >
+ <mkdir dir="tests" />
+ <junit
+ fork = "no"
+ printsummary="yes"
+ haltonfailure="yes"
+ >
+ <formatter type="plain" usefile="no"/>
+ <classpath>
+ <pathelement path="CherBot.jar" />
+ </classpath>
+ <test
+ name="cherbot.ExampleTester"
+ todir="tests"
+ >
+ <formatter type="plain"/>
+ <formatter type="xml"/>
+ </test>
+ </junit>
+ </target>
+
+ <target
+ name = "publish"
+ description = "publishes Cherbot documentation on the net"
+ depends = "createJar"
+ >
+ <java
+ fork="true"
+ classpath="classes"
+ classname="cherbot.ManagerDocumenter"
+ >
+ <arg value="src/doc/commands.xml" />
+ </java>
+ <xslt in="src/doc/commands.xml" out="src/doc/commands.xhtml" style="src/doc/commands.xslt" />
+ <mkdir dir="doc"/>
+ <copy todir="doc">
+ <fileset dir="src/doc">
+ <include name="**/*.css" />
+ </fileset>
+ </copy>
+ <megaxslt srcdir="src/doc" destdir="doc" includes="**/*.xhtml" validateSource="yes" validateDest="yes">
+ <xmlcatalog refid="xmlcatalog" />
+ <transformation stylesheet="src/doc/transform.xslt" />
+ <!--transformation stylesheet="libs/common/xslt/cleanupXhtml11.xslt" /-->
+ </megaxslt>
+ <megaxslt srcdir="doc" destdir="doc" includes="**/*.xhtml" ending="html" validateSource="yes" validateDest="no">
+ <xmlcatalog refid="xmlcatalog" />
+ <transformation stylesheet="src/doc/xhtml2html.xslt" />
+ <!--transformation stylesheet="libs/common/xslt/cleanupXhtml11.xslt" /-->
+ </megaxslt>
+ <ftp
+ server="${ftp.server}"
+ userid="${ftp.userid}"
+ password="${ftp.password}"
+ remotedir="daimonin"
+ depends="yes"
+ passive="yes"
+ ignoreNoncriticalErrors="yes"
+ >
+ <fileset dir="doc" />
+ </ftp>
+ <!--exec executable="bash">
+ <arg value="-c" />
+ <arg value="LC_ALL=C tar -cvz -C doc -f htdocs.tgz "`test -e ts_upload && (echo -n '-N ' ; cat ts_upload 2>/dev/null)`" ."/>
+ </exec-->
+ <!--ftp
+ server="${ftp.server}"
+ userid="${ftp.userid}"
+ password="${ftp.password}"
+ depends="no"
+ passive="yes"
+ ignoreNoncriticalErrors="yes"
+ -->
+ <!--remotedir="${ftp.remotedir}"-->
+ <!--fileset dir=".">
+ <include name="htdocs.tgz" />
+ </fileset>
+ </ftp>
+ <exec executable="bash">
+ <arg value="-c" />
+ <arg value="LC_ALL=C date >ts_upload" />
+ </exec-->
+ <!--telnet userid="${ftp.userid}" password="${ftp.password}" server="${ftp.server}"-->
+ <!--telnet server="${ftp.server}">
+ <read string="Login: "/>
+ <write string="${ftp.userid}" />
+ <read string="Password: "/>
+ <write string="${ftp.password}"/>
+ <read string="${ftp.server}> " />
+ <write string="cd ${ftp.remotedir}"/>
+ <read string="${ftp.server}> " />
+ <write>tar xzvf ../htdocs.tgz</write>
+ <read string="${ftp.server}> " />
+ </telnet-->
+ </target>
+
+</project>
+<!--
+ - $Log: build.xml,v $
+ - Revision 1.4 2005/11/09 20:30:00 chris
+ - Changed player access to allow players with - in their names. Now all non-whitespace chars are allowed for players.
+ -
+ - Revision 1.3 2005/10/20 06:17:27 chris
+ - *** empty log message ***
+ -
+ - Revision 1.2 2005/03/01 10:09:37 chris
+ - Enabled API documentation.
+ -
+ - Revision 1.1 2005/03/01 09:14:02 chris
+ - First import to version control.
+ -
+ -->
Property changes on: trunk/build.xml
___________________________________________________________________
Name: svn:mime-type
+ text/xml
Name: svn:eol-style
+ LF
Added: trunk/src/cherbot/BlackListManager.java
===================================================================
--- trunk/src/cherbot/BlackListManager.java (rev 0)
+++ trunk/src/cherbot/BlackListManager.java 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,171 @@
+/* $Header: /home/rpgroot/CherBot/src/cherbot/BlackListManager.java,v 1.13 2005/11/09 20:30:00 chris Exp $
+ *
+ * © 2005 Christian Hujer. All rights reserved.
+ * License: GNU General Public License. See file COPYING in the root directory of this project.
+ *
+ * Log: see end of file
+ */
+
+package cherbot;
+
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+/** Manages a black list of users that may not use Cherbot.
+ * @author $Author: chris $
+ * @version $Id: BlackListManager.java,v 1.13 2005/11/09 20:30:00 chris Exp $
+ */
+@Manager.Description("Blacklist of players that are denied to use Cherbot.")
+@Manager.Features({"Blacklist players that are denied to use Cherbot."})
+public class BlackListManager extends Manager {
+
+ /** Version information */
+ public static final String version = "$Revision: 1.13 $";
+
+ /** Permission to modify blacklist. */
+ private static final String PERM_BLACKLIST = "Blacklist";
+
+ /** The black list. */
+ private SortedSet<String> blacklist = new TreeSet<String>();
+
+ { // Commands
+ new Command("(?:$LIST ?(?:the )?blacklist(?:ed players)?|wh(?:o|ich players?) (?:is|are|r) (?:blacklisted|on (?:the )?blacklist))[.!?]?") {
+ @Description("Lists the blacklisted players.")
+ @Examples({"List blacklist", "Tell me the blacklisted players.", "Who is blacklisted?", "Which players are on the blacklist?"})
+ @Override public void performImpl() {
+ listBlacklist();
+ }
+ };
+ new Command("(?:put|add) $PLAYER (?:to|on) blacklist[.!]?") {
+ @Description("Puts a player on the blacklist.")
+ @Examples({"Put Lead on blacklist.", "Add Lead to blacklist."})
+ @Override public void performImpl() {
+ addBlacklist(player(1));
+ }
+ };
+ new Command("(?:remove) $PLAYER from blacklist[.!]?") {
+ @Description("Removes a player from the blacklist.")
+ @Examples({"Remove Lead from blacklist."})
+ @Override public void performImpl() {
+ removeBlacklist(player(1));
+ }
+ };
+ } // Commands
+
+ /** Create the BlackListManager.
+ * @param cherbot CherBot
+ */
+ public BlackListManager(final CherBot cherbot) {
+ super(cherbot, "blacklist");
+ }
+
+ /** List the blacklist. */
+ private void listBlacklist() {
+ if (blacklist.size() == 0) {
+ answer("Noone's on the blacklist yet.");
+ } else {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("The following players are blacklisted: ");
+ concat(sb, blacklist);
+ sb.append('.');
+ answer(sb.toString());
+ }
+ }
+
+ /** Puts a player to the blacklist.
+ * @param player Player to blacklist
+ */
+ private void addBlacklist(final String player) {
+ checkPermission(PERM_BLACKLIST);
+ if (blacklist.add(player)) {
+ answer("Added " + player + " to the blacklist.");
+ tell(player, getActor() + " has put you on the blacklist. You cannot use Cherbot anymore.");
+ } else {
+ answer(player + " already was on the blacklist.");
+ }
+ }
+
+ /** Removes a player from the blacklist.
+ * @param player Player to remove
+ */
+ private void removeBlacklist(final String player) {
+ checkPermission(PERM_BLACKLIST);
+ if (blacklist.remove(player)) {
+ answer("Removed " + player + " from the blacklist.");
+ tell(player, getActor() + " has removed you from the blacklist. You can use Cherbot again.");
+ } else {
+ answer(player + " wasn't blacklisted anyway.");
+ }
+ }
+
+ /** Checks wether a player is blacklisted.
+ * @param player Player to check
+ */
+ public boolean isBlacklisted(final String player) {
+ return blacklist.contains(player);
+ }
+
+ /** Checks wether the actor is blacklisted. */
+ public boolean isBlacklisted() {
+ return blacklist.contains(getActor());
+ }
+
+ /** {@inheritDoc} */
+ @Override public void help() {
+ answer("I have a blacklist. Players on the blacklist cannot use Cherbot.");
+ }
+
+ { // IO Modules
+ new CollectionIOModule("blacklist.txt", blacklist, false);
+ } // IO Modules
+
+} // class BlackListManager
+
+/*
+ * $Log: BlackListManager.java,v $
+ * Revision 1.13 2005/11/09 20:30:00 chris
+ * Changed player access to allow players with - in their names. Now all non-whitespace chars are allowed for players.
+ *
+ * Revision 1.12 2005/08/31 13:55:28 chris
+ * Improved code quality.
+ * Removed console control feature.
+ * Changed member count to reflect only real members.
+ *
+ * Revision 1.11 2005/08/29 15:45:39 chris
+ * Some minor improvements.
+ *
+ * Revision 1.10 2005/04/02 23:08:43 chris
+ * Reworked command pattern creation to allow variables.
+ * Reworked commands to use variables.
+ * Added alliances to groups.
+ * Added group membership listing to groups.
+ *
+ * Revision 1.9 2005/04/01 11:36:23 chris
+ * Removed unused boundaries from regexps.
+ *
+ * Revision 1.8 2005/04/01 11:20:33 chris
+ * Added Timemanager, made patterns case insensitive.
+ *
+ * Revision 1.7 2005/03/23 12:46:32 chris
+ * Improved regex handling.
+ *
+ * Revision 1.6 2005/03/18 16:53:56 chris
+ * Improved some regular expressions.
+ * Moved lots of I/O code from subclasses to Manager.java.
+ *
+ * Revision 1.5 2005/03/15 23:49:25 chris
+ * Fixed regular expressions with test results.
+ *
+ * Revision 1.4 2005/03/15 22:41:26 chris
+ * Improved regexes.
+ *
+ * Revision 1.3 2005/03/15 11:43:45 chris
+ * Added manager description.
+ *
+ * Revision 1.2 2005/03/15 01:55:43 chris
+ * Refactored matcher, fixed null vs. Blacklist bug.
+ *
+ * Revision 1.1 2005/03/14 16:55:00 chris
+ * Added.
+ *
+ */
Property changes on: trunk/src/cherbot/BlackListManager.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:eol-style
+ LF
Added: trunk/src/cherbot/CherBot.java
===================================================================
--- trunk/src/cherbot/CherBot.java (rev 0)
+++ trunk/src/cherbot/CherBot.java 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,749 @@
+/* $Header: /home/rpgroot/CherBot/src/cherbot/CherBot.java,v 1.31 2005/11/09 20:30:00 chris Exp $
+ *
+ * © 2005 Christian Hujer. All rights reserved.
+ * License: GNU General Public License. See file COPYING in the root directory of this project.
+ *
+ * Log: see end of file
+ */
+
+package cherbot;
+
+
+import java.io.BufferedReader;
+import java.io.EOFException;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.text.BreakIterator;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import cherbot.Manager.Command;
+
+/** A Daimonin bot.
+ * @todo split this class into four: A generic base class for robots, a class handling Daimonin-specific stuff, an interface for network
+ * implementations implemted by the latter, and this specific CherBot subclass.
+ * @todo perhaps add a graphical interface.
+ * @author $Author: chris $
+ * @version $Id: CherBot.java,v 1.31 2005/11/09 20:30:00 chris Exp $
+ */
+public class CherBot {
+
+ /** Lihes of code. */
+ private static final int LINES_OF_CODE = 11137;
+
+ /** Wether to stop.
+ * This variable initially is false.
+ * Telling the Bot to stop sets this variable to true, terminating the two thread loops for receiving packets and the console.
+ */
+ private boolean stop;
+
+ /** The user name this bot should use for connecting with the server. */
+ private String username;
+
+ /** The password this bot sohuld use for connecting with the server. */
+ private String password;
+
+ /** The SecurityManager.
+ * Provides access to security handling possibly used by every other manager.
+ * Thus needs to be available to all managers.
+ */
+ private CherBotSecurityManager securityManager;
+
+ /** The internal manager. */
+ private InternalManager internalManager;
+
+ /** The Blacklist manager. */
+ private BlackListManager blacklistManager;
+
+ /** The Player manager. */
+ private PlayerManager playerManager;
+
+ /** The Managers as a list for looping or similar.
+ * It's a List because the order in which the managers are added really matters.
+ * Managers might have regular expression overlapping, an input string could match the commands of more than just one manager.
+ * The managers are searched in their creation order.
+ * The basic association relation between the bot (1) and the managers (n) is a bidirectional composition.
+ */
+ private List<Manager> managers = new ArrayList<Manager>();
+
+ /** The Managers as map, for getting the Manager on a specific topic.
+ * Key: topic of Manager ({@link Manager#getTopic()}).
+ * Value: Manager
+ */
+ private Map<String,Manager> managerMap = new HashMap<String,Manager>();
+
+ /** The Managers with timers. */
+ private List<Manager> timers = new ArrayList<Manager>();
+
+ /** The Commands.
+ * The order is important, this must be a List.
+ */
+ private List<Command> commands = new ArrayList<Command>();
+
+ /** Main program.
+ * @param args command line arguments
+ * @throws IOException in case of I/O problems
+ */
+ public static void main(final String... args) throws IOException {
+ final CherBot bot = new CherBot();
+ bot.connect(args[0], args[1], args[2]);
+ bot.run();
+ }
+
+ /** Create the CherBot.
+ * This creates the managers.
+ * @todo put the list of managers that should be created in a file, read the file and use reflection to create the managers.
+ * This would allow users to configure what modules the bot should load without recompiling the bot.
+ */
+ public CherBot() {
+ // Add Managers
+ // The order is important, since commands (regexes) are searched in the order the managers are constructed.
+ // Also some managers require other managers to already exist
+ new SmutManager(this);
+ securityManager = new CherBotSecurityManager(this);
+ internalManager = new InternalManager(this);
+ blacklistManager = new BlackListManager(this);
+ playerManager = new PlayerManager(this);
+ new TimeManager(this);
+ new TestManager(this);
+ new GreetingsManager(this);
+ new LamentsManager(this);
+ new CollectionsManager(this);
+ //new CrimeManager(this);
+ new RodBabyManager(this);
+ new RodBabyWannabeManager(this);
+ new DeathsManager(this);
+ new PollManager(this);
+ new SalesManager(this);
+ new MailManager(this);
+ new EmotesManager(this);
+ new GroupManager(this);
+ new NoobManager(this);
+ }
+
+ /** Quit Cherbot. */
+ public void quit() {
+ System.exit(0);
+ }
+
+ /** Add a Manager.
+ * The constructor of Manager invokes this method.
+ * So do not call this method or a Manager would be added twice.
+ * @param manager Manager to add
+ */
+ public void addManager(final Manager manager) {
+ managers.add(manager);
+ if (manager.getTicksDelay() != 0) {
+ timers.add(manager);
+ }
+ managerMap.put(manager.getTopic(), manager);
+ }
+
+ /** Get a Manager for a certain topic.
+ * @param topic Topic to get Manager for
+ * @return Manager for <var>topic</var> or <code>null</code> if no manager for the specified topic is known
+ */
+ public Manager getManager(final String topic) {
+ return managerMap.get(topic);
+ }
+
+ /** Get all managers.
+ * The returned collection is immutable.
+ * @return all managers
+ */
+ public Collection<Manager> managers() {
+ return Collections.unmodifiableList(managers);
+ }
+
+ /** Get the SecurityManager.
+ * Don't rely on the SecurityManager instance being the same all the time for an instance of CherBot.
+ * The SecurityManager might change over the time.
+ * @return SecurityManager
+ */
+ public CherBotSecurityManager getSecurityManager() {
+ return securityManager;
+ }
+
+ /** Add a Command.
+ * The constructor of Manager.Command indirectly invokes this method by invoking Manager.addCommand.
+ * So do not call this method or a Command would be added twice.
+ * @param command Command to add
+ */
+ public void addCommand(final Command command) {
+ commands.add(command);
+ }
+
+ /** Get username used by the bot.
+ * @return username
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /** Connect to a server.
+ * @param username username
+ * @param password password
+ * @param server Server to connect to
+ * @throws IOException if the socket cannot be opened.
+ */
+ @SuppressWarnings({"SocketOpenedButNotSafelyClosed"})
+ public void connect(final String username, final String password, final String server) throws IOException {
+ this.username = username;
+ this.password = password;
+ socket = new Socket(server, 13327);
+ in = socket.getInputStream();
+ out = socket.getOutputStream();
+ receiveServerVersion();
+ sendClientVersion();
+ login();
+ try {
+ internalManager.load();
+ } catch (final Exception e) {
+ System.err.println(e);
+ }
+ //say("food");
+ }
+
+ /** Keep the bot running.
+ * @throws IOException in case of I/O problems
+ */
+ public void run() throws IOException {
+ try {
+ while (!stop) {
+ dispatch(receivePacket());
+ timer();
+ }
+ } finally {
+ try {
+ internalManager.save();
+ } catch (final Exception e) {
+ System.err.println(e);
+ }
+ try { in.close(); } catch (final IOException e) { /* ignore */ } finally { in = null; }
+ try { out.close(); } catch (final IOException e) { /* ignore */ } finally { out = null; }
+ try { socket.close(); } catch (final IOException e) { /* ignore */ } finally { socket = null; }
+ }
+ }
+
+ /** Answer.
+ * @param cs String to answer
+ */
+ public void answer(final CharSequence cs) {
+ tell(actor, cs.toString()); // TODO: Improve CharSequence handling
+ }
+
+ /** Shout.
+ * @param s String to shout
+ */
+ public void shout(final String s) {
+ final StringBuilder sb = new StringBuilder();
+ for (final String line : lineSplit(s)) {
+ sb.setLength(0);
+ sb.append("/shout ");
+ sb.append(line);
+ }
+ }
+
+ /** Tell
+ * @param p Player name
+ * @param s String to tell
+ */
+ public void tell(final String p, final String s) {
+ if (s.length() == 0) {
+ return; // nothing to tell.
+ }
+ if (p == null) {
+ println(s);
+ } else {
+ // either lineSplit or ncom has a bug. Probably lineSplit.
+ final StringBuilder sb = new StringBuilder();
+ for (final String line : lineSplit(s)) {
+ sb.setLength(0);
+ }
+ }
+ }
+
+ /** Reply
+ * @param s String to tell
+ */
+ public void reply(final String s) throws IOException {
+ final StringBuilder sb = new StringBuilder();
+ for (final String line : lineSplit(s)) {
+ sb.setLength(0);
+ }
+ }
+
+ /** Say.
+ * @param s String to say
+ */
+ public void say(final String s) {
+ final StringBuilder sb = new StringBuilder();
+ for (String line : lineSplit(s)) {
+ sb.setLength(0);
+ }
+ }
+
+ /** Split a String into substrings.
+ * @param s String to split
+ * @return substrings
+ */
+ @SuppressWarnings({"AssignmentToForLoopParameter"})
+ private static Iterable<String> lineSplit(final String s) {
+ final BreakIterator it = BreakIterator.getLineInstance();
+ it.setText(s);
+ final List<String> ret = new ArrayList<String>();
+ final int width = 230;
+ for (int end = it.last(), split = it.first(), current = 0; current <= end;) {
+ current = it.next();
+ if (current-split > width) {
+ current = it.previous();
+ if (current == split) { current = it.next(); }
+ ret.add(s.substring(split, current));
+ split = current;
+ } else if (current == end) {
+ ret.add(s.substring(split, current));
+ current++;
+ }
+ }
+ return ret;
+ }
+
+ /** Pattern for game entering. */
+ private static final Pattern enter = Pattern.compile("(\\S+) has entered the game.");
+
+ /** Pattern for game kill. */
+ private static final Pattern kill = Pattern.compile("(.+) killed (\\S+)( with (.*))?.");
+
+ /** Dispatch a packet of data.
+ * @param data packet to dispatch
+ * @throws IOException in case of I/O problems
+ */
+ private void dispatch(final byte[] data) throws IOException {
+ } // dispatch
+
+ private static final String[] colors = {
+ "\000\033[0m\001", // default / white
+ "\000\033[33m\001", // orange
+ "\000\033[96m\001", // light blue / navy
+ "\000\033[91m\001", // red
+ "\000\033[92m\001", // green
+ "\000\033[94m\001", // blue
+ "\000\033[37m\001", // grey
+ "\000\033[93m\001", // yellow
+ "\000\033[36m\001", // dark navy
+ "\000\033[0m\001", // don't know
+ "\000\033[93m\001", // yellow again
+ };
+ /** Switch output to a certain color.
+ * @param n color to switch to
+ */
+ private static void switchColor(final int n) {
+ try {
+ System.out.print(colors[n]);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ System.err.println("Unknown color number: " + n);
+ }
+ }
+
+ /** Handle communication.
+ * @param ct Communication Type
+ * @param who speaker
+ * @param msg message
+ * @throws IOException in case of I/O problems
+ * @todo this needs to be improved so /shout can also be used to communicate with Cherbot and Cherbot could respond on shout
+ */
+ private void communicate(final CommType ct, final String who, final String msg) throws IOException {
+ playerManager.see(who);
+ if (username.equals(who)) { return; } // avoid loop dispatch!
+ if (ct == CommType.shout) {
+ final Pattern p = Pattern.compile(username + "(?:(?:,|:)? *)(.*)");
+ final Matcher matcher = p.matcher(msg);
+ if (matcher.matches()) {
+ final String cmd = matcher.group(1);
+ dispatch(who, cmd);
+ }
+ } else {
+ dispatch(who, msg);
+ }
+ }
+
+ /** Who executes the current / executed the last command. */
+ private String actor;
+
+ /** Get the actor (player that executes current / executed the last command).
+ * @return actor
+ */
+ public String getActor() {
+ return actor;
+ }
+
+ /** Dispatch a message, try to execute it's command.
+ * @param who speaker
+ * @param rawCmd Command to perform
+ * @todo this needs to be improved so /shout can also be used to communicate with Cherbot and Cherbot could respond on shout
+ */
+ private synchronized void dispatch(final String who, final String rawCmd) {
+ final String cookedCmd = rawCmd.replaceAll("\\s+", " ").trim();
+ actor = who;
+ if (actor != null && blacklistManager.isBlacklisted()) {
+ answer("You are denied.");
+ return;
+ }
+ try {
+ for (final Command command : commands) {
+ if (command.perform(cookedCmd)) {
+ break;
+ }
+ }
+ } catch (CherBotException e) {
+ answer("I can't: " + e.getMessage());
+ } catch (SecurityException e) {
+ answer("I don't want to: " + e.getMessage());
+ }
+ }
+
+ /** Handle enter.
+ * @param who person that entered.
+ */
+ private void enter(final String who) {
+ for (final Manager manager : managers) {
+ manager.entered(who);
+ }
+ }
+
+ /** Handle kill.
+ * @param killer Killer
+ * @param who person that was killed
+ * @param with with what
+ * @throws IOException in case of I/O problems
+ */
+ private void kill(final String killer, final String who, final String with) throws IOException {
+ if (username.equals(who)) { return; } // avoid lamenting myself
+ for (Manager manager : managers) {
+ manager.died(who, killer, with);
+ }
+ }
+
+ /** Write a line to stdout.
+ * @param s line to write
+ */
+ private static void println(final String s) {
+ System.out.println(s);
+ }
+
+ /** The internal manager.
+ * @author $Author: chris $
+ * @version $Revision: 1.31 $
+ */
+ @Manager.Description("Manages the other modules and gives some general information about the bot.")
+ @Manager.Features({
+ "Load and save persistent data.",
+ "List commands.",
+ "Tell what's new."
+ })
+ private class InternalManager extends Manager {
+ private static final String PERM_SAVE = "Internal.Save";
+ private static final String PERM_LOAD = "Internal.Load";
+ private static final String PERM_QUIT = "Internal.Quit";
+
+ /* Commands. */
+ {
+ new Command("(?:in )?wh(?:ich|at) (?:programming[- ])?language (?:(?:were|are) $YOU|have you been) (?:written|programmed|coded)(?: in)?[?]?") {
+ @Description("You can ask in which language cherbot is written in.")
+ @Examples({"What language are you coded in?", "In which programming language have you been written?"})
+ @Override public void performImpl() {
+ answer("I'm written in " + LINES_OF_CODE + " of Java code.");
+ }
+ };
+ new Command("save[.!]?") {
+ @Description("Saves all module data to persistent storage.")
+ @Examples({"Save!"})
+ @Override public void performImpl() {
+ checkPermission(new CherBotPermission(PERM_SAVE));
+ try {
+ save();
+ answer("Saved all modules.");
+ } catch (Exception e) {
+ answer("Save failed: " + e);
+ }
+ }
+ };
+ new Command("save (\\w+)[.!]") {
+ @Description("Saves a specific module's data to persistent storage.")
+ @Examples({"Save collections!", "Save sales!"})
+ @Override public void performImpl() {
+ final String module = matcher.group(1);
+ checkPermission(new CherBotPermission(PERM_SAVE + '.' + module));
+ try {
+ managerMap.get(module).save();
+ answer("Saved module " + module + '.');
+ } catch (NullPointerException e) {
+ answer("No such module.");
+ } catch (Exception e) {
+ answer("Error while saving module " + module + ": " + e);
+ }
+ }
+ };
+ new Command("load[.!]?") {
+ @Description("Load all module data from persistent storage.")
+ @Examples({"Load!"})
+ @Override public void performImpl() {
+ checkPermission(new CherBotPermission(PERM_LOAD));
+ try {
+ load();
+ answer("Loaded.");
+ } catch (Exception e) {
+ answer("Save failed: " + e);
+ }
+ }
+ };
+ new Command("load (\\w+)[.!]?") {
+ @Description("Load a specific module's data from persistent storage.")
+ @Examples({"Load collections!", "Load sales!"})
+ @Override public void performImpl() {
+ final String module = matcher.group(1);
+ checkPermission(new CherBotPermission(PERM_LOAD + '.' + module));
+ try {
+ managerMap.get(module).load();
+ answer("Loaded module " + module + '.');
+ } catch (NullPointerException e) {
+ answer("No such module.");
+ } catch (Exception e) {
+ answer("Error while loading module " + module + ": " + e);
+ }
+ }
+ };
+ new Command("help[.!]?") {
+ @Description("Displays some general help.")
+ @Examples({"Help!"})
+ @Override public void performImpl() {
+ answer("More info: about, info, help commands, help topics, help usage, help testing");
+ }
+ };
+ new Command("(about|tell me about $YOU)[.!]?") {
+ @Description("Displays some information about Cherbot.")
+ @Examples({"About!", "Tell me about you!"})
+ @Override public void performImpl() {
+ answer("Hello. I am Cherbot, Cheristheus' stupid bot, written in 12 hours, approx. " + LINES_OF_CODE + " lines of code.\nI understand several commands, but most of them are privileged. If you talk to me, use short yet complete correct English sentences. I usually won't respond to single words thrown at me. If I say something like \"I don't want to.\", that means you used the correct command but you don't have enough permissions.\nAsk me about 'help topics' to find out what I can.");
+ }
+ };
+ new Command("(list|show|help) modules[.!]?") {
+ @Description("Lists which modules Cherbot has loaded.")
+ @Examples({"List modules!", "Show modules!" })
+ @Override public void performImpl() {
+ final StringBuilder mods = new StringBuilder();
+ for (Manager manager : managers) {
+ if (mods.length() > 0) { mods.append(", "); } else { mods.append("Loaded modules: "); }
+ mods.append(manager.getTopic());
+ }
+ mods
+ .append(". ")
+ .append(Integer.toString(managers.size()))
+ .append(" modules total. Use 'help <modulename>' to get information on a specific module.");
+ answer(mods.toString());
+ }
+ };
+ new Command("(list|show|help) commands[.!]?") {
+ @Description("Lists the commands. Won't really list the commands but show the modules, since the commands are quite a lot now.")
+ @Examples({"List commands!", "Show commands!"})
+ @Override public void performImpl() {
+ final StringBuilder sb = new StringBuilder();
+ for (Manager manager : managers) {
+ if (sb.length() == 0) { sb.append("Loaded modules: "); } else { sb.append(", "); }
+ sb.append(manager.getTopic());
+ }
+ sb.append(". To know the commands for a specific module, use 'help commands <modulename>', like 'help commands topics'.");
+ answer(sb.toString());
+ }
+ };
+ new Command("(list|show|help) commands? (of |from )?(the |module )?(\\w+)([- ](module|commands))?[.!]?") {
+ @Description("Lists all commands from the specified module.")
+ @Examples({"Show commands from module sales", "Show commands from the sales-module!"})
+ @Override public void performImpl() {
+ final String topic = matcher.group(4);
+ final StringBuilder sb = new StringBuilder();
+ for (Manager manager : managers) {
+ if (topic.equals(manager.getTopic())) {
+ sb.append("Commands for module ").append(topic).append('\n');
+ for (Command command : manager.commands()) {
+ sb.append(command.getPattern()).append('\n');
+ }
+ answer(sb.toString());
+ return;
+ }
+ }
+ answer("No such module: " + topic);
+ }
+ };
+ new Command("(list||show|help) (me )?all commands[.!]?") {
+ @Description("Lists all commands. Please don't use it.")
+ @Examples({"List all commands!", "Show me all commands!"})
+ @Override public void performImpl() {
+ answer("The commands might be quite a lot. If you really want me to do that, tell me 'Really list all commands.'.");
+ }
+ };
+ new Command("really (list|show|help) (me )?all commands[.!]?") {
+ @Description("Lists all commands. Please don't use it.")
+ @Examples({"Really list all commands!", "Really show me all commands!"})
+ @Override public void performImpl() {
+ final StringBuilder sb = new StringBuilder();
+ for (Manager manager : managers) {
+ sb.append(manager.getTopic()).append('\n').append(manager.getTopic().replaceAll(".", "-")).append('\n');
+ for (Command command : manager.commands()) {
+ sb.append(command.getPattern()).append('\n');
+ }
+ }
+ }
+ };
+ new Command("help (.*?)[.!]?") {
+ @Description("List the help on a specific module.")
+ @Examples({"Help collections!", "Help sales!"})
+ @Override public void performImpl() {
+ final String topic = matcher.group(1);
+ if (topic.equals("usage")) {
+ answer("Usage: tell me a command. You may also use shout or say but I will nearly always respond in tell. I don't want to bother other players. Use good, clear, correct, complete English sentences, that will work best. Tell me 'help commands' to find out what I understand.");
+ } else {
+ for (Manager manager : managers) {
+ if (topic.equalsIgnoreCase(manager.getTopic())) {
+ manager.help();
+ }
+ }
+ }
+ }
+ };
+ new Command("info[.!]?") {
+ @Description("Gives some general info about Cherbot.")
+ @Examples({"Info"})
+ @Override public void performImpl() {
+ final StringBuilder info = new StringBuilder();
+ info
+ .append("Version: some alpha.\n")
+ .append("Lines of code: approx. ")
+ .append(LINES_OF_CODE)
+ .append(".\n")
+ .append("Loaded modules: ")
+ .append(managers.size())
+ .append(".\n")
+ .append("Known commands: ")
+ .append(commands.size())
+ .append('.');
+ answer(info.toString());
+ }
+ };
+ new Command("how many commands do $YOU know[?]?") {
+ @Description("Asks Cherbot how many commands it knows.")
+ @Examples({"How many commands do you know?"})
+ @Override public void performImpl() {
+ answer("I know " + commands.size() + " commands.");
+ }
+ };
+ new Command("what('?s| is) new[?]?") {
+ @Description("Reports what's new since the last versions.")
+ @Examples({"What's new?"})
+ @Override public void performImpl() {
+ whatsNew();
+ }
+ };
+ new Command("ping") {
+ @Description("Command to test wether Cherbot is still active. If Cherbot works, it will respond \"pong\".")
+ @Examples({"ping"})
+ public void performImpl() {
+ answer("pong");
+ }
+ };
+ new Command("quit[.!]?") {
+ @Description("Quit Cherbot.")
+ @Examples({"Quit!"})
+ @Override public void performImpl() {
+ checkPermission(new CherBotPermission(PERM_QUIT));
+ answer("Quitting.");
+ quit();
+ }
+ };
+ } // Commands
+
+ // private final String[] permissions = { PERM_SAVE, PERM_LOAD };
+
+ /** Create an internal manager.
+ * @param cherBot Cher Bot
+ */
+ InternalManager(final CherBot cherBot) {
+ super(cherBot, "topics");
+ }
+
+ /** {@inheritDoc} */
+ @Override public void help() {
+ final StringBuilder topics = new StringBuilder();
+ for (Manager manager : managers) {
+ if (topics.length() > 0) {
+ topics.append(", ");
+ }
+ topics.append(manager.getTopic());
+ }
+ topics.insert(0, "I have help on the following topics: \n");
+ topics.append(".\n");
+ topics.append("Use help <topic> (without <>) to learn more on a specific topic.");
+ answer(topics.toString());
+ }
+
+ ///** {@inheritDoc} */
+ //public String[] getPermissions() {
+ // return permissions;
+ //}
+
+ /** What's new. */
+ private void whatsNew() {
+ BufferedReader in = null;
+ try {
+ in = new BufferedReader(new InputStreamReader(new FileInputStream("news.txt")));
+ final StringBuilder sb = new StringBuilder();
+ for (String line; (line = in.readLine()) != null; sb.append(line).append('\n'));
+ answer(sb.toString());
+ } catch (IOException e) {
+ answer("No news available.");
+ } finally {
+ try { in.close(); } catch (Exception e) { /* ignore */ } finally { in = null; }
+ }
+ }
+
+ { // IO Modules
+ new IOModule() {
+ @Override public void save() {
+ for (Manager manager : managers) {
+ if (manager != InternalManager.this) {
+ try {
+ manager.save();
+ } catch (Exception e) {
+ System.err.println("Error while saving data from module " + manager.getTopic() + ": " + e);
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ @Override public void load() {
+ for (Manager manager : managers) {
+ if (manager != InternalManager.this) {
+ try {
+ manager.load();
+ } catch (Exception e) {
+ System.err.println("Error while loading data for module " + manager.getTopic() + ": " + e);
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ };
+ }
+ } // class InternalManager
+
+} // class CherBot
Property changes on: trunk/src/cherbot/CherBot.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:eol-style
+ LF
Added: trunk/src/cherbot/CherBotException.java
===================================================================
--- trunk/src/cherbot/CherBotException.java (rev 0)
+++ trunk/src/cherbot/CherBotException.java 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,53 @@
+/* $Header: /home/rpgroot/CherBot/src/cherbot/CherBotException.java,v 1.3 2005/03/18 17:35:42 chris Exp $
+ *
+ * © 2005 Christian Hujer. All rights reserved.
+ * License: GNU General Public License. See file COPYING in the root directory of this project.
+ *
+ * Log: see end of file
+ */
+
+package cherbot;
+
+/** Base Exception for exteptions that could occur when using players.
+ * These exceptions are runtime exceptions thrown if actors use illegal arguments or commands in a wrong state.
+ * The message of such an exception must be a message meaningful to the end user (bot user).
+ * @author $Author: chris $
+ * @version $Id: CherBotException.java,v 1.3 2005/03/18 17:35:42 chris Exp $
+ */
+public class CherBotException extends RuntimeException {
+
+ /** Version information */
+ public static final String version = "$Revision: 1.3 $";
+
+ /** Serial Version. */
+ private static final long serialVersionUID = 1L;
+
+ /** Create a CherBotException.
+ * @param msg Message (displayed to end user)
+ */
+ public CherBotException(final String msg) {
+ super(msg);
+ }
+
+} // class CherBotException
+
+/*
+ * $Log: CherBotException.java,v $
+ * Revision 1.3 2005/03/18 17:35:42 chris
+ * Fixed cocumentation
+ *
+ * Revision 1.2 2005/03/14 03:06:20 chris
+ * Fixed copyright.
+ *
+ * Revision 1.1 2005/03/09 01:08:23 chris
+ * Added annotations to document commands.
+ * Improved commands.
+ * Unified some regular expressions.
+ * Reworked code to only shout in 2 particular cases:
+ * a) VOTE for Daimonin adds.
+ * b) A known criminal enters.
+ * Added PollManager.
+ * Added ManagerDocumenter.
+ * Reworked Exception Handling to integrate CherBotException.
+ *
+ */
Property changes on: trunk/src/cherbot/CherBotException.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:eol-style
+ LF
Added: trunk/src/cherbot/CherBotLogger.java
===================================================================
--- trunk/src/cherbot/CherBotLogger.java (rev 0)
+++ trunk/src/cherbot/CherBotLogger.java 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,96 @@
+/* $Header: /home/rpgroot/CherBot/src/cherbot/CherBotLogger.java,v 1.2 2005/08/31 13:55:28 chris Exp $
+ *
+ * © 2005 Christian Hujer. All rights reserved.
+ * License: GNU General Public License. See file COPYING in the root directory of this project.
+ *
+ * Log: see end of file
+ */
+
+package cherbot;
+
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+
+/** This class is used for logging within Cherbot.
+ * @author $Author: chris $
+ * @version $Id: CherBotLogger.java,v 1.2 2005/08/31 13:55:28 chris Exp $
+ */
+public class CherBotLogger {
+
+ /** Version information */
+ public static final String version = "$Revision: 1.2 $";
+
+ /** The logger. */
+ private PrintWriter log;
+
+ /** Create a logger. */
+ @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
+ public CherBotLogger() throws IOException {
+ log = new PrintWriter(new FileWriter("log.txt", true));
+ }
+
+ /** Log something said.
+ * @param who Who said it
+ * @param msg What he said
+ */
+ public void say(final String who, final String msg) {
+ log.append("[say] ").append(who).append(": ").append(msg).println();
+ }
+
+ /** Log something told.
+ * @param who Who told it
+ * @param msg What he told
+ */
+ public void tell(final String who, final String msg) {
+ log.append("[tell] ").append(who).append(": ").append(msg).println();
+ }
+
+ /** Log something shouted.
+ * @param who Who shouted it
+ * @param msg What he shouted
+ */
+ public void shout(final String who, final String msg) {
+ log.append("[shout] ").append(who).append(": ").append(msg).println();
+ }
+
+ /** Log a successful command.
+ * @param who Who invoked it
+ * @param msg Message that triggered command
+ * @param cmd Command
+ */
+ public void command(final String who, final String msg, final Manager.Command cmd) {
+ log.append("[cmd] ").append("[").append(cmd.getManager().getTopic()).append("]").append(who).append(": ").append(msg).println();
+ }
+
+ /** Log an unsuccessful command.
+ * @param who Who invoked it
+ * @param msg Message that triggered command
+ * @param cmd Command
+ * @param ex Exception that made the command fail
+ */
+ public void fail(final String who, final String msg, final Manager.Command cmd, final Exception ex) {
+ log.append("[fail] ").append("[").append(cmd.getManager().getTopic()).append("]").append(who).append(": ").append(msg).append("!").append(ex.toString()).println();
+ }
+
+ /** Log that a command wasn't found.
+ * @param who Who tried to command
+ * @param msg Message that didn't trigger a command
+ */
+ public void noCommand(final String who, final String msg) {
+ log.append("[nocmd] ").append(who).append(": ").append(msg).println();
+ }
+
+} // class CherBotLogger
+
+/*
+ * $Log: CherBotLogger.java,v $
+ * Revision 1.2 2005/08/31 13:55:28 chris
+ * Improved code quality.
+ * Removed console control feature.
+ * Changed member count to reflect only real members.
+ *
+ * Revision 1.1 2005/08/29 15:45:39 chris
+ * Some minor improvements.
+ *
+ */
Property changes on: trunk/src/cherbot/CherBotLogger.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:eol-style
+ LF
Added: trunk/src/cherbot/CherBotPermission.java
===================================================================
--- trunk/src/cherbot/CherBotPermission.java (rev 0)
+++ trunk/src/cherbot/CherBotPermission.java 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,39 @@
+/* $Header: /home/rpgroot/CherBot/src/cherbot/CherBotPermission.java,v 1.1 2005/03/01 09:14:02 chris Exp $
+ *
+ * © 2005 Christian Hujer. All rights reserved.
+ * License: GNU General Public License. See file COPYING in the root directory of this project.
+ *
+ * Log: see end of file
+ */
+
+package cherbot;
+
+import java.security.BasicPermission;
+
+/** Permissions to access the CherBot.
+ * @author $Author: chris $
+ * @version $Id: CherBotPermission.java,v 1.1 2005/03/01 09:14:02 chris Exp $
+ */
+public class CherBotPermission extends BasicPermission {
+
+ /** Version information */
+ public static final String version = "$Revision: 1.1 $";
+
+ /** Serial Version. */
+ private static final long serialVersionUID = 1L;
+
+ /** Create a CherBotPermission.
+ * @param name name
+ */
+ public CherBotPermission(final String name) {
+ super(name);
+ }
+
+} // class CherBotPermission
+
+/*
+ * $Log: CherBotPermission.java,v $
+ * Revision 1.1 2005/03/01 09:14:02 chris
+ * First import to version control.
+ *
+ */
Property changes on: trunk/src/cherbot/CherBotPermission.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:eol-style
+ LF
Added: trunk/src/cherbot/CherBotSecurityManager.java
===================================================================
--- trunk/src/cherbot/CherBotSecurityManager.java (rev 0)
+++ trunk/src/cherbot/CherBotSecurityManager.java 2006-10-27 08:40:41 UTC (rev 2)
@@ -0,0 +1,356 @@
+/* $Header: /home/rpgroot/CherBot/src/cherbot/CherBotSecurityManager.java,v 1.17 2005/11/09 20:30:00 chris Exp $
+ *
+ * © 2005 Christian Hujer. All rights reserved.
+ * License: GNU General Public License. See file COPYING in the root directory of this project.
+ *
+ * Log: see end of file
+ */
+
+package cherbot;
+
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.security.AllPermission;
+import java.security.Permission;
+import java.security.Permissions;
+import java.util.Comparator;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** SecurityManager for CherBot.
+ * The CherBotSecurityManager manages the permissions granted for the individual modules and actions.
+ * @author $Author: chris $
+ * @version $Id: CherBotSecurityManager.java,v 1.17 2005/11/09 20:30:00 chris Exp $
+ */
+@Manager.Description("Cherbot has a sophisticated security system, derived from Java. It is comparable with JAAS, the security concept used in Java application servers. This module controls security.")
+@Manager.Features({"Grant permissions", "Revoke permissions", "List permissions"})
+public class CherBotSecurityManager extends Manager {
+
+ /** Version information */
+ public static final String version = "$Revision: 1.17 $";
+
+ /** Permission to grant permissions. */
+ private static final String PERM_GRANT = "Security.Grant";
+
+ /** Permission to revoke permissions. */
+ private static final String PERM_REVOKE = "Security.Revoke";
+
+ /** Permission to list own permissions. */
+ private static final String PERM_LIST_OWN = "Security.List.Own";
+
+ /** Permission to list other player's permissions. */
+ private static final String PERM_LIST_OTHER = "Security.List";
+
+ /** The Permissions.
+ * Key: player name.
+ * Value: Set with permission names.
+ */
+ private Map<String,Permissions> permissions = new HashMap<String,Permissions>();
+
+ /** NullStringComparator. */
+ private Comparator<String> nullStringComparator = new Comparator<String>() {
+ public int compare(final String o1, final String o2) {
+ if (o1 == null && o2 == null) {
+ return 0;
+ } else if (o1 == null) {
+ return -1;
+ } else if (o2 == null) {
+ return 1;
+ } else {
+ return o1.compareTo(o2);
+ }
+ }
+ };
+
+ { // Commands
+ /* Grant command. */
+ new Command("(?:grant|allow) $PLAYER(?: access| permission)?(?: to| on)? (.*?)[.!]?") {
+ @Description("Grants someone the permission to do something.")
+ @Examples({"Grant Michtoen permission on *.", "Allow Michtoen access to *.", "Allow Tehrtapimp to Greetings.Set.Own."})
+ @Override public void performImpl() {
+ grant(player(1), gr(2));
+ }
+ };
+
+ /* Revoke command. */
+ new Command("(?:deny|revoke) $PLAYER(?:'s?)?(?: access| permission)?(?: to| on)? (.*?)[.!]?") {
+ @Description("Revokes someone's permission to do something.")
+ @Examples({"Deny Tehrtapimp to Greetings.Set.Own."})
+ @Override public void performImpl() {
+ revoke(player(1), gr(2));
+ }
+ };
...
[truncated message content] |