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 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());
50 XMPPSession.getThreadSession().send(xmsg);
51 } catch(XMPPException e) {
52 connectState = ConnectState.DISCONNECTED;
53 throw new SessionException("Error sending message to " + remoteNode, e);
58 * Waits for a message to arrive over the network and passes
59 * all received messages to the stack for processing
60 * @param millis The number of milliseconds to wait for a message to arrive
62 public static void waitForMessage(long millis) throws SessionException, MethodException {
64 Stack.processXMPPMessage(
65 XMPPSession.getThreadSession().recv(millis));
66 } catch(XMPPException e) {
67 throw new SessionException("Error waiting for message", e);
72 * Removes this session from the session cache.
74 public void cleanup() {
75 sessionCache.remove(thread);
79 * Searches for the cached session with the given thread.
80 * @param thread The session thread.
81 * @return The found session or null.
83 public static Session findCachedSession(String thread) {
84 return sessionCache.get(thread);
88 * Puts this session into session cache.
90 protected void cacheSession() {
91 sessionCache.put(thread, this);
95 * Sets the remote address
96 * @param nodeName The name of the remote node.
98 public void setRemoteNode(String nodeName) {
99 remoteNode = nodeName;
102 * @return The remote node
104 public String getRemoteNode() {
111 * @return thread as String.
113 public String getThread() {
119 * @param thread the value to set.
121 public void setThread(String thread) {
122 this.thread = thread;
127 * @return connectState as ConnectState.
129 public ConnectState getConnectState() {
135 * @param connectState the value to set.
137 public void setConnectState(ConnectState connectState) {
138 this.connectState = connectState;