package net.tomp2p.connection;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is a soft limit, as there is no way to drop a connection before creating
 * a socket from Java. This handler counts the incoming connections and drops the
 * connection if a certain limit is reached.
 * 
 * @author Thomas Bocek
 * 
 */
@Sharable
public class DropConnectionInboundHandler extends ChannelInboundHandlerAdapter {

	private static final Logger LOG = LoggerFactory.getLogger(DropConnectionInboundHandler.class);
	private final AtomicInteger counter = new AtomicInteger();
	final int limit;

	public DropConnectionInboundHandler(int limit) {
		this.limit = limit;
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		int current = -1;
		if ((current = counter.incrementAndGet()) > limit) {
			ctx.channel().close();
			LOG.warn("dropped connection because: " + current +" > " + limit +" connections active");
		} else {
			ctx.fireChannelRegistered();
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		counter.decrementAndGet();
		ctx.fireChannelInactive();
	}
}

@@ -1108,74 +1108,61 @@
 ause
-: %22 + current +%22 %3E %22 + limit +%22 connections active%22);%0A%09%09%7D else %7B%0A%09
+ %7B%7D %3E %7B%7D connections active.%22,  current, limit);%0A%09%09%7D%0A
 %09%09ct
@@ -1188,20 +1188,16 @@
 ered();%0A
-%09%09%7D%0A
 %09%7D%0A%0A%09@Ov

remove redundant else-block