Skip to content

Instantly share code, notes, and snippets.

Created November 18, 2014 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/000c1f987f3d484c8927 to your computer and use it in GitHub Desktop.
Save anonymous/000c1f987f3d484c8927 to your computer and use it in GitHub Desktop.
import java.io.File
import java.net.ConnectException
import javax.net.ssl.SSLException
import com.typesafe.scalalogging.Logger
import org.jboss.netty.channel._
import org.jboss.netty.handler.codec.frame.LineBasedFrameDecoder
import org.jboss.netty.handler.codec.string.{StringDecoder, StringEncoder}
import org.jboss.netty.handler.ssl.SslHandler
import org.slf4j.LoggerFactory
class ClientPipelineFactory(certFileDir: String, password: String) extends ChannelPipelineFactory {
def getPipeline = {
val pipeline = Channels.pipeline()
val clientKeyStore = new File(s"$certFileDir/client.keystore")
val clientTrustStore = new File(s"$certFileDir/client.truststore")
val sslManager = new SslManager(clientKeyStore, clientTrustStore, password, password)
val engine = sslManager.createSSLEngine(client = true)
pipeline.addLast("ssl", new SslHandler(engine))
pipeline.addLast("framer", new LineBasedFrameDecoder(8192, true, false))
pipeline.addLast("decoder", new StringDecoder())
pipeline.addLast("encoder", new StringEncoder())
pipeline.addLast("handler", new ClientHandler())
pipeline
}
}
class ClientHandler extends SimpleChannelUpstreamHandler {
val logger = Logger(LoggerFactory.getLogger("client"))
override def channelConnected(ctx: ChannelHandlerContext, e: ChannelStateEvent) {
// Get the SslHandler from the pipeline
val sslHandler = ctx.getPipeline.get(classOf[SslHandler])
// Begin handshake.
val handshakeFuture: ChannelFuture = sslHandler.handshake()
handshakeFuture.addListener(new SecureConnectionEstablishedListener())
()
}
override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent) {
e.getCause match {
case ce: ConnectException =>
logger.warn(s"connection failed with message: ${ce.getMessage}")
case ssl: SSLException =>
logger.warn(s"failed to establish secure connection with message: ${ssl.getMessage}")
case oe =>
logger.warn("exception caught", oe)
e.getChannel.close()
()
}
}
class SecureConnectionEstablishedListener extends ChannelFutureListener {
def operationComplete(future: ChannelFuture) {
if (future.isSuccess) {
logger.info(s"channel from ${future.getChannel.getRemoteAddress} connected")
// You can start communicating
}
else {
// SSLException handled in exceptionCaught
future.getChannel.close()
()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment