KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > claros > chat > threads > ChatSender


1 package org.claros.chat.threads;
2
3 import java.util.HashMap JavaDoc;
4 import java.util.List JavaDoc;
5
6 import org.claros.chat.controllers.QueueController;
7 import org.claros.chat.models.Queue;
8 import org.jivesoftware.smack.Chat;
9 import org.jivesoftware.smack.XMPPConnection;
10
11 /**
12  * @author Umut Gokbayrak
13  */

14 public class ChatSender extends Thread JavaDoc {
15     private String JavaDoc user;
16     private XMPPConnection conn;
17     private HashMap JavaDoc chatMap;
18     private boolean running;
19
20     /**
21      * Do not use this constructor
22      */

23     private ChatSender() {
24         super();
25     }
26
27     public ChatSender(String JavaDoc user, XMPPConnection conn) {
28         if (chatMap == null) {
29             chatMap = new HashMap JavaDoc();
30         }
31         this.user = user;
32         this.conn = conn;
33         this.running = true;
34     }
35
36     /**
37      * method to call to stop this thread
38      *
39      */

40     public void terminate() {
41         running = false;
42     }
43
44     /* (non-Javadoc)
45      * @see java.lang.Thread#run()
46      */

47     public void run() {
48         while (running) {
49             try {
50                 List JavaDoc msgs = QueueController.fetchUserMessages(user, QueueController.QUEUE_OUT);
51                 if (msgs != null) {
52                     Queue tmp = null;
53                     for (int i=0; i<msgs.size(); i++) {
54                         tmp = (Queue)msgs.get(i);
55                         
56                         Chat chat = (Chat)chatMap.get(tmp.getMsgTo());
57                         if (chat == null) {
58                             chat = conn.createChat(tmp.getMsgTo());
59                             chatMap.put(tmp.getMsgTo(), chat);
60                         }
61                         chat.sendMessage(tmp.getMsgBody());
62                     }
63                 }
64             } catch (Throwable JavaDoc e) {
65                 e.printStackTrace();
66             }
67             // sleep for a while and then go on;
68
try {
69                 Thread.sleep((long)(Math.random() * 1500L));
70             } catch (InterruptedException JavaDoc e1) {
71                 e1.printStackTrace();
72             }
73         }
74     }
75
76     /**
77      * creates a message and adds it to the send queue
78      * @param from
79      * @param to
80      * @param body
81      */

82     public void sendMessage(String JavaDoc to, String JavaDoc body) {
83         QueueController.push(QueueController.prepareName(user), to, body, QueueController.QUEUE_OUT);
84     }
85
86     public boolean isRunning() {
87         return running;
88     }
89
90     public void setRunning(boolean running) {
91         this.running = running;
92     }
93
94 }
95
Popular Tags