2 import org.opensrf.util.JSONWriter;
3 import org.opensrf.net.xmpp.*;
5 import java.util.HashMap;
6 import java.util.Arrays;
8 public abstract class Session {
10 /** Represents the different connection states for a session */
11 public enum ConnectState {
17 /** local cache of existing sessions */
18 private static Map<String, Session>
19 sessionCache = new HashMap<String, Session>();
21 /** the current connection state */
22 private ConnectState connectState;
24 /** The (jabber) address of the remote party we are communicating with */
25 private String remoteNode;
28 * The thread is used to link messages to a given session.
29 * In other words, each session has a unique thread, and all messages
30 * in that session will carry this thread around as an indicator.
32 private String thread;
35 connectState = ConnectState.DISCONNECTED;
39 * Sends a Message to our remoteNode.
41 public void send(Message omsg) throws SessionException {
43 /** construct the XMPP message */
44 XMPPMessage xmsg = new XMPPMessage();
45 xmsg.setTo(remoteNode);
46 xmsg.setThread(thread);
47 xmsg.setBody(new JSONWriter(Arrays.asList(new Message[] {omsg})).write());
48 XMPPSession ses = XMPPSession.getGlobalSession();
51 XMPPSession.getGlobalSession().send(xmsg);
52 } catch(XMPPException e) {
53 connectState = ConnectState.DISCONNECTED;
54 throw new SessionException("Error sending message to " + remoteNode, e);
59 * Waits for a message to arrive over the network and passes
60 * all received messages to the stack for processing
61 * @param millis The number of milliseconds to wait for a message to arrive
63 public static void waitForMessage(long millis) throws SessionException {
65 Stack.processXMPPMessage(
66 XMPPSession.getGlobalSession().recv(millis));
67 } catch(XMPPException e) {
68 throw new SessionException("Error waiting for message", e);
73 * Removes this session from the session cache.
75 public void cleanup() {
76 sessionCache.remove(thread);
80 * Searches for the cached session with the given thread.
81 * @param thread The session thread.
82 * @return The found session or null.
84 public static Session findCachedSession(String thread) {
85 return sessionCache.get(thread);
88 protected void cacheSession() {
89 sessionCache.put(thread, this);
92 public void setRemoteNode(String nodeName) {
93 remoteNode = nodeName;
95 public String getRemoteNode() {
102 * @return thread as String.
104 public String getThread() {
110 * @param thread the value to set.
112 public void setThread(String thread) {
113 this.thread = thread;
118 * @return connectState as ConnectState.
120 public ConnectState getConnectState() {
126 * @param connectState the value to set.
128 public void setConnectState(ConnectState connectState) {
129 this.connectState = connectState;