}
SSLSelectorHandler createTLSEndpoint(InetSocketAddress addr) {
int linger = -1;
final SSLSelectorHandler selectorHandler = new SSLSelectorHandler() {
/**
* Intercept the accept operations and cache the associated
* connection. This is duplication of code from the TCPSelectorhandler
* above. TODO to refactor this.
*/
@Override
public boolean onAcceptInterest(SelectionKey key, Context ctx)
throws IOException {
try {
SelectableChannel channel = acceptWithoutRegistration(key);
if (channel != null) {
configureChannel(channel);
SelectionKey readKey = channel.register(selector,
SelectionKey.OP_READ);
// Cache the connection.
TargetTuple tt = connectionManager.add(readKey, this);
outboundConnectionsTuple.put(readKey, tt);
}
} catch (Exception e) {
if (logger.isLoggable(Level.FINE)){
logger.log(Level.FINE, "Exception onAccept ", e);
}
}
return false;
}
@Override
protected void onConnectOp(Context ctx,
SelectionKeyOP.ConnectSelectionKeyOP selectionKeyOp)
throws IOException {
try {
SocketAddress remoteAddress =
selectionKeyOp.getRemoteAddress();
SocketAddress localAddress =
selectionKeyOp.getLocalAddress();
CallbackHandler callbackHandler =
selectionKeyOp.getCallbackHandler();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.socket().setReuseAddress(reuseAddress);
if (localAddress != null) {
socketChannel.socket().bind(localAddress);
}
socketChannel.configureBlocking(false);
SelectionKey key = socketChannel.register(selector,
SelectionKey.OP_CONNECT);
key.attach(ExpiringCallbackHandlerSelectionKeyAttachment.create(
key, callbackHandler));
boolean isConnected;
try {
isConnected = socketChannel.connect(remoteAddress);
} catch (Exception e) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"Exception occured when tried to connect socket",
e.getMessage());
}
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST,
"Exception occured when tried to connect socket",
e);
}
// set isConnected to true to let callback handler to know about the problem happened
isConnected = true;
}
// if channel was connected immediately or exception occured
if (isConnected) {
onConnectInterest(key, ctx);
}
} catch (Exception e) {
if (logger.isLoggable(Level.FINE)){
logger.log(Level.FINE, "Exception on connect ", e);
}
if (logger.isLoggable(Level.FINEST)){
logger.log(Level.FINEST, "Exception on connect ",
e.getMessage());
}
}
}
};
selectorHandler.setPort(addr.getPort());
selectorHandler.setInet(addr.getAddress());
selectorHandler.setLinger(linger);
selectorHandler.setLogger(logger);
selectorHandler.setReuseAddress(true);
selectorHandler.setSocketTimeout(keepAliveTimeoutInSeconds * 1000);
return selectorHandler;
}