MySQLNegotiateHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { if (msg instanceof MySQLHandshakePacket) { MySQLHandshakePacket handshake = (MySQLHandshakePacket) msg; MySQLHandshakeResponse41Packet handshakeResponsePacket = new MySQLHandshakeResponse41Packet(1, MAX_PACKET_SIZE, CHARACTER_SET, username); handshakeResponsePacket.setAuthResponse(generateAuthResponse(handshake.getAuthPluginData().getAuthPluginData())); handshakeResponsePacket.setCapabilityFlags(generateClientCapability()); handshakeResponsePacket.setDatabase("mysql"); handshakeResponsePacket.setAuthPluginName(MySQLAuthenticationMethod.SECURE_PASSWORD_AUTHENTICATION); ctx.channel().writeAndFlush(handshakeResponsePacket); serverInfo = new ServerInfo(); serverInfo.setServerVersion(new ServerVersion(handshake.getServerVersion())); return; } if (msg instanceof MySQLOKPacket) { ctx.channel().pipeline().remove(this); authResultCallback.setSuccess(serverInfo); return; } MySQLErrPacket error = (MySQLErrPacket) msg; ctx.channel().close(); throw new RuntimeException(error.getErrorMessage()); }  @Override void channelRead(final ChannelHandlerContext ctx, final Object msg);  }
@Test public void assertChannelReadHandshakeInitPacket() throws NoSuchFieldException, IllegalAccessException { MySQLHandshakePacket handshakePacket = new MySQLHandshakePacket(0, new MySQLAuthPluginData(new byte[8], new byte[12])); handshakePacket.setAuthPluginName(MySQLAuthenticationMethod.SECURE_PASSWORD_AUTHENTICATION); mysqlNegotiateHandler.channelRead(channelHandlerContext, handshakePacket); verify(channel).writeAndFlush(ArgumentMatchers.any(MySQLHandshakeResponse41Packet.class)); ServerInfo serverInfo = ReflectionUtil.getFieldValueFromClass(mysqlNegotiateHandler, "serverInfo", ServerInfo.class); assertThat(serverInfo.getServerVersion().getMajor(), is(8)); assertThat(serverInfo.getServerVersion().getMinor(), is(0)); assertThat(serverInfo.getServerVersion().getSeries(), is(20)); }
@Test public void assertChannelReadOkPacket() throws NoSuchFieldException, IllegalAccessException { MySQLOKPacket okPacket = new MySQLOKPacket(0); ServerInfo serverInfo = new ServerInfo(); ReflectionUtil.setFieldValueToClass(mysqlNegotiateHandler, "serverInfo", serverInfo); mysqlNegotiateHandler.channelRead(channelHandlerContext, okPacket); verify(pipeline).remove(mysqlNegotiateHandler); verify(authResultCallback).setSuccess(serverInfo); }
@Test(expected = RuntimeException.class) public void assertChannelReadErrorPacket() { MySQLErrPacket errorPacket = new MySQLErrPacket(0, MySQLServerErrorCode.ER_NO_DB_ERROR); mysqlNegotiateHandler.channelRead(channelHandlerContext, errorPacket); }