001: package org.claros.chat.threads;
002:
003: import java.util.HashMap;
004: import java.util.List;
005:
006: import org.claros.chat.controllers.QueueController;
007: import org.claros.chat.models.Queue;
008: import org.jivesoftware.smack.Chat;
009: import org.jivesoftware.smack.MessageListener;
010: import org.jivesoftware.smack.XMPPConnection;
011: import org.jivesoftware.smack.packet.Message;
012:
013: /**
014: * @author Umut Gokbayrak
015: */
016: public class ChatSender extends Thread {
017: private String user;
018: private XMPPConnection conn;
019: private HashMap chatMap;
020: private boolean running;
021: private String defaultDomain;
022:
023: /**
024: * Do not use this constructor
025: */
026: @SuppressWarnings("unused")
027: private ChatSender() {
028: super ();
029: }
030:
031: public ChatSender(String user, XMPPConnection conn,
032: String defaultDomain) {
033: if (chatMap == null) {
034: chatMap = new HashMap();
035: }
036: this .user = user;
037: this .conn = conn;
038: this .running = true;
039: this .defaultDomain = defaultDomain;
040: }
041:
042: /**
043: * method to call to stop this thread
044: *
045: */
046: public void terminate() {
047: running = false;
048: }
049:
050: /* (non-Javadoc)
051: * @see java.lang.Thread#run()
052: */
053: public void run() {
054: while (running) {
055: try {
056: List msgs = QueueController.fetchUserMessages(user,
057: QueueController.QUEUE_OUT, defaultDomain);
058: if (msgs != null) {
059: Queue tmp = null;
060: for (int i = 0; i < msgs.size(); i++) {
061: tmp = (Queue) msgs.get(i);
062:
063: Chat chat = (Chat) chatMap.get(tmp.getMsgTo());
064: if (chat == null) {
065: chat = conn.getChatManager().createChat(
066: tmp.getMsgTo(),
067: new MessageListener() {
068: public void processMessage(
069: Chat ch, Message msg) {
070: System.out.println("msg: "
071: + msg);
072: }
073: });
074: chatMap.put(tmp.getMsgTo(), chat);
075: }
076: chat.sendMessage(tmp.getMsgBody());
077: }
078: }
079: } catch (Throwable e) {
080: e.printStackTrace();
081: }
082: // sleep for a while and then go on;
083: try {
084: Thread.sleep((long) (Math.random() * 1500L));
085: } catch (InterruptedException e1) {
086: e1.printStackTrace();
087: }
088: }
089: }
090:
091: /**
092: * creates a message and adds it to the send queue
093: * @param from
094: * @param to
095: * @param body
096: */
097: public void sendMessage(String to, String body) {
098: QueueController.push(QueueController.prepareName(user,
099: defaultDomain), to, body, QueueController.QUEUE_OUT);
100: }
101:
102: public boolean isRunning() {
103: return running;
104: }
105:
106: public void setRunning(boolean running) {
107: this.running = running;
108: }
109:
110: }
|