KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > zirc > threads > ConnectThread


1 package zirc.threads ;
2
3 import java.io.* ;
4 import java.net.* ;
5 import java.util.* ;
6 import zirc.base.* ;
7 import zirc.gui.* ;
8 import zirc.msg.* ;
9 import zirc.dcc2.* ;
10
11 //zIrc, irc client.
12
// Copyright (C) 2004 CoolBytes(Stephane claret, Andre Aymon, Alban Zumofen) coolbytes@hotmail.com
13
//
14
// This program is free software; you can redistribute it and/or
15
// modify it under the terms of the GNU General Public License
16
// as published by the Free Software Foundation; either version 2
17
// of the License, or (at your option) any later version.
18
//
19
// This program is distributed in the hope that it will be useful,
20
// but WITHOUT ANY WARRANTY; without even the implied warranty of
21
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22
// GNU General Public License for more details.
23

24 /**
25  * <p>Title: ConnectThread</p>
26  * <p>Description: Thread de la connexion principale, fait enormement de choses...</p>
27  * <p>Copyright: Copyright (c) 2004</p>
28  * <p>Company: CoolBytes(Stephane Claret, Andre Aymon, Alban Zumofen) coolbytes@hotmail.com</p>
29  * @version 1.0
30  */

31
32 public class ConnectThread extends Thread JavaDoc
33 {
34   //un ircconnexion dispose de toutes les infos utiles
35
private IRCconnexion chatIRC ;
36   private static IdentListenerThread il ;
37
38   //contiendra la liste des users dans un chan
39
private ArrayList userLists = new ArrayList() ;
40
41   //le int qui contient la valeur int du reply serveur
42
private int replyCode ;
43
44   //pour definir le stop du thread
45
private boolean loop = true ;
46
47   //contient une réponse du serv en
48
MessageRecuSplite servRep ;
49
50   private String JavaDoc lastOne = "" ;
51
52   public ConnectThread(IRCconnexion _chatIRC)
53   {
54     chatIRC = _chatIRC ;
55   }
56
57   private void connectSocket(int port) throws UnknownHostException, ConnectException, IOException
58   {
59     /*
60            Command: USER
61            Parameters: <username> <hostname> <servername> <realname>
62      */

63
64     //message d'info
65
//(new MSGinfo(chatIRC, chatIRC.GetStatusFrm(), "Connexion au serveur...")).affiche() ;
66

67     //ouvrir un socket
68
chatIRC.setMainSock(new Socket(chatIRC.GetMainSockServer(), port /*chatIRC.GetMainSockPort()*/)) ;
69
70     //garnir les i/o streams
71
chatIRC.setMainSockIn(new BufferedReader(new InputStreamReader(chatIRC.getMainSock().getInputStream()))) ;
72     chatIRC.setMainSockOut(new PrintWriter(chatIRC.getMainSock().getOutputStream())) ;
73
74     //gérer le serveur ident
75
if (il == null)
76     {
77       il = new IdentListenerThread() ;
78       il.start() ;
79     }
80     il.addConnection(this.chatIRC) ;
81
82     //envoyer les commandes de login
83
chatIRC.sendCommand("PASS none") ;
84     chatIRC.sendCommand("NICK " + chatIRC.GetUser_nickName()) ;
85     chatIRC.sendCommand("USER " + chatIRC.getUser_nomUser() + " " + chatIRC.GetUser_hote() + " " + chatIRC.GetUser_serverName() + " : " +
86                         chatIRC.getUser_realName()) ;
87
88   }
89
90   public void run()
91   {
92
93     int p = 0 ; //le nbre de port teste
94
int nbOfPorts = chatIRC.getServerPortList().length ; //le nbre de ports total
95
boolean portOK = false ; //boolean qui dit si on a pu se connecter par le port
96

97     do //on boucle tant qu'il ya des ports
98
{
99       try
100       {
101         (new MSGinfoPlus(chatIRC, chatIRC.GetStatusFrm(),
102                          ("Tentative de connexion au serveur sur le port " + chatIRC.getServerPortList()[p] + "..."))).affiche() ;
103         connectSocket(chatIRC.getServerPortList()[p]) ;
104
105         //si on passe la c que le port est ok
106
portOK = true ;
107
108       }
109       catch (UnknownHostException ex)
110       {
111         (new MSGinfoPlus(chatIRC, chatIRC.GetStatusFrm(),
112                          ("Hote inconnu..."))).affiche() ;
113         ex.printStackTrace() ;
114         loop = false ; //on sort du run, thread termine
115
}
116       catch (ConnectException ex1)
117       {
118         (new MSGinfoPlus(chatIRC, chatIRC.GetStatusFrm(),
119                          ("Tentative de connexion au serveur sur le port " + chatIRC.getServerPortList()[p] + " echouee..."))).affiche() ;
120         p++ ;
121         portOK = false ;
122       }
123       catch (IOException ex)
124       {
125         ex.printStackTrace() ;
126       }
127
128       catch (Exception JavaDoc ex)
129       {
130         ex.printStackTrace() ;
131       }
132     }
133     while (p < nbOfPorts && !portOK && loop) ;
134
135     //quand il n'y a plus de ports et que la connexion est tj null on part dans le nullpointerexception
136

137     String JavaDoc line ;
138
139     try
140     {
141       while (loop && (line = chatIRC.getMainSockIn().readLine()) != null)
142       {
143         parserRepServ(line) ;
144       }
145     }
146     catch (SocketException ex)
147     {
148       ex.printStackTrace() ;
149       System.out.println("!!!!!!CATCHEE!!!!!!") ;
150
151       (new MSGinfoPlus(chatIRC, chatIRC.GetStatusFrm(),
152                        ("Connexion perdue..."))).affiche() ;
153     }
154     catch (IOException ex)
155     {
156       ex.printStackTrace() ;
157       System.out.println("!!!!!!CATCHEE!!!!!!") ;
158     }
159     catch (NullPointerException JavaDoc ex)
160     {
161       ex.printStackTrace() ;
162       System.out.println("!!!!!!CATCHEE!!!!!!") ;
163
164       (new MSGinfoPlus(chatIRC, chatIRC.GetStatusFrm(),
165                        ("Connexion impossible..."))).affiche() ;
166     }
167   }
168
169   private void parserRepServ(String JavaDoc _line)
170   {
171     System.out.println(_line) ;
172
173     //message
174
AbstractMessage msg = null ;
175
176     //splitte la reponse
177
servRep = new MessageRecuSplite(_line) ;
178
179     //devient vrai si la reponse a été traitée
180
boolean DejaTraite = false ;
181
182     //MESSAGE PRIVMSG
183
if (((String JavaDoc)(servRep.get(1))).equalsIgnoreCase("PRIVMSG"))
184     {
185       try
186       {
187         //DCC standard
188
if (servRep.get(3).toString().substring(2).equalsIgnoreCase("DCC"))
189         {
190           DCCin dcc = new DCCin(chatIRC.GetMainFrm(), chatIRC,_line) ;
191         }
192         else
193         {
194           msg = new MSGprivMsg(chatIRC, servRep.get(0), servRep.get(2), _line) ;
195         }
196       }
197       catch (StringIndexOutOfBoundsException JavaDoc ex)
198       {
199         msg = new MSGprivMsg(chatIRC, servRep.get(0), servRep.get(2), _line) ;
200       }
201       finally
202       {
203           DejaTraite = true ;
204       }
205     }
206
207     //COMMANDE PING pour le keepAlive, test 1er element
208
if (!DejaTraite && servRep.get(0).toString().equalsIgnoreCase("PING"))
209     {
210       //repondre
211
msg = new MSGpingpong(chatIRC, chatIRC.GetStatusFrm(), _line) ;
212
213       DejaTraite = true ;
214     }
215
216     //MESSAGE NICK test 2e element
217
if (!DejaTraite && ((String JavaDoc)(servRep.get(1))).equalsIgnoreCase("NICK"))
218     {
219       msg = new MSGnick(chatIRC, servRep.get(0).toString(), servRep.get(2).toString()) ;
220       DejaTraite = true ;
221     }
222
223     //MESSAGE JOIN test 2e element
224
if (!DejaTraite && ((String JavaDoc)(servRep.get(1))).equalsIgnoreCase("JOIN"))
225     {
226       msg = new MSGJoin(chatIRC, servRep.get(0).toString(), servRep.get(2).toString(), _line) ;
227       DejaTraite = true ;
228     }
229
230     //MESSAGE MODE test sur le 2e element
231
if (!DejaTraite && ((String JavaDoc)(servRep.get(1))).equalsIgnoreCase("MODE"))
232     {
233       try
234       { //mode user
235
msg = new MSGmode(chatIRC, servRep.get(0), servRep.get(1), servRep.get(2), servRep.get(3), servRep.get(4)) ;
236       }
237       catch (IndexOutOfBoundsException JavaDoc ex)
238       { //la c un mode chan
239
msg = new MSGmode(chatIRC, servRep.get(0), servRep.get(1), servRep.get(2), servRep.get(3), null) ;
240       }
241       finally
242       {
243         DejaTraite = true ;
244       }
245     }
246
247     //MESSAGE PART
248
if (!DejaTraite && ((String JavaDoc)(servRep.get(1))).equalsIgnoreCase("PART"))
249     {
250       msg = new MSGPart(chatIRC, servRep.get(0).toString(), servRep.get(2).toString(), _line) ;
251       msg.reagit() ;
252       DejaTraite = true ;
253     }
254
255     //MESSAGE QUIT
256
if (!DejaTraite && servRep.get(1).equals("QUIT"))
257     {
258       msg = new MSGquit(chatIRC, servRep.get(0).toString(), _line) ;
259       msg.reagit() ;
260       DejaTraite = true ;
261     }
262
263     //MESSAGE KICK
264
//:zumzum!~azuu@CB243DF0.CEE497DF.CA7F87DF.IP KICK #zuzutest azuu :pignoufle
265
//:zumzum!~azuu@CB243DF0.CEE497DF.CA7F87DF.IP KICK #zuzutest azuu :zumzum
266

267     if (!DejaTraite && servRep.get(1).equals("KICK"))
268     {
269       msg = new MSGkick(chatIRC, servRep.get(0), servRep.get(1), servRep.get(2), servRep.get(3), servRep.get(4)) ;
270       DejaTraite = true ;
271     }
272
273     //MESSAGE DE NOTICE test 2e element
274
if (!DejaTraite && servRep.get(1).equals("NOTICE"))
275     {
276
277       if (servRep.get(2).equals("AUTH"))
278       {
279         //message notice auth
280
msg = new MSGnoticeAuth(chatIRC, chatIRC.GetStatusFrm(), _line) ;
281
282       }
283       else
284       {
285         //notice simple dirigée
286
msg = new MSGnotice(chatIRC, chatIRC.GetStatusFrm(), _line) ;
287       }
288       DejaTraite = true ;
289     }
290
291     //MESSAGE CODES
292
if (!DejaTraite)
293     {
294       //sort le code du reply du serveur
295
replyCode = getReplyCode(_line) ;
296
297       //
298
//lance les commandes definies automatiquement au passage du code reponse 1
299
//
300
if (replyCode == 1)
301       {
302         for (int i = 0 ; i < OptionDialog.getOnConnectCommand().size() ; i++)
303         {
304           if (!OptionDialog.getOnConnectCommand().get(i).toString().equals(null))
305           {
306             chatIRC.sendCommand(OptionDialog.getOnConnectCommand().get(i).toString()) ;
307           }
308         }
309       }
310
311       //
312
//Traite le NAMES list
313
//
314

315       //la ligne de la reponse du NAMES list
316
if (!DejaTraite && replyCode == 353)
317       {
318         gere353(servRep, _line) ;
319         DejaTraite = true ;
320       }
321
322       //la fin du NAMES list
323
//quand on a le fin de liste on envoie ca a la chatframe concernee
324
if (!DejaTraite && replyCode == 366)
325       {
326         gere366(servRep, _line) ;
327         DejaTraite = true ;
328       }
329
330       //
331
//traite le listing de chan
332
//
333

334       //si code 321 on cree l'arraylist des chans
335
if (replyCode == 321)
336       {
337         DejaTraite = true ;
338       }
339
340       //si code 322 on ajoute les chans a l'arraylist
341
if (replyCode == 322)
342       {
343         DejaTraite = true ;
344         chatIRC.addChanToList(_line) ;
345       }
346
347       //si code 323 on envoie le end a IRCconnexion pour affichage
348
if (replyCode == 323)
349       {
350         DejaTraite = true ;
351         chatIRC.addChanToList("END") ;
352       }
353
354       //code du topic a l'entree sur un chan
355
if (replyCode == 332)
356       {
357         String JavaDoc chan = servRep.get(3).toString().replaceAll(":", "") ;
358         String JavaDoc msg1 = "" ;
359         for (int i = 0 ; i < chatIRC.getOpenChanArray().size() ; i++)
360         {
361           if (((ChatFrame)((chatIRC.getOpenChanArray().get(i)))).getName().equals(chan))
362           {
363             for (int j = 4 ; j < servRep.size() ; j++)
364             {
365               msg1 += servRep.get(j).toString() + " " ;
366             }
367             msg = new MSGtopic(chatIRC, ((ChatFrame)((chatIRC.getOpenChanArray().get(i)))), msg1) ;
368           }
369         }
370         DejaTraite = true ;
371       }
372
373       //
374
//Autre code
375
//
376

377       //code non géré, doit juste etre parsé
378
if (!DejaTraite && replyCode > 0)
379       {
380         msg = new MSGcodeNonGere(chatIRC, chatIRC.GetStatusFrm(), _line, replyCode) ;
381         DejaTraite = true ;
382       }
383
384       // afficher simplement
385
if (!DejaTraite)
386       {
387         msg = new MSGServer(chatIRC, chatIRC.GetStatusFrm(), _line) ;
388       }
389     }
390
391     //
392
//A présent, le message est identifié, faisons le nécessaire
393
//
394
if (msg != null)
395     {
396       msg.reagit() ;
397       msg.affiche() ;
398     }
399
400   }
401
402   //GEre le corps du name list (353)
403
private void gere353(MessageRecuSplite _split, String JavaDoc _line)
404   {
405     //:broadway.ny.us.dal.net 353 zuzu = #medan :@Neo__ @V-BoBo ritorron SAPU^Sun0S SAPU^LINUX
406

407     //
408
//Attention, ca se peut que les messages 353 consécutifs ne soient pas tous du meme chan
409
//
410

411     //chercher si on a une liste ouverte sur ce chan
412
String JavaDoc chan = (String JavaDoc)(_split.get(4)) ;
413
414     //indice de l'arraylist
415
int ind = -1 ;
416
417     //chercher si on a deja un arraylist de ce chan
418
for (int i = 0 ; i < userLists.size() ; i++)
419     {
420       if (((ArrayList)(userLists.get(i))).get(0).toString().equalsIgnoreCase(chan))
421       {
422         ind = i ;
423       }
424     }
425
426     ArrayList arr ;
427
428     //vérifier qu on a trouvé
429
if (ind == -1)
430     {
431       //créer un nouvel arraylist d'user
432
arr = new ArrayList() ;
433       arr.add(chan) ;
434       userLists.add(arr) ;
435     }
436     else
437     {
438       //utiliser l'array trouvé
439
arr = (ArrayList)(userLists.get(ind)) ;
440     }
441
442     //arr est a present l'arraylist qui contient les noms du chan concerné
443
arr.add(_line.substring(_line.indexOf(":", 5) + 1)) ;
444   }
445
446   //Gere la fin du name list (366)
447
private void gere366(MessageRecuSplite _split, String JavaDoc _line)
448   {
449     //:broadway.ny.us.dal.net 366 zuzu #medan :End of /NAMES list.
450

451     //chan concerné
452
String JavaDoc chan = (String JavaDoc)(_split.get(3)) ;
453
454     //indice de l'arraylist
455
int ind = -1 ;
456
457     //chercher si on a un arraylist de ce chan
458
for (int i = 0 ; i < userLists.size() ; i++)
459     {
460       if (((ArrayList)(userLists.get(i))).get(0).toString().equalsIgnoreCase(chan))
461       {
462         ind = i ;
463       }
464     }
465
466     ArrayList arr ;
467
468     //vérifier qu on a trouvé
469
if (ind != -1)
470     {
471       //créer un nouvel arraylist d'user
472
arr = (ArrayList)(userLists.get(ind)) ;
473
474       //chercher la fenetre du chan concerné
475
ChatFrame frm = chatIRC.GetFenetreDuChan(chan) ;
476
477       if (frm != null)
478       {
479         //balancer a la chatframe une chaine d'user complete
480
StringBuffer JavaDoc ret = new StringBuffer JavaDoc("") ;
481         for (int i = 1 ; i < arr.size() ; i++)
482         {
483           ret.append(" " + arr.get(i).toString()) ;
484         }
485
486         frm.addUserListInChan(new String JavaDoc(ret)) ;
487
488       }
489
490       //supprimer le arraylist utilisé, et cela que la fenetre existe ou non...
491
userLists.remove(arr) ;
492     }
493   }
494
495 //sort le codeServeur(int) de la ligne du reply
496
private int getReplyCode(String JavaDoc line)
497   {
498     int code = -1 ;
499
500     StringTokenizer str = new StringTokenizer(line, " ") ;
501     str.nextElement() ;
502     try
503     {
504       code = Integer.parseInt(str.nextElement().toString()) ;
505       //System.err.println(code) ;
506
}
507     catch (NumberFormatException JavaDoc e)
508     {
509       //e.printStackTrace() ;
510
}
511     return code ;
512   }
513
514   public void stopConnexion()
515   {
516     //enlever la connexion de la liste ident
517
if (il != null)
518     {
519       il.removeConnection(this.chatIRC) ;
520     }
521
522     chatIRC.sendCommand("QUIT " + chatIRC.getQuitMSG()) ;
523     loop = false ;
524   }
525 }
526
Popular Tags