From 8600bf9ae5426f3d0781a2666f53b5ba0c1e7dcb Mon Sep 17 00:00:00 2001 From: Fabrice Bacchella Date: Wed, 20 Jun 2018 23:52:22 +0200 Subject: [PATCH] channel().localAddress() not always return an InetSocketAddress, for example during unit tests. So check they are the right type before type cast. --- .../java/org/logstash/beats/BeatsHandler.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/logstash/beats/BeatsHandler.java b/src/main/java/org/logstash/beats/BeatsHandler.java index 8120aa0d..31e9be69 100644 --- a/src/main/java/org/logstash/beats/BeatsHandler.java +++ b/src/main/java/org/logstash/beats/BeatsHandler.java @@ -7,6 +7,8 @@ import org.apache.logging.log4j.Logger; import java.net.InetSocketAddress; +import java.net.SocketAddress; + import javax.net.ssl.SSLHandshakeException; public class BeatsHandler extends SimpleChannelInboundHandler { @@ -114,23 +116,21 @@ private void writeAck(ChannelHandlerContext ctx, byte protocol, int sequence) { * we will use similar logic than Netty's LoggingHandler */ private String format(String message) { - InetSocketAddress local = (InetSocketAddress) context.channel().localAddress(); - InetSocketAddress remote = (InetSocketAddress) context.channel().remoteAddress(); - - String localhost; - if(local != null) { - localhost = local.getAddress().getHostAddress() + ":" + local.getPort(); - } else{ - localhost = "undefined"; - } + SocketAddress local = context.channel().localAddress(); + SocketAddress remote = context.channel().remoteAddress(); - String remotehost; - if(remote != null) { - remotehost = remote.getAddress().getHostAddress() + ":" + remote.getPort(); - } else{ - remotehost = "undefined"; - } + String localhost = addressToString(local); + String remotehost = addressToString(remote); return "[local: " + localhost + ", remote: " + remotehost + "] " + message; } + + private String addressToString(SocketAddress saddr) { + if (saddr instanceof InetSocketAddress) { + InetSocketAddress inetaddr = (InetSocketAddress) saddr; + return inetaddr.getAddress().getHostAddress() + ":" + inetaddr.getPort(); + } else { + return "undefined"; + } + } }