// ZMQ.NORMAL|senderUrl|tokenJson|body
// ZMQ.HANDSHAKE|senderUrl|tokenJson|timestamp
// ZMQ.HANDSHAKE_RESPONSE|senderUrl|tokenJson|null
final URI senderUrl = new URI(new String(msg[1].array()));
final TokenRet token = JOM.getInstance().readValue(msg[2].array(),
TokenRet.class);
final String body = new String(msg[3].array());
final String key = senderUrl + ":" + token.getToken();
if (Arrays.equals(msg[0].array(), ZMQ.HANDSHAKE)) {
// Reply token corresponding to timestamp.
final String res = TokenStore.get(body);
service.sendAsync(ZMQ.HANDSHAKE_RESPONSE, res, zmqUrl, senderUrl,
res, null);
return;
} else if (Arrays.equals(msg[0].array(), ZMQ.HANDSHAKE_RESPONSE)) {
// post response to callback for handling by other thread
final AsyncCallbackQueue<String> callbacks = host.getCallbackQueue(
"zmqHandshakes", String.class);
AsyncCallback<String> callback = callbacks.pull(key);
if (callback != null) {
callback.onSuccess(body);
} else {
LOG.warning("Received ZMQ.HANDSHAKE_RESPONSE for unknown handshake..."
+ senderUrl + " : " + token);
}
return;
} else {
final ObjectCache sessionCache = ObjectCache.get("ZMQSessions");
if (!sessionCache.containsKey(key)
&& host.getAgent(agentId).hasPrivate()) {
final AsyncCallbackQueue<String> callbacks = host
.getCallbackQueue("zmqHandshakes", String.class);
SyncCallback<String> callback = new SyncCallback<String>();
callbacks.push(key, "", callback);
service.sendAsync(ZMQ.HANDSHAKE, token.toString(), zmqUrl,
senderUrl, token.getTime(), null);
String retToken = null;
try {
retToken = callback.get();
} catch (Exception e) {
}
if (token.getToken().equals(retToken)) {
sessionCache.put(key, true);
} else {
LOG.warning("Failed to complete handshake!");
return;
}