01: package org.claros.chat.threads;
02:
03: import java.util.HashMap;
04: import java.util.List;
05:
06: import org.claros.chat.controllers.QueueController;
07: import org.claros.chat.models.Queue;
08: import org.jivesoftware.smack.Chat;
09: import org.jivesoftware.smack.XMPPConnection;
10:
11: /**
12: * @author Umut Gokbayrak
13: */
14: public class ChatSender extends Thread {
15: private String user;
16: private XMPPConnection conn;
17: private HashMap chatMap;
18: private boolean running;
19: private String defaultDomain;
20:
21: /**
22: * Do not use this constructor
23: */
24: private ChatSender() {
25: super ();
26: }
27:
28: public ChatSender(String user, XMPPConnection conn,
29: String defaultDomain) {
30: if (chatMap == null) {
31: chatMap = new HashMap();
32: }
33: this .user = user;
34: this .conn = conn;
35: this .running = true;
36: this .defaultDomain = defaultDomain;
37: }
38:
39: /**
40: * method to call to stop this thread
41: *
42: */
43: public void terminate() {
44: running = false;
45: }
46:
47: /* (non-Javadoc)
48: * @see java.lang.Thread#run()
49: */
50: public void run() {
51: while (running) {
52: try {
53: List msgs = QueueController.fetchUserMessages(user,
54: QueueController.QUEUE_OUT, defaultDomain);
55: if (msgs != null) {
56: Queue tmp = null;
57: for (int i = 0; i < msgs.size(); i++) {
58: tmp = (Queue) msgs.get(i);
59:
60: Chat chat = (Chat) chatMap.get(tmp.getMsgTo());
61: if (chat == null) {
62: chat = conn.createChat(tmp.getMsgTo());
63: chatMap.put(tmp.getMsgTo(), chat);
64: }
65: chat.sendMessage(tmp.getMsgBody());
66: }
67: }
68: } catch (Throwable e) {
69: e.printStackTrace();
70: }
71: // sleep for a while and then go on;
72: try {
73: Thread.sleep((long) (Math.random() * 1500L));
74: } catch (InterruptedException e1) {
75: e1.printStackTrace();
76: }
77: }
78: }
79:
80: /**
81: * creates a message and adds it to the send queue
82: * @param from
83: * @param to
84: * @param body
85: */
86: public void sendMessage(String to, String body) {
87: QueueController.push(QueueController.prepareName(user,
88: defaultDomain), to, body, QueueController.QUEUE_OUT);
89: }
90:
91: public boolean isRunning() {
92: return running;
93: }
94:
95: public void setRunning(boolean running) {
96: this.running = running;
97: }
98:
99: }
|