KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > client > LlamaChat


1 /*- LlamaChat.java ------------------------------------------------+
2  | |
3  | Copyright (C) 2002-2003 Joseph Monti, LlamaChat |
4  | countjoe@users.sourceforge.net |
5  | http://www.42llamas.com/LlamaChat/ |
6  | |
7  | This program is free software; you can redistribute it and/or |
8  | modify it under the terms of the GNU General Public License |
9  | as published by the Free Software Foundation; either version 2 |
10  | of the License, or (at your option) any later version |
11  | |
12  | This program is distributed in the hope that it will be useful, |
13  | but WITHOUT ANY WARRANTY; without even the implied warranty of |
14  | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
15  | GNU General Public License for more details. |
16  | |
17  | A copy of the GNU General Public License may be found in the |
18  | installation directory named "GNUGPL.txt" |
19  | |
20  +-----------------------------------------------------------------+
21  */

22
23 package client;
24
25 import java.awt.*;
26 import java.awt.event.*;
27 import javax.swing.*;
28 import javax.swing.text.*;
29 import javax.swing.text.html.*;
30 import javax.swing.event.*;
31 import javax.swing.border.*;
32 import java.util.*;
33 import java.lang.*;
34 import java.net.URL JavaDoc;
35 import java.net.MalformedURLException JavaDoc;
36 import java.nio.CharBuffer JavaDoc;
37 import java.util.regex.Pattern JavaDoc;
38 import java.util.Properties JavaDoc;
39
40 import common.*;
41 import common.sd.*;
42
43 /* -------------------- JavaDoc Information ----------------------*/
44 /**
45  * For use in a webpage:<br><pre>
46 &lt;OBJECT
47    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
48     width="615" height="360"
49     codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-i586.cab#Version=1,4,0,mn"&gt;
50   &lt;PARAM name="code" value="LlamaChat.class"&gt;
51   &lt;PARAM name="archive" value="LlamaChat.jar"&gt;
52   &lt;PARAM name="type" value="application/x-java-applet;version=1.4"&gt;
53   &lt;PARAM name="scriptable" value="true"&gt;
54   &lt;param name="username" value="[replace with username]"&gt;
55   &lt;param name="port" value="[replace with port]"&gt;
56 &lt;COMMENT&gt;
57 &lt;EMBED type="application/x-java-applet;version=1.4"
58    width="615" height="331"
59    code="LlamaChat.class" archive="LlamaChat.jar"
60    pluginspage="http://java.sun.com/j2se/1.4.1/download.html"
61  username="[replace with username]"
62  port="[replace with port]"&gt;
63     &lt;NOEMBED&gt;
64         No Java 1.4 plugin
65     &lt;/NOEMBED&gt;&lt;/EMBED&gt;
66 &lt;/COMMENT&gt;
67 &lt;/OBJECT&gt;
68  </pre>
69  This is the LlamaChat client applet; The above html needs values for
70  username, port, site, and location; Username is the name of the connecting
71  user, port is the port on which the server is running, site is the
72  IP address or hostname of the server, location is the location of the
73  client applet on the web
74  * @author Joseph Monti <a HREF="mailto:countjoe@users.sourceforge.net">countjoe@users.sourceforge.net</a>
75  * @version 0.8
76  */

77 /*
78 For use in a webpage:
79 <OBJECT
80    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
81     width="615" height="360"
82     codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-i586.cab#Version=1,4,0,mn">
83   <PARAM name="code" value="client/LlamaChat.class">
84   <PARAM name="archive" value="LlamaChat.jar">
85   <PARAM name="type" value="application/x-java-applet;version=1.4">
86   <PARAM name="scriptable" value="true">
87   <param name="username" value="[replace with username]">
88   <param name="port" value="[replace with port]">
89 <COMMENT>
90 <EMBED type="application/x-java-applet;version=1.4"
91    width="615" height="331"
92    code="client/LlamaChat.class" archive="LlamaChat.jar"
93    pluginspage="http://java.sun.com/j2se/1.4.1/download.html"
94  username="[replace with username]"
95  port="[replace with port]">
96     <NOEMBED>
97         No Java 1.4 plugin
98     </NOEMBED></EMBED>
99 </COMMENT>
100 </OBJECT>
101 */

102 public class LlamaChat extends JApplet {
103     
104     public String JavaDoc username;
105     private ServerConnection server;
106     public int PORT;
107     public String JavaDoc site;
108     public ArrayList users;
109     private CommandHistory history;
110     public ArrayList ignores;
111     public ArrayList afks;
112     public ArrayList admins;
113     public boolean admin;
114     public String JavaDoc locationURL;
115     private final String JavaDoc linkURL = "http://joe.tgpr.org/LlamaChat";
116     public Hashtable channels;
117     private static final String JavaDoc VERSION = "v0.8";
118     public PrivateMsg privates;
119     public boolean showUserStatus;
120     public boolean chanAdmin;
121     
122     Container c;
123     
124     ChatPane mainChat;
125     JList userList;
126     JTextField messageText;
127     JScrollPane textScroller;
128     JPopupMenu popup;
129     JComboBox cboChannels;
130     JButton butChannel;
131     JButton butCreate;
132     
133     ImageIcon conNo;
134     ImageIcon conYes;
135     ImageIcon secNo;
136     ImageIcon secYes;
137     JLabel conIcon;
138     JLabel secIcon;
139     JLabel bottomText;
140     
141     
142     MyAction myAction;
143     MyKeyListener myKeyListener;
144     MyMouseListener myMouseListener;
145     MyHyperlinkListener myHyperlinkListener;
146     Color myColors[] = new Color[3];
147     
148     Rectangle rect;
149
150     /**
151      * Initializes the graphical components
152      */

153     public void init() {
154         username = getParameter("username");
155         if (username == null) {
156             username = JOptionPane.showInputDialog(
157                                     this,
158                                     "Please enter a username",
159                                     "Login",
160                                     JOptionPane.QUESTION_MESSAGE);
161         }
162         try {
163             PORT = Integer.valueOf(getParameter("port")).intValue();
164         } catch (NumberFormatException JavaDoc e) {
165             PORT = 42412;
166         }
167         
168         URL JavaDoc url = getDocumentBase();
169         site = url.getHost();
170         locationURL = "http://" + site + ":" + url.getPort() + "/" + url.getPath();
171         
172         setSize(615,362);
173         c = getContentPane();
174         
175         c.setBackground(new Color(224,224,224));
176         
177         if (site == null || locationURL == null) {
178             c.add(new JLabel("ERROR: did not recieve needed data from page"));
179         }
180
181         myAction = new MyAction();
182         myKeyListener = new MyKeyListener();
183         myMouseListener = new MyMouseListener();
184         myHyperlinkListener = new MyHyperlinkListener();
185
186         c.setLayout(null);
187         
188         cboChannels = new JComboBox();
189         cboChannels.setBounds(5, 5, 150, 24);
190         
191         butChannel = new JButton("Join");
192         butChannel.setToolTipText("Join channel");
193         butChannel.addActionListener(myAction);
194         butChannel.setBounds(160, 5, 60, 24);
195         
196         butCreate = new JButton("Create");
197         butCreate.setToolTipText("Create new channel");
198         butCreate.addActionListener(myAction);
199         butCreate.setBounds(230, 5, 80, 24);
200         butCreate.setEnabled(false);
201         
202         mainChat = new ChatPane(this);
203         textScroller = new JScrollPane(mainChat,
204                                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
205                                 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
206         textScroller.setBounds(5,34,500,270);
207                 
208         userList = new JList();
209         userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
210         userList.setCellRenderer(new MyCellRenderer());
211         userList.setBackground(new Color(249, 249, 250));
212         JScrollPane userScroller = new JScrollPane(userList);
213         userScroller.setBounds(510,34,100,297);
214         
215         messageText = new JTextField();
216         messageText.setBounds(5,309,500,22);
217         messageText.setColumns(10);
218         messageText.setBackground(new Color(249, 249, 250));
219         
220         JMenuItem item;
221         popup = new JPopupMenu("test");
222         popup.add("whisper").addActionListener(myAction);
223         popup.add("private message").addActionListener(myAction);
224         popup.add("ignore").addActionListener(myAction);
225         popup.add("clear ignore list").addActionListener(myAction);
226         
227         conNo = new ImageIcon(getURL("images/connect_no.gif"));
228         conYes = new ImageIcon(getURL("images/connect_established.gif"));
229         secNo = new ImageIcon(getURL("images/decrypted.gif"));
230         secYes = new ImageIcon(getURL("images/encrypted.gif"));
231
232         conIcon = new JLabel(conNo);
233         conIcon.setBorder(new EtchedBorder());
234         secIcon = new JLabel(secNo);
235         secIcon.setBorder(new EtchedBorder());
236         
237
238         conIcon.setBounds(563,334, 22, 22);
239         secIcon.setBounds(588,334, 22, 22);
240         
241         bottomText = new JLabel("<html><body><font color=#445577><b>" +
242                         "LlamaChat " + VERSION + "</b></font> &nbsp;&copy; " +
243                         "<a HREF=\"" + linkURL+ "\">Joseph Monti</a> 2002-2003" +
244                         "</body></html>");
245         bottomText.setBounds(5, 336, 500, 20);
246         
247         c.add(cboChannels);
248         c.add(butChannel);
249         c.add(butCreate);
250         c.add(textScroller);
251         c.add(userScroller);
252         c.add(messageText);
253         c.add(conIcon);
254         c.add(secIcon);
255         c.add(bottomText);
256         
257         userList.addMouseListener(myMouseListener);
258         messageText.addKeyListener(myKeyListener);
259         bottomText.addMouseListener(myMouseListener);
260         
261         users = new ArrayList();
262         ignores = new ArrayList(5);
263         afks = new ArrayList(5);
264         admins = new ArrayList(5);
265         history = new CommandHistory(10);
266         admin = false;
267         channels = new Hashtable();
268         privates = new PrivateMsg(this);
269         showUserStatus = false;
270         
271         myColors[0] = new Color(200, 0, 0);
272         myColors[1] = new Color(0, 150, 0);
273         myColors[2] = new Color(0, 0, 200);
274         
275         rect = new Rectangle(0,0,1,1);
276         
277         String JavaDoc opening = "<font color=#333333>" +
278                          "==================================<br>" +
279                          "Welcome to LlamaChat " + VERSION + "<br>" +
280                          "If you need assistance, type \\help<br>" +
281                          "Enjoy your stay!<br>" +
282                          "==================================<br></font>";
283         HTMLDocument doc = (HTMLDocument) mainChat.getDocument();
284         HTMLEditorKit kit = (HTMLEditorKit) mainChat.getEditorKit();
285         try {
286             kit.insertHTML(doc,doc.getLength(),opening,0,0,HTML.Tag.FONT);
287         } catch (Throwable JavaDoc t) { t.printStackTrace(System.out); }
288
289         // validate the name
290
if (!username.matches("[\\w_-]+?")) {
291             error("username contains invalid characters, changing to " +
292                         "'invalid' for now. " +
293                         "Type \\rename to chose a new name");
294             username = "invalid";
295         }
296         if (username.length() > 10) {
297             username = username.substring(0,10);
298             error("username too long, changed to " + username);
299         }
300
301         connect();
302     }
303     
304     public void start() { }
305     
306     public void stop() {
307         if (server != null)
308             server._writeObject(new SD_UserDel(null)); // to bypass the queue
309
}
310     
311     /**
312      * Subclass to act as the action listener for graphical components
313      */

314     protected final class MyAction implements ActionListener {
315         public void actionPerformed(ActionEvent ae) {
316             String JavaDoc cmd = ae.getActionCommand().intern();
317             if (ae.getSource() == butChannel) {
318                 String JavaDoc pass = null;
319                 String JavaDoc channel = (String JavaDoc) cboChannels.getSelectedItem();
320                 if (channels.containsKey(channel) && ((Boolean JavaDoc) channels.get(channel)).booleanValue()) {
321                     String JavaDoc message = "Password for " + channel +
322                                     "? (blank for no password)";
323                     pass = JOptionPane.showInputDialog(
324                                     (Component) ae.getSource(),
325                                     message,
326                                     "Join Channel",
327                                     JOptionPane.QUESTION_MESSAGE);
328                 }
329                 server.writeObject(new SD_Channel(false, channel,
330                             ("".equals(pass) ? null : pass)));
331                 showUserStatus = false;
332             } else if (ae.getSource() == butCreate) {
333                 String JavaDoc channel = JOptionPane.showInputDialog(
334                                     (Component) ae.getSource(),
335                                     "Enter the name of the channel",
336                                     "Create Channel",
337                                     JOptionPane.INFORMATION_MESSAGE);
338                 if (channel == null) return;
339                 String JavaDoc message = "Password for " + channel +
340                                     "? (blank for no password)";
341                 String JavaDoc pass = JOptionPane.showInputDialog(
342                                     (Component) ae.getSource(),
343                                     message,
344                                     "Join Channel",
345                                     JOptionPane.QUESTION_MESSAGE);
346                 server.writeObject(new SD_Channel(true, channel,
347                                     ("".equals(pass) ? null : pass)));
348                 showUserStatus = false;
349             } else if (cmd == "whisper") {
350                 String JavaDoc user = (String JavaDoc)userList.getSelectedValue();
351                 if (user != null && !messageText.getText().equals("") &&
352                                                     !user.equals(username)) {
353                     messageText.setText("\\whisper " + user + " " +
354                                                     messageText.getText());
355                     sendMessage();
356                 } else {
357                     error("invalid user or no message, type a message below," +
358                             " select a user, and then whisper");
359                 }
360             } else if (cmd == "private message") {
361                 String JavaDoc user = (String JavaDoc)userList.getSelectedValue();
362                 if (user != null && !user.equals(username)) {
363                     privates.newPrivate(user);
364                 } else {
365                     error("invalid user");
366                 }
367             } else if (ae.getActionCommand().equals("ignore")) {
368                 String JavaDoc user = (String JavaDoc)userList.getSelectedValue();
369                 if (user != null) {
370                     ignore(user, false);
371                 } else {
372                     error("no user selected");
373                 }
374             } else if (cmd == "clear ignore list") {
375                 ignores.clear();
376                 updateList();
377                 serverMessage("ignore list cleared");
378             } else if (cmd == "kick user") {
379                 String JavaDoc user = (String JavaDoc)userList.getSelectedValue();
380                 if (user != null) {
381                     if (user.equals(username)) {
382                         error("cannot kick yourself");
383                     } else {
384                         server.writeObject(new SD_Kick(user));
385                     }
386                 } else {
387                     error("no user selected");
388                 }
389             }
390         }
391     }
392     
393     /**
394      * Subclass to act as the key listener for the graphical componets
395      */

396     protected final class MyKeyListener implements KeyListener {
397         public void keyTyped(KeyEvent ke) {
398             if (ke.getKeyChar() == KeyEvent.VK_ENTER) {
399                 sendMessage();
400             }
401         }
402         public void keyPressed(KeyEvent ke) {
403             //
404
}
405         public void keyReleased(KeyEvent ke) {
406             if (ke.getKeyCode() == KeyEvent.VK_UP) {
407                 String JavaDoc up = history.getUp();
408                 if (up != null)
409                     messageText.setText(up);
410             } else if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
411                 String JavaDoc down = history.getDown();
412                 if (down != null)
413                     messageText.setText(down);
414             }
415         }
416     }
417     
418     /**
419      * Subclass to act as the mouse listener for the graphical components
420      */

421     protected final class MyMouseListener implements MouseListener {
422         public void mousePressed(MouseEvent e) {
423         }
424
425         public void mouseReleased(MouseEvent e) {
426             maybeShowPopup(e);
427         }
428     
429         public void mouseEntered(MouseEvent e) {
430             if (e.getSource() == bottomText) {
431                 bottomText.setCursor(
432                         Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
433             }
434         }
435         public void mouseExited(MouseEvent e) {
436             if (e.getSource() == bottomText) {
437                 bottomText.setCursor(Cursor.getDefaultCursor());
438             }
439         }
440     
441         public void mouseClicked(MouseEvent e) {
442             if (e.getSource() == bottomText) {
443                 try {
444                     getAppletContext().showDocument(
445                                         new URL JavaDoc(linkURL), "_blank");
446                 } catch (java.net.MalformedURLException JavaDoc ex) { }
447             } else {
448                 maybeShowPopup(e);
449             }
450         }
451
452         /**
453          * Checks to see if the event was to show the popup menu
454          */

455         private void maybeShowPopup(MouseEvent e) {
456             if ((e.getModifiers() & MouseEvent.BUTTON3_MASK)!=0) {
457                 popup.show(userList, e.getX(), e.getY());
458             }
459         }
460     }
461     
462     protected final class MyHyperlinkListener implements HyperlinkListener {
463         public void hyperlinkUpdate(HyperlinkEvent e) {
464             if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
465                 getAppletContext().showDocument(e.getURL(), "_blank");
466             }
467         }
468     }
469     
470     /**
471      * a Subclass to handle cell items in the user list
472      * lets us modify add an icon to the username
473      */

474     protected final class MyCellRenderer extends DefaultListCellRenderer {
475         final ImageIcon normal =
476                     new ImageIcon(getURL("images/face.gif"));
477         final ImageIcon ignored =
478                     new ImageIcon(getURL("images/face_ignore.gif"));
479         final ImageIcon afk =
480                     new ImageIcon(getURL("images/afk.gif"));
481         final ImageIcon admin =
482                     new ImageIcon(getURL("images/admin.gif"));
483
484         /* This is the only method defined by ListCellRenderer. We just
485         * reconfigure the Jlabel each time we're called.
486         */

487         public Component getListCellRendererComponent(
488                     JList list,
489                     Object JavaDoc value, // value to display
490
int index, // cell index
491
boolean iss, // is the cell selected
492
boolean chf) // the list and the cell have the focus
493
{
494             /* The DefaultListCellRenderer class will take care of
495             * the JLabels text property, it's foreground and background
496             * colors, and so on.
497             */

498             super.getListCellRendererComponent(list, value, index, iss, chf);
499             if (afks.contains(value.toString())) {
500                 setIcon(afk);
501             } else if (admins.contains(value.toString())) {
502                 setIcon(admin);
503             } else if (ignores.contains(value.toString())) {
504                 setIcon(ignored);
505             } else {
506                 setIcon(normal);
507             }
508             if (username.equals(getText())) {
509                 setForeground(myColors[1]);
510             } else {
511                 setForeground(myColors[2]);
512             }
513
514             return this;
515         }
516     }
517     
518     /**
519      * Method to take a filename and return a URL object
520      * @param filename the name of the file to be turned into URL
521      * @return the url representing filename
522      */

523     protected final URL JavaDoc getURL(String JavaDoc filename) {
524         URL JavaDoc url = null;
525
526         try {
527             url = new URL JavaDoc(locationURL + filename);
528         } catch (java.net.MalformedURLException JavaDoc e) {
529             System.err.println("Couldn't create image: " +
530                                "badly specified URL");
531             return null;
532         }
533     
534         return url;
535     }
536
537     /**
538      * Method called when a user message has been sent.
539      * checks to see if it is a command or regular message
540      */

541     private void sendMessage() {
542         String JavaDoc txt = new String JavaDoc(messageText.getText());
543         if (!txt.equals("")) {
544             if (txt.charAt(0) == '\\' || txt.charAt(0) == '/') {
545                 parseCommand(txt.substring(1));
546                 messageText.setText("");
547                 history.add(txt);
548             } else if (server != null && server.connected && username != null) {
549                 sendText(username, txt, false);
550                 messageText.setText("");
551                 sendChat(txt);
552                 history.add(txt);
553             } else {
554                 error("Not connected, type \\reconnect to try and reconnect");
555             }
556         }
557     }
558     
559     /**
560      * Method to parse a command and perform the specified action
561      * @param cmd the command that the user typed
562      * @return a status indicator to tell if the command was valid
563      */

564     public boolean parseCommand(String JavaDoc cmd) {
565         cmd = cmd.intern();
566         if (cmd == "help" || cmd == "?") {
567             String JavaDoc commands = "Listing available commands:\n" +
568                     "<pre>\\help or \\? \t\t- display this message<br>" +
569                     "\\admin &lt;passphrase&gt; \t- become an admin<br>" +
570                     "\\create &lt;channel&gt; [password]\t- create a new channel with optional password<br>" +
571                     "\\join &lt;channel&gt; [password]\t- join channel with optional password<br>" +
572                     "\\disconnect \t\t- disconnect from server<br>" +
573                     "\\whisper &lt;user&gt; &lt;message&gt; \t- whisper to a user<br>" +
574                     "\\private &lt;user&gt; \t- start a private message session<br>" +
575                     "\\ignore &lt;user&gt; \t\t- ignores a user<br>" +
576                     "\\clearignore \t\t- clear list of ignores<br>" +
577                     "\\reconnect \t\t- attempt to reconnect to server<br>" +
578                     "\\rename &lt;new name&gt; \t\t- change your username<br>";
579             if (admin) {
580                 commands += "\\kick &lt;user&gt; \t\t- kick user from room<br>" +
581                             "\\logstart \t\t- start logging sessoin<br>" +
582                             "\\logstop \t\t- stop logging session<br>";
583             }
584             commands += "up or down \t\t- cycle your chat history</pre>";
585             sendText("server", commands, false);
586             return true;
587         } else if (cmd == "disconnect") {
588             if (server != null) {
589                 stop();
590             }
591             return true;
592         } else if (cmd == "reconnect") {
593             if (username == null) {
594                 error("username still invalid. use \\rename &lt;new name&gt; to chose a new name and reconnect");
595             } else {
596                 if (server != null) {
597                     stop();
598                 }
599                 server = new ServerConnection(this);
600             }
601             return true;
602         } else if (cmd == "clearignore") {
603             ignores.clear();
604             updateList();
605             serverMessage("ignore list cleared");
606             return true;
607         } else if (cmd.startsWith("whisper")) {
608             int start = cmd.indexOf(' ');
609             if (start < 0) {
610                 error("usage: \\whisper &lt;user&gt; &lt;message&gt;");
611                 return false;
612             }
613             cmd = cmd.substring(start+1);
614             start = cmd.indexOf(' ');
615             if (start < 0) {
616                 error("usage: \\whisper &lt;user&gt; &lt;message&gt;");
617                 return false;
618             }
619             String JavaDoc un = cmd.substring(0, start);
620             if (username.equals(un) || !users.contains(un)) {
621                 error("invalid user");
622                 return false;
623             }
624             String JavaDoc message = cmd.substring(start+1);
625             if (message.length() < 1) {
626                 error("usage: \\whisper &lt;user&gt; &lt;message&gt;");
627             }
628             sendWhisper(un, message);
629             sendText(username, message, true);
630             return true;
631         } else if (cmd.startsWith("private")) {
632             int start = cmd.indexOf(' ');
633             if (start < 0) {
634                 error("usage: \\private &lt;user&gt;");
635                 return false;
636             }
637             String JavaDoc un = cmd.substring(start+1);
638             if (username.equals(un)) {
639                 error("cannot private message yourself");
640                 return false;
641             }
642             privates.newPrivate(un);
643             return true;
644         } else if (cmd.startsWith("rename")) {
645             int start = cmd.indexOf(' ');
646             if (start < 0) {
647                 error("usage: \\rename &lt;newname&gt;");
648                 return false;
649             }
650             String JavaDoc newName = cmd.substring(start+1);
651             if ((newName.length() < 1) || (newName.length()) > 10 ||
652                                             (newName.equals("server")) ||
653                                             (!newName.matches("[\\w_-]+?"))) {
654                 error("invalid name");
655                 return false;
656             }
657             if (!server.connected) {
658                 server = new ServerConnection(this);
659             }
660             if (username == null) {
661                 username = newName;
662                 server.writeObject(new SD_UserAdd(newName));
663             } else {
664                 rename(username, newName);
665                 username = newName;
666                 server.writeObject(new SD_Rename(null, username));
667             }
668             return true;
669         } else if (cmd.startsWith("ignore")) {
670             int start = cmd.indexOf(' ');
671             if (start < 0) {
672                 error("usage: \\ignre &lt;user&gt;");
673                 return false;
674             }
675             ignore(cmd.substring(start+1), false);
676             return true;
677         } else if (cmd.startsWith("join")) {
678             int start = cmd.indexOf(' ');
679             if (start < 0) {
680                 error("usage: \\join &lt;channel&gt; [password]");
681                 return false;
682             }
683             String JavaDoc name = cmd.substring(start+1);
684             String JavaDoc pass = null;
685             start = name.indexOf(' ');
686             if (start > 0) {
687                 pass = name.substring(start+1);
688                 name = name.substring(0, start);
689             }
690             server.writeObject(new SD_Channel(false, name, pass));
691             return true;
692         } else if (cmd.startsWith("create")) {
693             int start = cmd.indexOf(' ');
694             if (start < 0) {
695                 error("usage: \\create &lt;channel&gt; [password]");
696                 return false;
697             }
698             String JavaDoc name = cmd.substring(start+1);
699             String JavaDoc pass = null;
700             start = name.indexOf(' ');
701             if (start > 0) {
702                 pass = name.substring(start+1);
703                 name = name.substring(0, start);
704             }
705             server.writeObject(new SD_Channel(true, name, pass));
706             return true;
707 /* } else if (cmd.startsWith("proxy")) {
708             int start = cmd.indexOf(' ');
709             if (start < 0) {
710                 error("usage: \\proxy &lt;host&gt; &lt;port&gt;");
711                 return false;
712             }
713             String phost = cmd.substring(start+1);
714             start = phost.indexOf(' ');
715             if (start < 0) {
716                 error("usage: \\proxy &lt;host&gt; &lt;port&gt;");
717                 return false;
718             }
719             String pport = phost.substring(start+1);
720             phost = phost.substring(0, start);
721             Properties systemSettings = System.getProperties();
722             systemSettings.put("proxySet", "true");
723             systemSettings.put("proxyHost", phost);
724             systemSettings.put("proxyPort", pport);
725             System.setProperties(systemSettings);
726             serverMessage("Using " + phost + ":" + pport + " as proxy server<br>you can type \\reconnect to reconnect with this proxy");
727             return true; */

728         }else if (cmd.startsWith("admin")) {
729             int start = cmd.indexOf(' ');
730             if (start < 0) {
731                 error("usage: \\admin &lt;password&gt;");
732                 return false;
733             }
734             String JavaDoc pass = cmd.substring(start+1);
735             server.writeObject(new SD_AdminAdd(pass));
736             return true;
737         } else if (admin && cmd.startsWith("kick")) {
738             int start = cmd.indexOf(' ');
739             if (start < 0) {
740                 error("usage: \\kick &lt;user&gt;");
741                 return false;
742             }
743             String JavaDoc un = cmd.substring(start+1);
744             if (un.equals(username)) {
745                 error("cannot kick yourself");
746                 return false;
747             }
748             server.writeObject(new SD_Kick(un));
749             return true;
750         } else if (admin && cmd == "logstart") {
751             server.writeObject(new SD_Log(true));
752             return true;
753         } else if (admin && cmd == "logstop") {
754             server.writeObject(new SD_Log());
755             return true;
756         }
757         error("unrecognized command, type \\help for help");
758         return false;
759     }
760     
761     /**
762      * Method to ignore all incoming messages from a user
763      * @param i the user to ignore
764      * @param quite if true will not show confirmation
765      * @return true on succes, false on failure
766      */

767     private boolean ignore(String JavaDoc i, boolean quiet) {
768         if (username.equals(i) || i.equals("server") || admins.contains(i)) {
769             if (!quiet) {
770                 error("can't ignore that person");
771             }
772             return false;
773         }
774         if (!users.contains(i)) {
775             if (!quiet) {
776                 error("user does not exists");
777             }
778             return false;
779         }
780         if (ignores.contains(i)) {
781             if (!quiet) {
782                 error("already ignoring user");
783             }
784             return false;
785         }
786         ignores.add(i);
787         updateList();
788         if (!quiet) {
789             serverMessage("ignoring " + i);
790         }
791         return true;
792     }
793     
794     /**
795      * Sends a text to the chat window. Parses the message to pick
796      * out emoticons.
797      * @param un the name of the user sending the message
798      * @param message the message to be sent
799      * @param whisper indicates the message was a wisper and makes the
800      * message italic
801      */

802     public void sendText(String JavaDoc un, String JavaDoc message, boolean whisper) {
803         mainChat.sendText(un, message, whisper);
804     }
805     
806     /**
807      * Create a new connection to a server
808      */

809     private void connect() {
810         server = new ServerConnection(this);
811     }
812     
813     /**
814      * sends a new message to the server
815      * @param message the message to be sent
816      */

817     private void sendChat(String JavaDoc message) {
818         if (server != null) {
819             server.writeObject(new SD_Chat(null, message));
820         }
821     }
822     
823     /**
824      * sends a whisper to the server
825      * @param message the message to be sent
826      */

827     private void sendWhisper(String JavaDoc to, String JavaDoc message) {
828         if (server != null) {
829             server.writeObject(new SD_Whisper(to, message));
830         }
831     }
832     
833     /**
834      * sorts the user list and rebuilds the user list from
835      * the sorted user vector,
836      */

837     public void updateList() {
838         Object JavaDoc[] tmp = users.toArray();
839         Arrays.sort(tmp);
840         userList.setListData(tmp);
841     }
842     
843     /**
844      * adds a new user to the interal list of users
845      * @param un the name of the user to be added
846      */

847     public void userAdd(String JavaDoc un) {
848         if (!users.contains(un)) {
849             users.add(un);
850             updateList();
851             if (!un.equals(username) && showUserStatus)
852                 serverMessage(un + " has joined " + server.channel);
853         }
854     }
855     
856     /**
857      * removes a user from the user list
858      * @param un the name of the user to be removed
859      */

860     public void userDel(String JavaDoc un) {
861         users.remove(users.indexOf(un));
862         if (ignores.contains(un)) {
863             ignores.remove(ignores.indexOf(un));
864         }
865         if (afks.contains(un)) {
866             afks.remove(afks.indexOf(un));
867         }
868         if (admins.contains(un)) {
869             admins.remove(admins.indexOf(un));
870         }
871         updateList();
872         serverMessage(un + " has left " + server.channel);
873         privates.serverMessage(un, un + " has left");
874     }
875     
876     /**
877      * changes the name of a user, updating list of admins,
878      * afks, ignoes, and master user list
879      * @param on old username
880      * @param nn new username
881      */

882     public void rename(String JavaDoc on, String JavaDoc nn) {
883         if (admins.contains(on)) {
884             admins.remove(admins.indexOf(on));
885             admins.add(nn);
886         }
887         if (afks.contains(on)) {
888             afks.remove(afks.indexOf(on));
889             afks.add(nn);
890         }
891         if (ignores.contains(on)) {
892             ignores.remove(ignores.indexOf(on));
893             ignores.add(nn);
894         }
895         users.remove(on);
896         users.add(nn);
897         updateList();
898         serverMessage(on + " renamed to " + nn);
899     }
900     
901     /**
902      * Recieving method for a chat message
903      * @param un the name of the user sending the chat
904      * @param message the message that was sent
905      */

906     public void recieveChat(String JavaDoc un, String JavaDoc message) {
907         if (!ignores.contains(un)) {
908             sendText(un, message, false);
909         }
910     }
911     
912     /**
913      * Reciving method for a whisper
914      * @param un the name of the user sending the whisper
915      * @param message the message that was sent
916      */

917     public void recieveWhisper(String JavaDoc un, String JavaDoc message) {
918         if (!ignores.contains(un)) {
919             sendText(un, message, true);
920         }
921     }
922     
923     /**
924      * Recieving method for private
925      * @param un the name of the user sending the message
926      * @param message the message that was sent
927      */

928     public void recievePrivate(String JavaDoc un, String JavaDoc message) {
929         if (!ignores.contains(un)) {
930             privates.recievePrivate(un, message);
931         }
932     }
933     
934     /**
935      * signifies an error and reports it to the user
936      * @param s the error message
937      */

938     public void error(String JavaDoc s) {
939         mainChat.error(s);
940     }
941     
942     /**
943      * A shortcut to be used when a message from the server (or any automated
944      * message) must ben sent to the client
945      * @param s the message
946      */

947     public void serverMessage(String JavaDoc s) {
948         sendText("server", s, false);
949     }
950     
951     /**
952      * cleans up a connection by removing all user from all maintained lists
953      */

954     public void close() {
955         error("Connection to server was lost");
956         admin = false;
957         users.clear();
958         afks.clear();
959         ignores.clear();
960         admins.clear();
961         channels.clear();
962         cboChannels.removeAllItems();
963         updateList();
964     }
965     
966     /**
967      * used to manage the connection icons to signify connection and
968      * secure status
969      * @param b true if connected
970      */

971     public void setConnected(boolean b) {
972         if (b) {
973             conIcon.setIcon(conYes);
974             conIcon.setToolTipText("Connected");
975             secIcon.setIcon(secYes);
976             secIcon.setToolTipText("Secure Connection");
977             butChannel.setEnabled(true);
978         } else {
979             conIcon.setIcon(conNo);
980             conIcon.setToolTipText("Not Connected");
981             secIcon.setIcon(secNo);
982             secIcon.setToolTipText("Connection not Secured");
983             butChannel.setEnabled(false);
984             butCreate.setEnabled(false);
985         }
986     }
987     
988     /**
989      * sets this user to be an admin
990      */

991     public void setAdmin() {
992         admin = true;
993         popup.add("kick user").addActionListener(myAction);
994         if (chanAdmin) {
995             butCreate.setEnabled(true);
996         }
997     }
998     
999     /**
1000     * creates a new channel, if the channel exists it is removed
1001     * (this method doubles as a removeChannel)
1002     * @param name the name of the channel
1003     */

1004    public void newChannel(String JavaDoc name, boolean pass) {
1005        if (channels.containsKey(name)) {
1006            channels.remove(name);
1007            cboChannels.removeItem(name);
1008        } else {
1009            channels.put(name, new Boolean JavaDoc(pass));
1010            cboChannels.addItem(name);
1011        }
1012    }
1013    
1014    public void sendPrivate(String JavaDoc name, String JavaDoc message) {
1015        server.writeObject(new SD_Private(name, message));
1016    }
1017}
1018
1019
Popular Tags