1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
package org.eclipse.ecf.example.clients;
import org.eclipse.ecf.core.ContainerFactory;
import org.eclipse.ecf.core.IContainer;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.identity.IDFactory;
import org.eclipse.ecf.core.identity.IDInstantiationException;
import org.eclipse.ecf.core.identity.Namespace;
import org.eclipse.ecf.core.security.ConnectContextFactory;
import org.eclipse.ecf.core.util.ECFException;
import org.eclipse.ecf.presence.IMessageListener;
import org.eclipse.ecf.presence.IMessageSender;
import org.eclipse.ecf.presence.IPresenceContainer;
public class XMPPClient {
protected static String CONTAINER_TYPE = "ecf.xmpp.smack";
Namespace namespace = null;
IContainer container = null;
IPresenceContainer presence = null;
IMessageSender sender = null;
ID userID = null;
// Interface for receiving messages
IMessageReceiver receiver = null;
public XMPPClient() {
this(null);
}
public XMPPClient(IMessageReceiver receiver) {
super();
this.receiver = receiver;
}
public void connect(String account, String password) throws ECFException {
container = ContainerFactory.getDefault().createContainer(CONTAINER_TYPE);
namespace = container.getConnectNamespace();
ID targetID = IDFactory.getDefault().createID(namespace, account);
presence = (IPresenceContainer) container
.getAdapter(IPresenceContainer.class);
sender = presence.getMessageSender();
presence.addMessageListener(new IMessageListener() {
public void handleMessage(ID fromID, ID toID, Type type, String subject, String messageBody) {
if (receiver != null) {
receiver.handleMessage(fromID.getName(), messageBody);
}
}
});
// Now connect
container.connect(targetID,ConnectContextFactory.createPasswordConnectContext(password));
userID = getID(account);
}
private ID getID(String name) {
try {
return IDFactory.getDefault().createID(namespace, name);
} catch (IDInstantiationException e) {
e.printStackTrace();
return null;
}
}
public void sendMessage(String jid, String msg) {
if (sender != null) {
sender.sendMessage(userID, getID(jid),
IMessageListener.Type.NORMAL, "", msg);
}
}
public synchronized boolean isConnected() {
if (container == null) return false;
return (container.getConnectedID() != null);
}
public synchronized void close() {
if (container != null) {
container.dispose();
container = null;
presence = null;
sender = null;
receiver = null;
userID = null;
}
}
}
|