/** * Sends this response to all the passed channels as a {@link TextWebSocketFrame} * @param listener A channel future listener to attach to each channel future. Ignored if null. * @param channels The channels to send this response to * @return An array of the futures for the write of this response to each channel written to */ public ChannelFuture[] send(ChannelFutureListener listener, Channel...channels) { if(channels!=null && channels.length>0) { Set<ChannelFuture> futures = new HashSet<ChannelFuture>(channels.length); if(opCode==null) { opCode = "ok"; } TextWebSocketFrame frame = new TextWebSocketFrame(this.toChannelBuffer()); for(Channel channel: channels) { if(channel!=null && channel.isWritable()) { ChannelFuture cf = Channels.future(channel); if(listener!=null) cf.addListener(listener); channel.getPipeline().sendDownstream(new DownstreamMessageEvent(channel, cf, frame, channel.getRemoteAddress())); futures.add(cf); } } return futures.toArray(new ChannelFuture[futures.size()]); } return EMPTY_CHANNEL_FUTURE_ARR; }
@Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { HttpRequest request = (HttpRequest) msg; QueryStringDecoder decoder = new QueryStringDecoder(request.getUri()); DeviceSession deviceSession = getDeviceSession( channel, remoteAddress, decoder.getParameters().get("UserName").get(0)); if (deviceSession == null) { return null; } Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0)); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS)); position.setValid(true); position.setLatitude(parser.nextDouble(0)); position.setLongitude(parser.nextDouble(0)); position.setAltitude(parser.nextDouble(0)); position.setSpeed(parser.nextDouble(0)); position.setCourse(parser.nextDouble(0)); if (channel != null) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); channel.write(response).addListener(ChannelFutureListener.CLOSE); } return position; }
@Override public void handle(Channel channel, Token<DelegationTokenIdentifier> token, String serviceUrl) throws IOException { Assert.assertEquals(testToken, token); Credentials creds = new Credentials(); creds.addToken(new Text(serviceUrl), token); DataOutputBuffer out = new DataOutputBuffer(); creds.write(out); int fileLength = out.getData().length; ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength); cbuffer.writeBytes(out.getData()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(fileLength)); response.setContent(cbuffer); channel.write(response).addListener(ChannelFutureListener.CLOSE); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { super.messageReceived(ctx, e); System.out.println("-------- Server Channel messageRecieved " + System.currentTimeMillis()); if (induceError.get()) { System.out .println("Inducing Error in Server messageReceived method"); throw new IOException("Induced error "); } MessageEventBag bag = new MessageEventBag(); bag.setBytes(e); bagList.add(bag); ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(); buffer.writeInt(200); ChannelFuture future = e.getChannel().write(buffer); future.addListener(ChannelFutureListener.CLOSE); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { System.out.println("Server Exception Caught"); e.getCause().printStackTrace(); /** * Very important to respond here. * The agent will always be listening for some kind of feedback. */ ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(); buffer.writeInt(500); ChannelFuture future = e.getChannel().write(buffer); future.addListener(ChannelFutureListener.CLOSE); }
@Override public void messageReceived(ChannelHandlerContext context, MessageEvent messageEvent) throws Exception { context.getChannel().getPipeline().remove(this); Response response = (Response) context.getChannel().getAttachment(); if (response == null) { logger.debug("response is null"); HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, "0"); httpResponse.setContent(ChannelBuffers.EMPTY_BUFFER); httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); context.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE); return; } handleHttpResponse(context, response); }
/** * Writes the given body to Netty channel. Will <b>not</b >wait until the body has been written. * * @param log logger to use * @param channel the Netty channel * @param remoteAddress the remote address when using UDP * @param body the body to write (send) * @param exchange the exchange * @param listener listener with work to be executed when the operation is complete */ public static void writeBodyAsync(Logger log, Channel channel, SocketAddress remoteAddress, Object body, Exchange exchange, ChannelFutureListener listener) { ChannelFuture future; if (remoteAddress != null) { if (log.isDebugEnabled()) { log.debug("Channel: {} remote address: {} writing body: {}", new Object[]{channel, remoteAddress, body}); } future = channel.write(body, remoteAddress); } else { if (log.isDebugEnabled()) { log.debug("Channel: {} writing body: {}", new Object[]{channel, body}); } future = channel.write(body); } if (listener != null) { future.addListener(listener); } }
/** * Avoid channel double close * * @param channel */ void closeChannel(final Channel channel) { synchronized (this) { if (closingChannel.contains(channel)) { LOG.info(channel.toString() + " is already closed"); return ; } closingChannel.add(channel); } LOG.debug(channel.toString() + " begin to closed"); ChannelFuture closeFuture = channel.close(); closeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { synchronized (this) { closingChannel.remove(channel); } LOG.debug(channel.toString() + " finish closed"); } }); }
@Override public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) { //prevent javax.net.ssl.SSLException: Received close_notify during handshake final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class); if (sslHandler == null) { return; } final ChannelFuture handshakeFuture = sslHandler.handshake(); handshakeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (logger.isTraceEnabled()) { logger.trace("Node to Node encryption cipher is {}/{}", sslHandler.getEngine().getSession().getProtocol(), sslHandler .getEngine().getSession().getCipherSuite()); } ctx.sendUpstream(e); } }); }
/** * Avoid channel double close * * @param channel */ void closeChannel(final Channel channel) { synchronized (this) { if (closingChannel.contains(channel)) { LOG.info(channel.toString() + " is already closed"); return ; } closingChannel.add(channel); } LOG.debug(channel.toString() + " begin to closed"); ChannelFuture closeFuture = channel.close(); closeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { synchronized (this) { closingChannel.remove(channel); } LOG.debug(channel.toString() + " finish closed"); } }); }
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (buffer.readableBytes() < 2) { return null; } final int magic1 = buffer.getUnsignedByte(buffer.readerIndex()); final int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1); boolean isFlashPolicyRequest = (magic1 == '<' && magic2 == 'p'); if (isFlashPolicyRequest) { l.info("flash policy requested"); buffer.skipBytes(buffer.readableBytes()); // Discard everything channel.write(policyResponse).addListener(ChannelFutureListener.CLOSE); return null; } // Remove ourselves, important since the byte length check at top can hinder frame decoding // down the pipeline ctx.getPipeline().remove(this); return buffer.readBytes(buffer.readableBytes()); }
public void shutdown() { L4j.getL4j().info(SHUTDOWN); try { this.isShuttingDown = true; Channel channel = this.pipeline.getCurrentPipeline().getChannel(); this.channelFuture.getChannel().write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); L4j.getL4j().info(CLOSE_CHANNEL); channelFactory.releaseExternalResources(); L4j.getL4j().info(RELEASE_FACTORY); clientBootstrap.releaseExternalResources(); L4j.getL4j().info(RELEASE_CLIENT); } catch (Exception e) { L4j.getL4j().error(new StringBuilder(ERROR_CHANNEL).append(e.toString()).toString(), e); } }
/** * Avoid channel double close * * @param channel */ void closeChannel(final Channel channel) { synchronized (channelClosing) { if (closingChannel.contains(channel)) { LOG.info(channel.toString() + " is already closed"); return; } closingChannel.add(channel); } LOG.debug(channel.toString() + " begin to closed"); ChannelFuture closeFuture = channel.close(); closeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { synchronized (channelClosing) { closingChannel.remove(channel); } LOG.debug(channel.toString() + " finish closed"); } }); }
private void sendClosedPacket(Channel channel) { if (!channel.isConnected()) { logger.debug("channel already closed. skip sendClosedPacket() {}", channel); return; } logger.debug("write ClientClosePacket"); ClientClosePacket clientClosePacket = new ClientClosePacket(); ChannelFuture write = channel.write(clientClosePacket); write.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { logger.warn("ClientClosePacket write failed. channel:{}", future.getCause(), future.getCause()); } else { logger.debug("ClientClosePacket write success. channel:{}", future.getChannel()); } } }); write.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS); }
public SocketChannel(final Channel channel, long timeoutMillis, Timer timer) { if (channel == null) { throw new NullPointerException("channel"); } if (timer == null) { throw new NullPointerException("channel"); } this.channel = channel; this.timeoutMillis = timeoutMillis; this.timer = timer; this.requestManager = new RequestManager(this.timer); this.responseWriteFail = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { logger.warn("responseWriteFail. {}", channel); } } }; }
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { final Channel channel = e.getChannel(); logger.info("channelConnected channel:{}", channel); if (released) { logger.warn("already released. channel:{}", channel); channel.write(new ServerClosePacket()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { future.getChannel().close(); } }); return; } prepareChannel(channel); ChannelContext channelContext = getChannelContext(channel); boolean isIgnore = isIgnoreAddress(channel); if (!isIgnore) { channelContext.changeStateToRunWithoutHandshake(); } super.channelConnected(ctx, e); }
private void sendServerClosedPacket() { logger.info("sendServerClosedPacket start"); final ChannelGroupFuture write = this.channelGroup.write(new ServerClosePacket()); write.awaitUninterruptibly(5000, TimeUnit.MILLISECONDS); if (logger.isWarnEnabled()) { write.addListener(new ChannelGroupFutureListener() { private final ChannelFutureListener listener = new WriteFailFutureListener(logger, "serverClosePacket write fail", "serverClosePacket write success"); @Override public void operationComplete(ChannelGroupFuture future) throws Exception { for (ChannelFuture channelFuture : future) { channelFuture.addListener(listener); } } }); } logger.info("sendServerClosedPacket end"); }
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(NiftyClientConnector<T> clientChannelConnector, @Nullable Duration connectTimeout, @Nullable Duration receiveTimeout, @Nullable Duration readTimeout, @Nullable Duration sendTimeout, int maxFrameSize, @Nullable HostAndPort socksProxyAddress) { checkNotNull(clientChannelConnector, "clientChannelConnector is null"); ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress); bootstrap.setOptions(nettyClientConfig.getBootstrapOptions()); if (connectTimeout != null) { bootstrap.setOption("connectTimeoutMillis", connectTimeout.toMillis()); } bootstrap.setPipelineFactory(clientChannelConnector.newChannelPipelineFactory(maxFrameSize, nettyClientConfig)); ChannelFuture nettyChannelFuture = clientChannelConnector.connect(bootstrap); nettyChannelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Channel channel = future.getChannel(); if (channel != null && channel.isOpen()) { allChannels.add(channel); } } }); return new TNiftyFuture<>(clientChannelConnector, receiveTimeout, readTimeout, sendTimeout, nettyChannelFuture); }
private TNiftyFuture(final NiftyClientConnector<T> clientChannelConnector, @Nullable final Duration receiveTimeout, @Nullable final Duration readTimeout, @Nullable final Duration sendTimeout, final ChannelFuture channelFuture) { channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { if (future.isSuccess()) { Channel nettyChannel = future.getChannel(); T channel = clientChannelConnector.newThriftClientChannel(nettyChannel, nettyClientConfig); channel.setReceiveTimeout(receiveTimeout); channel.setReadTimeout(readTimeout); channel.setSendTimeout(sendTimeout); set(channel); } else if (future.isCancelled()) { if (!cancel(true)) { setException(new TTransportException("Unable to cancel client channel connection")); } } else { throw future.getCause(); } } catch (Throwable t) { setException(new TTransportException("Failed to connect client channel", t)); } } }); }
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) { // Generate an error page if response status code is not OK (200). if (res.getStatus().getCode() != 200) { res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8)); setContentLength(res, res.getContent().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.getChannel().write(res); if (!isKeepAlive(req) || (res.getStatus().getCode() != 200)) { f.addListener(ChannelFutureListener.CLOSE); } }
private void writeResponse(MessageEvent e) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8"); ChannelBuffer content = ChannelBuffers.dynamicBuffer(); Writer writer = new OutputStreamWriter(new ChannelBufferOutputStream(content), CharsetUtil.UTF_8); reportAdapter.toJson(report.get(), writer); try { writer.close(); } catch (IOException e1) { LOG.error("error writing resource report", e1); } response.setContent(content); ChannelFuture future = e.getChannel().write(response); future.addListener(ChannelFutureListener.CLOSE); }
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (buffer.readableBytes() < 2) { return null; } final int magic1 = buffer.getUnsignedByte(buffer.readerIndex()); final int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1); boolean isFlashPolicyRequest = (magic1 == '<' && magic2 == 'p'); if (isFlashPolicyRequest) { buffer.skipBytes(buffer.readableBytes()); // Discard everything channel.write(policyResponse).addListener(ChannelFutureListener.CLOSE); return null; } // Remove ourselves, important since the byte length check at top can hinder frame decoding // down the pipeline ctx.getPipeline().remove(this); return buffer.readBytes(buffer.readableBytes()); }
@Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) { final Channel inboundChannel = e.getChannel(); RtmpProxy.ALL_CHANNELS.add(inboundChannel); inboundChannel.setReadable(false); ClientBootstrap cb = new ClientBootstrap(cf); cb.getPipeline().addLast("handshaker", new ProxyHandshakeHandler()); cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel())); ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort)); outboundChannel = f.getChannel(); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.info("connected to remote host: {}, port: {}", remoteHost, remotePort); inboundChannel.setReadable(true); } else { inboundChannel.close(); } } }); }
private void connect( final NioClientSocketChannel channel, final ChannelFuture cf, SocketAddress remoteAddress) { try { if (channel.channel.connect(remoteAddress)) { channel.worker.register(channel, cf); } else { channel.getCloseFuture().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture f) throws Exception { if (!cf.isDone()) { cf.setFailure(new ClosedChannelException()); } } }); cf.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); channel.connectFuture = cf; nextBoss().register(channel, cf); } } catch (Throwable t) { cf.setFailure(t); fireExceptionCaught(channel, t); channel.worker.close(channel, succeededFuture(channel)); } }
public void close() { closeThread.execute(new Thread(){ public void run() { if (ch != null && ch.isWritable()) { ch.write(new CloseWebSocketFrame()); ChannelFuture closing = ch.getCloseFuture(); closing.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (ch != null) { ch.close(); } } }); } } }); }
@Override public void commit() { if (channel.isOpen()) { final ChannelFuture channelFuture; if (httpResponse.isChunked()) { if (log.isTraceEnabled()) { log.trace("Writing last chunk to {}", channel.getRemoteAddress()); } channelFuture = channel.write(new DefaultHttpChunkTrailer()); } else { // we don't chunk the response so we simply write it in one go. if (log.isTraceEnabled()) { log.trace("Writing entire {} bytes to client {}", httpResponse.getContent().readableBytes(), channel.getRemoteAddress()); } channelFuture = channel.write(httpResponse); } if (connectionClose) { log.debug("Closing connection to {}", channel.getRemoteAddress()); channelFuture.addListener(ChannelFutureListener.CLOSE); } else { channelFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } } }
@Override public void failure(Throwable error) { log.error("Uncaught exception in transport layer. This is likely a bug, closing channel.", error); if (channel.isOpen()) { if (channel.isWritable()) { final DefaultHttpResponse internalServerResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.INTERNAL_SERVER_ERROR); try { internalServerResponse.setContent(ChannelBuffers.wrappedBuffer(("Uncaught exception!\n" + error.getMessage()).getBytes("UTF-8"))); } catch (UnsupportedEncodingException ignored) {} channel.write(internalServerResponse).addListener(ChannelFutureListener.CLOSE); } else { channel.close(); } } }
public void invalidRequestSent(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel channel = ctx.getChannel(); if (channel == null || !channel.isOpen()) { log.debug("Not writing any response, channel is already closed.", e.getCause()); return; } final DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.BAD_REQUEST); response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); response.headers().add(HttpHeaders.Names.CONNECTION, "close"); final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(); new ChannelBufferOutputStream(buffer).writeBytes("Your client has sent a malformed or illegal request.\n"); response.setContent(buffer); final ChannelFuture channelFuture = channel.write(response); channelFuture.addListener(ChannelFutureListener.CLOSE); }
@Test public void multiple_connected_same_ip() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); verify(ctx, times(2)).sendUpstream(openEvent); verify(channel, times(1)).write(argThat(new ArgumentMatcher<Object>() { @Override public boolean matches(Object argument) { return QueryMessages.connectionsExceeded(MAX_CONNECTIONS_PER_IP).equals(argument); } })); verify(channelFuture, times(1)).addListener(ChannelFutureListener.CLOSE); verify(whoisLog).logQueryResult(anyString(), eq(0), eq(0), eq(QueryCompletionInfo.REJECTED), eq(0L), (InetAddress) Mockito.anyObject(), Mockito.anyInt(), eq("")); verify(ctx, times(2)).sendUpstream(openEvent); }
@Test public void multiple_connected_limit_disabled() throws Exception { subject.setMaxConnectionsPerIp(0); final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); final ChannelEvent closeEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.FALSE); subject.handleUpstream(ctx, closeEvent); subject.handleUpstream(ctx, closeEvent); subject.handleUpstream(ctx, closeEvent); verify(ctx, times(3)).sendUpstream(openEvent); verify(ctx, times(3)).sendUpstream(closeEvent); verify(channel, never()).close(); verify(channel, never()).write(anyObject()); verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE); }
@Test public void multiple_connected_unlimited_allowed() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(ipResourceConfiguration.isUnlimitedConnections(any(IpInterval.class))).thenReturn(true); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent event = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, event); subject.handleUpstream(ctx, event); subject.handleUpstream(ctx, event); verify(ctx, times(3)).sendUpstream(event); verify(channel, never()).close(); verify(channel, never()).write(anyObject()); verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE); }
@Test public void multiple_connected_proxy_allowed() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(ipResourceConfiguration.isProxy(any(IpInterval.class))).thenReturn(true); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent event = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, event); subject.handleUpstream(ctx, event); subject.handleUpstream(ctx, event); verify(ctx, times(3)).sendUpstream(event); verify(channel, never()).close(); verify(channel, never()).write(anyObject()); verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE); }
@Test public void multiple_connected_different_ip() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); final InetSocketAddress remoteAddress2 = new InetSocketAddress("10.0.0.1", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress).thenReturn(remoteAddress).thenReturn(remoteAddress2); final ChannelEvent event = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, event); subject.handleUpstream(ctx, event); final ChannelEvent event2 = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, event2); verify(ctx, times(2)).sendUpstream(event); verify(ctx, times(1)).sendUpstream(event2); verify(channel, never()).close(); verify(channel, never()).write(anyObject()); verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE); }
@Test public void multiple_connected_same_ip_and_closed() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); final ChannelEvent closeEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.FALSE); subject.handleUpstream(ctx, closeEvent); subject.handleUpstream(ctx, closeEvent); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); verify(ctx, times(4)).sendUpstream(openEvent); verify(ctx, times(2)).sendUpstream(closeEvent); verify(channel, never()).close(); verify(channel, never()).write(anyObject()); verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE); }