|
| 1 | +package com.kttdevelopment.simplehttpserver.handler; |
| 2 | + |
| 3 | +import com.kttdevelopment.simplehttpserver.SimpleHttpServer; |
| 4 | +import com.sun.net.httpserver.HttpExchange; |
| 5 | + |
| 6 | +import java.util.concurrent.atomic.AtomicInteger; |
| 7 | +import java.util.function.Predicate; |
| 8 | + |
| 9 | +public class ConnectionThrottler { |
| 10 | + |
| 11 | + private final SimpleHttpServer server; |
| 12 | + |
| 13 | + private final Predicate<HttpExchange> contributeToLimit; |
| 14 | + private final AtomicInteger connections = new AtomicInteger(0); |
| 15 | + |
| 16 | + private int maxConnections = 0; |
| 17 | + |
| 18 | + public ConnectionThrottler(final SimpleHttpServer server){ |
| 19 | + this.server = server; |
| 20 | + contributeToLimit = (exchange) -> true; |
| 21 | + } |
| 22 | + |
| 23 | + public ConnectionThrottler(final SimpleHttpServer server, final Predicate<HttpExchange> counts){ |
| 24 | + this.server = server; |
| 25 | + this.contributeToLimit = counts; |
| 26 | + } |
| 27 | + |
| 28 | + |
| 29 | + public synchronized final boolean addConnection(final HttpExchange exchange){ |
| 30 | + if(!contributeToLimit.test(exchange)){ |
| 31 | + return true; |
| 32 | + }else if(connections.get() + 1 <= maxConnections){ |
| 33 | + connections.incrementAndGet(); |
| 34 | + return true; |
| 35 | + } |
| 36 | + return false; |
| 37 | + } |
| 38 | + |
| 39 | + public synchronized final void deleteConnection(final HttpExchange exchange){ |
| 40 | + if(contributeToLimit.test(exchange)) |
| 41 | + connections.decrementAndGet(); |
| 42 | + } |
| 43 | + |
| 44 | + // |
| 45 | + |
| 46 | + |
| 47 | + @Override |
| 48 | + public String toString(){ |
| 49 | + final StringBuilder OUT = new StringBuilder(); |
| 50 | + |
| 51 | + OUT.append("ConnectionThrottler") .append('{'); |
| 52 | + OUT.append("server") .append('=') .append(server.toString()) .append(", "); |
| 53 | + OUT.append("connections") .append('=') .append(connections) .append(", "); |
| 54 | + OUT.append("maxConnections") .append('=') .append(maxConnections); |
| 55 | + OUT.append('}'); |
| 56 | + |
| 57 | + return OUT.toString(); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments