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:
20: /**
21: * Do not use this constructor
22: */
23: private ChatSender() {
24: super ();
25: }
26:
27: public ChatSender(String user, XMPPConnection conn) {
28: if (chatMap == null) {
29: chatMap = new HashMap();
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 msgs = QueueController.fetchUserMessages(user,
51: QueueController.QUEUE_OUT);
52: if (msgs != null) {
53: Queue tmp = null;
54: for (int i = 0; i < msgs.size(); i++) {
55: tmp = (Queue) msgs.get(i);
56:
57: Chat chat = (Chat) chatMap.get(tmp.getMsgTo());
58: if (chat == null) {
59: chat = conn.createChat(tmp.getMsgTo());
60: chatMap.put(tmp.getMsgTo(), chat);
61: }
62: chat.sendMessage(tmp.getMsgBody());
63: }
64: }
65: } catch (Throwable e) {
66: e.printStackTrace();
67: }
68: // sleep for a while and then go on;
69: try {
70: Thread.sleep((long) (Math.random() * 1500L));
71: } catch (InterruptedException e1) {
72: e1.printStackTrace();
73: }
74: }
75: }
76:
77: /**
78: * creates a message and adds it to the send queue
79: * @param from
80: * @param to
81: * @param body
82: */
83: public void sendMessage(String to, String body) {
84: QueueController.push(QueueController.prepareName(user), to,
85: body, QueueController.QUEUE_OUT);
86: }
87:
88: public boolean isRunning() {
89: return running;
90: }
91:
92: public void setRunning(boolean running) {
93: this.running = running;
94: }
95:
96: }
|