From a47bcc8cf49281034035b0f0fbdbc8972cb9cbee Mon Sep 17 00:00:00 2001 From: Aayush Atharva Date: Mon, 15 Jul 2024 02:21:56 +0530 Subject: [PATCH] Cleanup (#174) --- .../expressgateway/backend/Connection.java | 49 ++++++++++++----- .../expressgateway/backend/Node.java | 9 ++-- .../backend/NodeBytesTracker.java | 16 +++--- .../expressgateway/backend/State.java | 4 ++ .../backend/cluster/Cluster.java | 10 ++-- .../backend/cluster/ClusterBuilder.java | 9 ++-- .../cluster/ClusterOnlineNodesWorker.java | 8 +-- .../backend/events/node/NodeEvent.java | 2 +- .../exceptions/LoadBalanceException.java | 6 ++- .../exceptions/NoNodeAvailableException.java | 8 ++- .../TooManyConnectionsException.java | 5 ++ .../healthcheck/HealthCheckRunner.java | 3 +- .../healthcheck/HealthCheckTemplate.java | 16 +++--- .../backend/loadbalance/LoadBalance.java | 2 +- .../backend/loadbalance/Request.java | 2 +- .../backend/loadbalance/Response.java | 2 +- .../backend/strategy/l4/L4Balance.java | 2 +- .../backend/strategy/l4/L4Request.java | 2 - .../backend/strategy/l4/Random.java | 4 +- .../l4/sessionpersistence/FourTupleHash.java | 3 +- .../l4/sessionpersistence/SourceIPHash.java | 8 +-- .../backend/strategy/l7/http/HTTPBalance.java | 2 +- .../strategy/l7/http/HTTPBalanceRequest.java | 1 + .../backend/strategy/l7/http/HTTPRandom.java | 4 +- .../sessionpersistence/StickySession.java | 2 +- .../StickySessionSearchComparator.java | 6 ++- .../healthcheck/HealthCheckServiceTest.java | 2 +- .../strategy/l4/LeastConnectionTest.java | 4 -- .../backend/strategy/l4/LeastLoadTest.java | 4 -- .../backend/strategy/l4/RandomTest.java | 7 +-- .../backend/strategy/l4/RoundRobinTest.java | 2 +- .../sessionpersistence/SourceIPHashTest.java | 2 +- .../strategy/l7/http/HTTPRandomTest.java | 7 +-- .../strategy/l7/http/HTTPRoundRobinTest.java | 2 +- .../sessionpersistence/StickySessionTest.java | 2 +- .../expressgateway/bootstrap/Bootstrap.java | 4 ++ .../expressgateway/common/crypto/Hasher.java | 5 +- .../expressgateway/common/crypto/Keypair.java | 7 ++- .../common/crypto/PrivateKeyUtil.java | 2 +- .../expressgateway/common/map/Cleaner.java | 2 +- .../common/map/DefaultCleaner.java | 2 +- .../common/map/ExpiringMap.java | 8 +-- .../expressgateway/common/utils/Hex.java | 4 ++ .../expressgateway/common/utils/ListUtil.java | 4 ++ .../expressgateway/common/utils/MathUtil.java | 4 ++ .../common/utils/NetworkInterfaceUtil.java | 4 ++ .../common/utils/NetworkUtil.java | 2 +- .../common/utils/NumberUtil.java | 12 ++--- .../common/utils/ObjectUtils.java | 19 +++++++ .../common/utils/ReferenceCountedUtil.java | 2 +- .../common/utils/StringUtil.java | 6 ++- .../zookeeper/CertificateManagerTest.java | 2 +- .../common/zookeeper/CuratorUtilsTest.java | 6 --- .../ExpressGatewayCustomizedUtil.java | 6 ++- .../eventstream/AsyncEventStream.java | 2 +- .../eventstream/AsyncEventStreamTest.java | 2 +- .../eventstream/EventStreamTest.java | 2 +- .../configuration/Configuration.java | 2 +- .../configuration/ConfigurationContext.java | 17 ------ .../buffer/BufferConfiguration.java | 2 +- .../eventloop/EventLoopConfiguration.java | 3 +- .../eventstream/EventStreamConfiguration.java | 3 +- .../healthcheck/HealthCheckConfiguration.java | 3 +- .../configuration/http/HttpConfiguration.java | 3 +- .../configuration/tls/CertificateKeyPair.java | 5 +- .../configuration/tls/IntermediateCrypto.java | 6 ++- .../configuration/tls/ModernCrypto.java | 6 ++- .../configuration/tls/OCSPClient.java | 4 ++ .../configuration/tls/Protocol.java | 10 ++-- .../tls/TlsClientConfiguration.java | 2 +- .../configuration/tls/TlsConfiguration.java | 7 +-- .../tls/TlsServerConfiguration.java | 2 +- .../transport/TransportConfiguration.java | 15 +++--- .../tls/CertificateKeyPairTest.java | 6 +-- .../tls/TlsConfigurationTest.java | 6 +-- .../core/factory/BootstrapFactory.java | 2 +- .../handlers/ConnectionTimeoutHandler.java | 2 +- .../core/handlers/SNIHandler.java | 2 +- .../core/loadbalancer/L4LoadBalancer.java | 16 +++--- .../healthcheck/HealthCheck.java | 6 +-- .../healthcheck/l7/HTTPServer.java | 16 +++--- .../protocol/http/DownstreamHandler.java | 2 +- .../expressgateway/protocol/http/Headers.java | 4 ++ .../http/Http11ServerInboundHandler.java | 7 ++- .../http/Http2ServerInboundHandler.java | 2 +- .../http/alpn/ALPNHandlerBuilder.java | 2 +- .../http/compression/CompressionUtil.java | 16 ++++-- .../protocol/http/websocket/Bootstrapper.java | 4 +- .../websocket/WebSocketDownstreamHandler.java | 1 - .../protocol/http/BrotliCompressionTest.java | 6 +-- .../protocol/http/DeflateCompressionTest.java | 2 +- .../protocol/http/GzipCompressionTest.java | 4 +- .../http/TestableHttpLoadBalancer.java | 6 +-- .../WebSocketHttpUpgradeHandler.java | 2 +- .../protocol/tcp/Bootstrapper.java | 4 +- .../protocol/tcp/DownstreamHandler.java | 10 ++-- .../protocol/tcp/ServerInitializer.java | 12 +++-- .../protocol/tcp/TCPConnection.java | 9 ++++ .../protocol/tcp/TCPListener.java | 15 ++++-- .../protocol/tcp/UpstreamHandler.java | 12 +++-- .../protocol/udp/DownstreamHandler.java | 4 +- .../protocol/udp/UDPListener.java | 4 +- .../protocol/udp/UpstreamHandler.java | 5 +- .../restapi/ExceptionHandlerController.java | 2 +- .../restapi/api/cluster/ClusterHandler.java | 30 +++++------ .../CertificateKeyPairHolder.java | 2 +- .../api/loadbalancer/LoadBalancerHandler.java | 4 +- ...alidLoadBalancerStartRequestException.java | 5 ++ .../restapi/response/FastBuilder.java | 4 ++ .../restapi/response/builder/APIResponse.java | 18 +++---- .../response/builder/ErrorMessage.java | 4 +- .../restapi/CustomOkHttpClient.java | 3 ++ ...usterConfigurationEndpointHandlerTest.java | 2 +- .../restapi/api/configuration/BufferTest.java | 53 ++++++++++++------- .../api/configuration/TransportTest.java | 6 +-- .../client/ServiceDiscoveryClientTest.java | 4 +- .../handler/codec/http2/Http2FrameCodec.java | 30 +++++------ .../standalone/BasicHttpServerTest.java | 2 +- .../standalone/BasicTcpUdpServerTest.java | 2 +- 119 files changed, 459 insertions(+), 315 deletions(-) create mode 100644 common/src/main/java/com/shieldblaze/expressgateway/common/utils/ObjectUtils.java diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/Connection.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/Connection.java index c69e23568..6b8e12178 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/Connection.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/Connection.java @@ -27,7 +27,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; /** - *

Base class for Connection. Protocol implementations must extend this class.

+ *

Base class for Connection. A connection is a Downstream {@link Channel}. Protocol implementations must extend this class.

* *

{@link #init(ChannelFuture)} must be called once {@link ChannelFuture} is ready * for a new connection.

@@ -39,7 +39,7 @@ public abstract class Connection { */ public enum State { /** - * Connection has been initialized. + * Connection has been initialized but not connected (or ready) yet. */ INITIALIZED, @@ -49,20 +49,22 @@ public enum State { CONNECTION_TIMEOUT, /** - * Connection has been closed with remote host. + * Connection has been closed with downstream channel. */ CONNECTION_CLOSED, /** - * Connection has been connected successfully and is active. + * Connection has been connected successfully, active and ready to accept traffic. */ CONNECTED_AND_ACTIVE } /** * Backlog Queue contains objects pending to be written once connection establishes. + *

+ * This queue will be {@code null} once backlog is processed (either via {@link #writeBacklog()} or {@link #clearBacklog()}) */ - protected final ConcurrentLinkedQueue backlogQueue = new ConcurrentLinkedQueue<>(); + protected ConcurrentLinkedQueue backlogQueue; private final Node node; protected ChannelFuture channelFuture; @@ -76,12 +78,15 @@ public enum State { * @param node {@link Node} associated with this Connection */ @NonNull - public Connection(Node node) { + protected Connection(Node node) { this.node = node; + backlogQueue(new ConcurrentLinkedQueue<>()); } /** - * Initialize this Connection + * Initialize this Connection with {@link ChannelFuture} + * + * @param channelFuture {@link ChannelFuture} associated with this Connection (of Upstream or Downstream) */ @NonNull public void init(ChannelFuture channelFuture) { @@ -120,11 +125,11 @@ public void init(ChannelFuture channelFuture) { protected abstract void processBacklog(ChannelFuture channelFuture); /** - * Write and Process the Backlog + * Write Backlog to the {@link Channel} */ protected void writeBacklog() { backlogQueue.forEach(this::writeAndFlush); - backlogQueue.clear(); // Clear the new queue because we're done with it. + backlogQueue = null; } /** @@ -132,7 +137,7 @@ protected void writeBacklog() { */ protected void clearBacklog() { backlogQueue.forEach(ReferenceCountedUtil::silentRelease); - backlogQueue.clear(); + backlogQueue = null; } /** @@ -158,29 +163,49 @@ public ChannelFuture channelFuture() { return channelFuture; } + /** + * Get {@link Node} associated with this connection. + */ public Node node() { return node; } + /** + * {@link InetSocketAddress} of this {@link Connection} + */ public InetSocketAddress socketAddress() { return socketAddress; } + /** + * Current {@link State} of this {@link Connection} + */ public State state() { return state; } + /** + * Set the {@link State} of this {@link Connection} + */ + public void backlogQueue(ConcurrentLinkedQueue newQueue) { + backlogQueue = newQueue; + } + /** * Close this {@link Connection} */ public synchronized void close() { // If Backlog Queue contains something then clear it before closing connection. - if (!backlogQueue.isEmpty()) { + if (backlogQueue != null && !backlogQueue.isEmpty()) { clearBacklog(); } + // Remove this connection from Node node.removeConnection(this); - if (this.channel != null) { + + // If Channel is not null then close it. + // Channel can be null if the connection is not initialized. + if (channel != null) { channel.close(); } } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/Node.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/Node.java index 1410f6a87..cb770da67 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/Node.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/Node.java @@ -39,7 +39,7 @@ import java.util.concurrent.atomic.AtomicLong; /** - *

{@link Node} is the server where all requests are sent.

+ *

{@link Node} is the server (downstream) where all requests are sent.

* * Use {@link NodeBuilder} to build {@link Node} Instance. */ @@ -298,13 +298,14 @@ public void markOnline() { /** * Add a {@link Connection} with this {@linkplain Node} */ - public void addConnection(Connection connection) throws TooManyConnectionsException, IllegalStateException { + public void addConnection(Connection connection) throws TooManyConnectionsException { // If Maximum Connection is not -1 and Number of Active connections is greater than // Maximum number of connections then close the connection and throw an exception. if (connectionFull()) { connection.close(); throw new TooManyConnectionsException(this); - } else if (state != State.ONLINE) { + } + if (state != State.ONLINE) { throw new IllegalStateException("Node is not online"); } activeConnections.add(connection); @@ -343,7 +344,7 @@ public String toString() { ", Address=" + socketAddress + ", BytesSent=" + bytesSent + ", BytesReceived=" + bytesReceived + - ", Connections=" + activeConnection() + "/" + maxConnections() + + ", Connections=" + activeConnection() + '/' + maxConnections() + ", state=" + state + ", health=" + health() + '}'; diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/NodeBytesTracker.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/NodeBytesTracker.java index 65cb4b0ba..f21ed3541 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/NodeBytesTracker.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/NodeBytesTracker.java @@ -39,11 +39,11 @@ public NodeBytesTracker(Node node) { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - if (msg instanceof ByteBuf) { - int bytes = ((ByteBuf) msg).readableBytes(); + if (msg instanceof ByteBuf byteBuf && byteBuf.isReadable()) { + int bytes = byteBuf.readableBytes(); node.incBytesSent(bytes); - } else if (msg instanceof ByteBufHolder) { - int bytes = ((ByteBufHolder) msg).content().readableBytes(); + } else if (msg instanceof ByteBufHolder byteBufHolder && byteBufHolder.content().isReadable()) { + int bytes = byteBufHolder.content().readableBytes(); node.incBytesSent(bytes); } @@ -52,11 +52,11 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if (msg instanceof ByteBuf) { - int bytes = ((ByteBuf) msg).readableBytes(); + if (msg instanceof ByteBuf byteBuf && byteBuf.isReadable()) { + int bytes = byteBuf.readableBytes(); node.incBytesReceived(bytes); - } else if (msg instanceof ByteBufHolder) { - int bytes = ((ByteBufHolder) msg).content().readableBytes(); + } else if (msg instanceof ByteBufHolder byteBufHolder && byteBufHolder.content().isReadable()) { + int bytes = byteBufHolder.content().readableBytes(); node.incBytesReceived(bytes); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/State.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/State.java index bacd8e2d3..3e53fa864 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/State.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/State.java @@ -21,19 +21,23 @@ * Node State */ public enum State { + /** * {@link Node} is online, active and accepting connections. */ ONLINE, + /** * {@link Node} is offline, not active and not accepting any connections. */ OFFLINE, + /** * {@link Node} is idle, only processing established active connections and not accepting * any new connections. */ IDLE, + /** * {@link Node} is marked as offline manually. */ diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/Cluster.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/Cluster.java index 615fdbfa1..723ee07e5 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/Cluster.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/Cluster.java @@ -80,7 +80,7 @@ public class Cluster extends ClusterOnlineNodesWorker { Cluster(LoadBalance loadBalance) { loadBalance(loadBalance); - this.eventStream.subscribe(this); + eventStream.subscribe(this); } /** @@ -168,7 +168,7 @@ public Node get(String id) { * Get List of online {@link Node} associated with this {@linkplain Cluster} */ public List onlineNodes() { - return ONLINE_NODES; + return onlineNodes; } /** @@ -261,7 +261,7 @@ public HealthCheckTemplate healthCheckTemplate() { @NonNull void configureHealthCheck(HealthCheckConfiguration healthCheckConfiguration, HealthCheckTemplate healthCheckTemplate) { - this.healthCheckService = new HealthCheckService(healthCheckConfiguration, eventStream); + healthCheckService = new HealthCheckService(healthCheckConfiguration, eventStream); this.healthCheckTemplate = healthCheckTemplate; } @@ -284,9 +284,9 @@ private void configureHealthCheckForNode(Node node) throws Exception { case HTTP, HTTPS -> { String host; if (healthCheckTemplate.protocol() == HealthCheckTemplate.Protocol.HTTP) { - host = "http://" + InetAddress.getByName(healthCheckTemplate.host()).getHostAddress() + ":" + healthCheckTemplate().port(); + host = "http://" + InetAddress.getByName(healthCheckTemplate.host()).getHostAddress() + ':' + healthCheckTemplate().port(); } else { - host = "https://" + InetAddress.getByName(healthCheckTemplate.host()).getHostAddress() + ":" + healthCheckTemplate().port(); + host = "https://" + InetAddress.getByName(healthCheckTemplate.host()).getHostAddress() + ':' + healthCheckTemplate().port(); } healthCheck = new HTTPHealthCheck(URI.create(host), Duration.ofSeconds(healthCheckTemplate.timeout()), healthCheckTemplate.samples()); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterBuilder.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterBuilder.java index f15175745..fee8d8481 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterBuilder.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterBuilder.java @@ -23,6 +23,9 @@ import java.util.Objects; +import static com.shieldblaze.expressgateway.common.utils.ObjectUtils.nonNull; +import static java.util.Objects.requireNonNull; + /** * Builder for {@link Cluster} */ @@ -42,13 +45,13 @@ public ClusterBuilder withLoadBalance(LoadBalance loadBalance) { } public ClusterBuilder withHealthCheck(HealthCheckConfiguration healthCheckConfiguration, HealthCheckTemplate healthCheckTemplate) { - this.healthCheckConfiguration = Objects.requireNonNull(healthCheckConfiguration, "HealthCheckConfiguration cannot be 'null'"); - this.healthCheckTemplate = Objects.requireNonNull(healthCheckTemplate, "HealthCheckTemplate cannot be 'null'"); + this.healthCheckConfiguration = nonNull(healthCheckConfiguration, HealthCheckConfiguration.class); + this.healthCheckTemplate = nonNull(healthCheckTemplate, HealthCheckTemplate.class); return this; } public Cluster build() { - Objects.requireNonNull(loadBalance, "LoadBalance cannot be 'null'"); + nonNull(loadBalance, LoadBalance.class); Cluster cluster = new Cluster(loadBalance); // If HealthCheck configuration is available then apply it. diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterOnlineNodesWorker.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterOnlineNodesWorker.java index 4a5e4be80..40ffa0f0c 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterOnlineNodesWorker.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/cluster/ClusterOnlineNodesWorker.java @@ -29,16 +29,16 @@ class ClusterOnlineNodesWorker implements EventListener { - protected final List ONLINE_NODES = new CopyOnWriteArrayList<>(); + protected final List onlineNodes = new CopyOnWriteArrayList<>(); @Override public void accept(Event event) { if (event instanceof NodeEvent nodeEvent) { if (nodeEvent instanceof NodeOnlineEvent || nodeEvent instanceof NodeAddedEvent) { - ONLINE_NODES.add(nodeEvent.node()); + onlineNodes.add(nodeEvent.node()); } else { - ONLINE_NODES.remove(nodeEvent.node()); + onlineNodes.remove(nodeEvent.node()); } } } @@ -46,7 +46,7 @@ public void accept(Event event) { @Override public String toString() { return "ClusterOnlineNodesWorker{" + - "ONLINE_NODES=" + ONLINE_NODES.size() + + "onlineNodes=" + onlineNodes + '}'; } } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/events/node/NodeEvent.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/events/node/NodeEvent.java index 9bc24a395..c298ece19 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/events/node/NodeEvent.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/events/node/NodeEvent.java @@ -26,7 +26,7 @@ public abstract class NodeEvent extends DefaultEvent { private final Node node; - public NodeEvent(Node node) { + protected NodeEvent(Node node) { this.node = node; } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/LoadBalanceException.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/LoadBalanceException.java index 65e76656f..112ec33f6 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/LoadBalanceException.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/LoadBalanceException.java @@ -19,13 +19,17 @@ import com.shieldblaze.expressgateway.backend.loadbalance.LoadBalance; +import java.io.Serial; + /** * Thrown when there was an error during load-balancing by {@link LoadBalance} */ public class LoadBalanceException extends Exception { + @Serial + private static final long serialVersionUID = 1841399446385743110L; + public LoadBalanceException() { - super(); } public LoadBalanceException(String message) { diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/NoNodeAvailableException.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/NoNodeAvailableException.java index 37bb022e4..3283224cf 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/NoNodeAvailableException.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/NoNodeAvailableException.java @@ -19,15 +19,19 @@ import com.shieldblaze.expressgateway.backend.Node; +import java.io.Serial; + /** * Thrown when there is no {@link Node} available to handle request. */ public final class NoNodeAvailableException extends LoadBalanceException { + @Serial + private static final long serialVersionUID = 3016237192356488630L; + public static final NoNodeAvailableException INSTANCE = new NoNodeAvailableException("No Node is available to handle this exception"); public NoNodeAvailableException() { - super(); } public NoNodeAvailableException(String message) { @@ -42,7 +46,7 @@ public NoNodeAvailableException(Throwable cause) { super(cause); } - protected NoNodeAvailableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + private NoNodeAvailableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/TooManyConnectionsException.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/TooManyConnectionsException.java index 0e52ab138..ef7d96085 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/TooManyConnectionsException.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/exceptions/TooManyConnectionsException.java @@ -19,11 +19,16 @@ import com.shieldblaze.expressgateway.backend.Node; +import java.io.Serial; + /** * Thrown when a {@link Node} has exceeded the maximum number of connections count. */ public final class TooManyConnectionsException extends Exception { + @Serial + private static final long serialVersionUID = 6390465718005428833L; + public TooManyConnectionsException(Node node) { super("Node (" + node + ") has reached maximum number of connections."); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckRunner.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckRunner.java index 2df27cd23..f82cd4edf 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckRunner.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckRunner.java @@ -44,8 +44,7 @@ final class HealthCheckRunner implements Runnable { @Override public void run() { - // If Node is manually marked as offline - // then don't run Health Check. + // If Node is manually marked as offline, then don't run Health Check. if (node.state() == State.MANUAL_OFFLINE) { return; } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckTemplate.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckTemplate.java index df2754478..7e5ef8f24 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckTemplate.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckTemplate.java @@ -22,6 +22,10 @@ import java.util.Objects; +import static com.shieldblaze.expressgateway.common.utils.NumberUtil.checkInRange; +import static com.shieldblaze.expressgateway.common.utils.NumberUtil.checkPositive; +import static java.util.Objects.requireNonNull; + public final class HealthCheckTemplate { /** @@ -74,7 +78,7 @@ public Protocol protocol() { } public void setProtocol(Protocol protocol) { - this.protocol = Objects.requireNonNull(protocol, "Protocol"); + this.protocol = requireNonNull(protocol, "Protocol"); } public String host() { @@ -82,7 +86,7 @@ public String host() { } public void setHost(String host) { - this.host = Objects.requireNonNull(host, "Host"); + this.host = requireNonNull(host, "Host"); } public int port() { @@ -90,7 +94,7 @@ public int port() { } public void setPort(int port) { - this.port = NumberUtil.checkInRange(port, 1, 65535, "Port"); + this.port = checkInRange(port, 1, 65535, "Port"); } public String path() { @@ -98,7 +102,7 @@ public String path() { } public void setPath(String path) { - this.path = Objects.requireNonNull(path, "Path"); + this.path = requireNonNull(path, "Path"); } public int timeout() { @@ -106,7 +110,7 @@ public int timeout() { } public void setTimeout(int timeout) { - this.timeout = NumberUtil.checkPositive(timeout, "Timeout"); + this.timeout = checkPositive(timeout, "Timeout"); } public int samples() { @@ -114,7 +118,7 @@ public int samples() { } public void setSamples(int samples) { - this.samples = NumberUtil.checkPositive(samples, "Samples"); + this.samples = checkPositive(samples, "Samples"); } public enum Protocol { diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/LoadBalance.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/LoadBalance.java index 60abf92bd..bbb2e0a86 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/LoadBalance.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/LoadBalance.java @@ -40,7 +40,7 @@ public abstract class LoadBalance implements Even * @param sessionPersistence {@link SessionPersistence} Implementation Instance */ @NonNull - public LoadBalance(SessionPersistence sessionPersistence) { + protected LoadBalance(SessionPersistence sessionPersistence) { this.sessionPersistence = sessionPersistence; } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Request.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Request.java index db005678a..12a62f27e 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Request.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Request.java @@ -30,7 +30,7 @@ public abstract class Request { * * @param socketAddress {@link InetSocketAddress} of Client */ - public Request(InetSocketAddress socketAddress) { + protected Request(InetSocketAddress socketAddress) { this.socketAddress = socketAddress; } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Response.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Response.java index 29df53b26..e2eddb72a 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Response.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/loadbalance/Response.java @@ -30,7 +30,7 @@ public abstract class Response { * * @param node Selected {@linkplain Node} for the request */ - public Response(Node node) { + protected Response(Node node) { this.node = node; } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Balance.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Balance.java index de189a251..990cea323 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Balance.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Balance.java @@ -45,7 +45,7 @@ public abstract class L4Balance extends LoadBalance sessionPersistence) { + protected L4Balance(SessionPersistence sessionPersistence) { super(sessionPersistence); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Request.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Request.java index 9baff3a3c..6582917e0 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Request.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/L4Request.java @@ -34,6 +34,4 @@ public final class L4Request extends Request { public L4Request(InetSocketAddress socketAddress) { super(socketAddress); } - - } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/Random.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/Random.java index 4d438aac4..3fd5c5e49 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/Random.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/Random.java @@ -36,7 +36,7 @@ */ public final class Random extends L4Balance { - private final SplittableRandom RANDOM = new SplittableRandom(); + private final SplittableRandom random = new SplittableRandom(); /** * Create {@link Random} Instance @@ -64,7 +64,7 @@ public L4Response response(L4Request l4Request) throws LoadBalanceException { } try { - node = cluster.onlineNodes().get(RANDOM.nextInt(cluster.onlineNodes().size())); + node = cluster.onlineNodes().get(random.nextInt(cluster.onlineNodes().size())); } catch (Exception ex) { throw new NoNodeAvailableException(ex); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/FourTupleHash.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/FourTupleHash.java index 0ea77539e..6dd38b298 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/FourTupleHash.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/FourTupleHash.java @@ -34,8 +34,7 @@ */ public final class FourTupleHash implements SessionPersistence { - private final Map routeMap = - new SelfExpiringMap<>(new ConcurrentHashMap<>(), Duration.ofHours(1), false); + private final Map routeMap = new SelfExpiringMap<>(new ConcurrentHashMap<>(), Duration.ofHours(1), false); @Override public Node node(Request request) { diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHash.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHash.java index 5154b0a5e..bba051820 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHash.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHash.java @@ -112,20 +112,20 @@ public String name() { return "SourceIPHash"; } - private int ipv4WithMask(Request request) { + private static int ipv4WithMask(Request request) { return ipv4WithMask(request.socketAddress()); } - private BigInteger ipv6WithMask(Request request) { + private static BigInteger ipv6WithMask(Request request) { return ipv6WithMask(request.socketAddress()); } - private int ipv4WithMask(InetSocketAddress socketAddress) { + private static int ipv4WithMask(InetSocketAddress socketAddress) { int ipAddress = NetUtil.ipv4AddressToInt((Inet4Address) socketAddress.getAddress()); return ipAddress & prefixToSubnetMaskIPv4(); } - private BigInteger ipv6WithMask(InetSocketAddress socketAddress) { + private static BigInteger ipv6WithMask(InetSocketAddress socketAddress) { BigInteger ipAddress = ipToInt((Inet6Address) socketAddress.getAddress()); return ipAddress.and(prefixToSubnetMaskIPv6()); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalance.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalance.java index 4dca7de95..afed8429b 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalance.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalance.java @@ -31,7 +31,7 @@ public abstract class HTTPBalance extends LoadBalance sessionPersistence) { + protected HTTPBalance(SessionPersistence sessionPersistence) { super(sessionPersistence); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalanceRequest.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalanceRequest.java index 88cc77489..604c6c588 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalanceRequest.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPBalanceRequest.java @@ -27,6 +27,7 @@ * {@link HTTPBalanceRequest} contains {@link InetSocketAddress} and {@link HttpHeaders} of Client */ public final class HTTPBalanceRequest extends Request { + private final HttpHeaders httpHeaders; private final Http2Headers http2Headers; diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandom.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandom.java index 39f4af29f..a27b3b68c 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandom.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandom.java @@ -36,7 +36,7 @@ */ public final class HTTPRandom extends HTTPBalance { - private final SplittableRandom RANDOM = new SplittableRandom(); + private final SplittableRandom random = new SplittableRandom(); /** * Create {@link HTTPRandom} Instance @@ -67,7 +67,7 @@ public HTTPBalanceResponse response(HTTPBalanceRequest request) throws LoadBalan Node node; try { - node = cluster.onlineNodes().get(RANDOM.nextInt(cluster.onlineNodes().size())); + node = cluster.onlineNodes().get(random.nextInt(cluster.onlineNodes().size())); } catch (Exception ex) { throw new NoNodeAvailableException(ex); } diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySession.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySession.java index 09adfd668..f666c952d 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySession.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySession.java @@ -102,7 +102,7 @@ public HTTPBalanceResponse addRoute(HTTPBalanceRequest httpBalanceRequest, Node @Override public boolean removeRoute(HTTPBalanceRequest httpBalanceRequest, Node node) { - return this.nodes.remove(node); + return nodes.remove(node); } @Override diff --git a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionSearchComparator.java b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionSearchComparator.java index e193fa557..bb3e486a9 100644 --- a/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionSearchComparator.java +++ b/backend/src/main/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionSearchComparator.java @@ -19,9 +19,13 @@ import com.shieldblaze.expressgateway.backend.Node; +import java.io.Serial; +import java.io.Serializable; import java.util.Comparator; -final class StickySessionSearchComparator implements Comparator { +final class StickySessionSearchComparator implements Comparator, Serializable { + @Serial + private static final long serialVersionUID = 6565521040672349803L; static final StickySessionSearchComparator INSTANCE = new StickySessionSearchComparator(); diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckServiceTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckServiceTest.java index 9a2068ef0..328c77fc6 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckServiceTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/healthcheck/HealthCheckServiceTest.java @@ -44,7 +44,7 @@ class HealthCheckServiceTest { - private final static EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2); + private static final EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2); @BeforeAll static void setup() throws InterruptedException { diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastConnectionTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastConnectionTest.java index 49f5927f4..ce95bd9ef 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastConnectionTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastConnectionTest.java @@ -54,19 +54,15 @@ void testLeastConnection() throws Exception { switch (node.socketAddress().getHostString()) { case "10.10.1.1" -> { first++; - break; } case "10.10.1.2" -> { second++; - break; } case "10.10.1.3" -> { third++; - break; } case "10.10.1.4" -> { forth++; - break; } default -> { } diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastLoadTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastLoadTest.java index dced872e6..3797aed58 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastLoadTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/LeastLoadTest.java @@ -54,19 +54,15 @@ void testLeastLoad() throws Exception { switch (node.socketAddress().getHostString()) { case "10.10.1.1" -> { first++; - break; } case "10.10.1.2" -> { second++; - break; } case "10.10.1.3" -> { third++; - break; } case "10.10.1.4" -> { forth++; - break; } default -> { } diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RandomTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RandomTest.java index a19676c40..20cd5ecde 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RandomTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RandomTest.java @@ -53,23 +53,18 @@ void testRandom() throws Exception { switch (cluster.nextNode(l4Request).node().socketAddress().getHostString()) { case "172.16.20.1" -> { first++; - break; } case "172.16.20.2" -> { second++; - break; } case "172.16.20.3" -> { third++; - break; } case "172.16.20.4" -> { forth++; - break; } case "172.16.20.5" -> { fifth++; - break; } default -> { } @@ -83,7 +78,7 @@ void testRandom() throws Exception { assertTrue(fifth > 10); } - private void fastBuild(Cluster cluster, String host) throws Exception { + private static void fastBuild(Cluster cluster, String host) throws Exception { NodeBuilder.newBuilder() .withCluster(cluster) .withSocketAddress(new InetSocketAddress(host, 1)) diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RoundRobinTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RoundRobinTest.java index e4b39a20b..2fcb520fd 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RoundRobinTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/RoundRobinTest.java @@ -58,7 +58,7 @@ void testRoundRobin() throws Exception { } } - private void fastBuild(Cluster cluster, String host) throws Exception { + private static void fastBuild(Cluster cluster, String host) throws Exception { NodeBuilder.newBuilder() .withCluster(cluster) .withSocketAddress(new InetSocketAddress(host, 1)) diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHashTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHashTest.java index 62eb7d009..8b521ec1b 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHashTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l4/sessionpersistence/SourceIPHashTest.java @@ -76,7 +76,7 @@ void testSourceIPHash() throws Exception { cluster.nextNode(new L4Request(new InetSocketAddress("172.20.1.253", 1))).node().socketAddress()); } - private void fastBuild(Cluster cluster, String host) throws Exception { + private static void fastBuild(Cluster cluster, String host) throws Exception { NodeBuilder.newBuilder() .withCluster(cluster) .withSocketAddress(new InetSocketAddress(host, 1)) diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandomTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandomTest.java index a05b06ea8..ddf15127b 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandomTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRandomTest.java @@ -54,23 +54,18 @@ void testRandom() throws Exception { switch (cluster.nextNode(httpBalanceRequest).node().socketAddress().getHostString()) { case "172.16.20.1" -> { first++; - break; } case "172.16.20.2" -> { second++; - break; } case "172.16.20.3" -> { third++; - break; } case "172.16.20.4" -> { forth++; - break; } case "172.16.20.5" -> { fifth++; - break; } default -> { } @@ -84,7 +79,7 @@ void testRandom() throws Exception { assertTrue(fifth > 10); } - private void fastBuild(Cluster cluster, String host) throws Exception { + private static void fastBuild(Cluster cluster, String host) throws Exception { NodeBuilder.newBuilder() .withCluster(cluster) .withSocketAddress(new InetSocketAddress(host, 1)) diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRoundRobinTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRoundRobinTest.java index c79682d2f..820aec37b 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRoundRobinTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/HTTPRoundRobinTest.java @@ -59,7 +59,7 @@ void testRoundRobin() throws Exception { } } - private void fastBuild(Cluster cluster, String host) throws Exception { + private static void fastBuild(Cluster cluster, String host) throws Exception { NodeBuilder.newBuilder() .withCluster(cluster) .withSocketAddress(new InetSocketAddress(host, 1)) diff --git a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionTest.java b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionTest.java index 7f3fb3019..453e421ec 100644 --- a/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionTest.java +++ b/backend/src/test/java/com/shieldblaze/expressgateway/backend/strategy/l7/http/sessionpersistence/StickySessionTest.java @@ -64,7 +64,7 @@ void testStickySession() throws Exception { } } - private void fastBuild(Cluster cluster, String host) throws Exception { + private static void fastBuild(Cluster cluster, String host) throws Exception { NodeBuilder.newBuilder() .withCluster(cluster) .withSocketAddress(new InetSocketAddress(host, 1)) diff --git a/bootstrap/src/main/java/com/shieldblaze/expressgateway/bootstrap/Bootstrap.java b/bootstrap/src/main/java/com/shieldblaze/expressgateway/bootstrap/Bootstrap.java index 4ffaaf53c..4fb141fe1 100644 --- a/bootstrap/src/main/java/com/shieldblaze/expressgateway/bootstrap/Bootstrap.java +++ b/bootstrap/src/main/java/com/shieldblaze/expressgateway/bootstrap/Bootstrap.java @@ -37,6 +37,10 @@ public final class Bootstrap { private static final Logger logger = LogManager.getLogger(Bootstrap.class); + private Bootstrap() { + // Prevent outside initialization + } + public static void main() throws Exception { main(new String[0]); } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Hasher.java b/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Hasher.java index 63594fac0..a9101889f 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Hasher.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Hasher.java @@ -28,6 +28,10 @@ public final class Hasher { private static final Logger logger = LogManager.getLogger(Hasher.class); + private Hasher() { + // Prevent outside initialization + } + public enum Algorithm { SHA256, SHA384 @@ -47,7 +51,6 @@ private static MessageDigest messageDigest(Algorithm algorithm) throws NoSuchAlg return switch (algorithm) { case SHA256 -> MessageDigest.getInstance("SHA-256"); case SHA384 -> MessageDigest.getInstance("SHA-384"); - default -> throw new IllegalArgumentException("Unknown Algorithm: " + algorithm); }; } } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Keypair.java b/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Keypair.java index 179bd8390..1494cbe07 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Keypair.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/Keypair.java @@ -34,6 +34,10 @@ public final class Keypair { Security.addProvider(new BouncyCastleProvider()); } + private Keypair() { + // Prevent outside initialization + } + public static PrivateKey parse(String privateKeyString) throws IOException { PEMParser pemParser = new PEMParser(new StringReader(privateKeyString)); Object object = pemParser.readObject(); @@ -41,7 +45,8 @@ public static PrivateKey parse(String privateKeyString) throws IOException { if (object instanceof PEMKeyPair pemKeyPair) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); return converter.getKeyPair(pemKeyPair).getPrivate(); - } else if (object instanceof PrivateKeyInfo privateKeyInfo) { + } + if (object instanceof PrivateKeyInfo privateKeyInfo) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); return converter.getPrivateKey(privateKeyInfo); } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/PrivateKeyUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/PrivateKeyUtil.java index 74220f444..28689de7d 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/PrivateKeyUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/crypto/PrivateKeyUtil.java @@ -41,7 +41,7 @@ public static PrivateKey parsePrivateKey(String pem) { JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider()); KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair); - if (keyPair.getPrivate().getAlgorithm().equalsIgnoreCase("DSA")) { + if ("DSA".equalsIgnoreCase(keyPair.getPrivate().getAlgorithm())) { throw new IllegalArgumentException("Unsupported Private Key"); } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/map/Cleaner.java b/common/src/main/java/com/shieldblaze/expressgateway/common/map/Cleaner.java index c99b42b59..fe291c802 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/map/Cleaner.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/map/Cleaner.java @@ -28,7 +28,7 @@ public abstract class Cleaner implements Runnable, Closeable { private final SelfExpiringMap selfExpiringMap; - public Cleaner(SelfExpiringMap selfExpiringMap) { + protected Cleaner(SelfExpiringMap selfExpiringMap) { this.selfExpiringMap = selfExpiringMap; } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/map/DefaultCleaner.java b/common/src/main/java/com/shieldblaze/expressgateway/common/map/DefaultCleaner.java index 5cb6d4cd4..d7a1eb7f3 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/map/DefaultCleaner.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/map/DefaultCleaner.java @@ -18,7 +18,7 @@ final class DefaultCleaner extends Cleaner { DefaultCleaner(SelfExpiringMap selfExpiringMap) { super(selfExpiringMap); - scheduledFuture = GlobalExecutors.INSTANCE.submitTaskAndRunEvery(this, 1, 1, TimeUnit.SECONDS); + scheduledFuture = GlobalExecutors.submitTaskAndRunEvery(this, 1, 1, TimeUnit.SECONDS); } @Override diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/map/ExpiringMap.java b/common/src/main/java/com/shieldblaze/expressgateway/common/map/ExpiringMap.java index 17bdb039c..9527a43b4 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/map/ExpiringMap.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/map/ExpiringMap.java @@ -45,7 +45,7 @@ public abstract class ExpiringMap implements Map { * * @param ttlDuration TTL (Time-to-live) duration of entries */ - public ExpiringMap(Duration ttlDuration) { + protected ExpiringMap(Duration ttlDuration) { this(new HashMap<>(), ttlDuration, true); } @@ -57,7 +57,7 @@ public ExpiringMap(Duration ttlDuration) { * @param autoRenew Set to {@code true} if entries will be auto-renewed on {@link #get(Object)} call * else set to {@code false} */ - public ExpiringMap(Map storageMap, Duration ttlDuration, boolean autoRenew) { + protected ExpiringMap(Map storageMap, Duration ttlDuration, boolean autoRenew) { this(storageMap, ttlDuration, autoRenew, new IgnoreEntryRemovedListener<>()); } @@ -70,12 +70,12 @@ public ExpiringMap(Map storageMap, Duration ttlDuration, boolean autoRenew * else set to {@code false} * @param entryRemovedListener {@link EntryRemovedListener} Instance */ - public ExpiringMap(Map storageMap, Duration ttlDuration, boolean autoRenew, EntryRemovedListener entryRemovedListener) { + protected ExpiringMap(Map storageMap, Duration ttlDuration, boolean autoRenew, EntryRemovedListener entryRemovedListener) { this.storageMap = Objects.requireNonNull(storageMap, "StorageMap"); ttlNanos = ttlDuration.toNanos(); this.autoRenew = autoRenew; - if (this.storageMap.size() != 0) { + if (!this.storageMap.isEmpty()) { throw new IllegalArgumentException("StorageMap Size must be Zero (0)."); } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/Hex.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/Hex.java index 176981145..a80a9fe9d 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/Hex.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/Hex.java @@ -22,6 +22,10 @@ public final class Hex { private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.UTF_8); + private Hex() { + // Prevent outside initialization + } + /** * Convert byte array to Hex {@linkplain String}. * @param bytes Byte array diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ListUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ListUtil.java index 44f757559..a90e20704 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ListUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ListUtil.java @@ -23,6 +23,10 @@ public final class ListUtil { + private ListUtil() { + // Prevent outside initialization + } + public static T[] checkNonEmpty(T[] array, String name) { Objects.requireNonNull(array, name); NumberUtil.checkPositive(array.length, name); diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/MathUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/MathUtil.java index e57185b43..d69a201a0 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/MathUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/MathUtil.java @@ -19,6 +19,10 @@ public final class MathUtil { + private MathUtil() { + // Prevent outside initialization + } + public static float percentage(int current, int maximum) { return current * 100f / maximum; } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkInterfaceUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkInterfaceUtil.java index 5e92ebcf0..198db3f29 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkInterfaceUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkInterfaceUtil.java @@ -26,6 +26,10 @@ public final class NetworkInterfaceUtil { + private NetworkInterfaceUtil() { + // Prevent outside initialization + } + public static List getAllIps() { List ipAddressList = new ArrayList<>(); diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkUtil.java index 6310ab1bf..305bac780 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NetworkUtil.java @@ -58,7 +58,7 @@ public static boolean isAddressValid(String address) { * @param port Port to check * @throws IllegalArgumentException Thrown if address or port is not valid */ - public static void checkAddressAndPort(String address, int port) throws IllegalArgumentException { + public static void checkAddressAndPort(String address, int port) { if (!(isAddressValid(address) && isPortValid(port))) { throw new IllegalArgumentException("Invalid Address or Port"); } diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NumberUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NumberUtil.java index 87a4c8641..989cb377b 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NumberUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/NumberUtil.java @@ -88,8 +88,7 @@ public static int checkInRange(int i, int start, int end, String message) { if (i >= start && i <= end) { return i; } - throw new IllegalArgumentException("Invalid " + message + ": " + i + - "; (Expected: " + start + "-" + end + ")"); + throw new IllegalArgumentException("Invalid " + message + ": " + i + "; (Expected: " + start + '-' + end + ')'); } /** @@ -106,8 +105,7 @@ public static long checkInRange(long l, long start, long end, String message) { return l; } - throw new IllegalArgumentException("Invalid " + message + ": " + l + - "; (Expected: " + start + "-" + end + ")"); + throw new IllegalArgumentException("Invalid " + message + ": " + l + "; (Expected: " + start + '-' + end + ')'); } /** @@ -123,8 +121,7 @@ public static double checkInRange(double d, double start, double end, String mes if (d >= start && d <= end) { return d; } - throw new IllegalArgumentException("Invalid " + message + ": " + d + - "; (Expected: " + start + "-" + end + ")"); + throw new IllegalArgumentException("Invalid " + message + ": " + d + "; (Expected: " + start + '-' + end + ')'); } /** @@ -140,8 +137,7 @@ public static float checkInRange(float f, float start, float end, String message if (f >= start && f <= end) { return f; } - throw new IllegalArgumentException("Invalid " + message + ": " + f + - "; (Expected: " + start + "-" + end + ")"); + throw new IllegalArgumentException("Invalid " + message + ": " + f + "; (Expected: " + start + '-' + end + ')'); } private NumberUtil() { diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ObjectUtils.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ObjectUtils.java new file mode 100644 index 000000000..31f839a97 --- /dev/null +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ObjectUtils.java @@ -0,0 +1,19 @@ +package com.shieldblaze.expressgateway.common.utils; + +public final class ObjectUtils { + + private ObjectUtils() { + // Prevent outside initialization + } + + public static T nonNull(T obj, Class clazz) { + return nonNull(obj, clazz.getSimpleName()); + } + + public static T nonNull(T obj, String message) { + if (obj == null) { + throw new NullPointerException(message); + } + return obj; + } +} diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ReferenceCountedUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ReferenceCountedUtil.java index b892c939d..28e1c24a0 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ReferenceCountedUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/ReferenceCountedUtil.java @@ -21,7 +21,7 @@ import io.netty.util.ReferenceCounted; /** - * Provides extra utilities for {@link io.netty.util.ReferenceCounted} objects. + * Provides extra utilities for {@link ReferenceCounted} objects. */ public final class ReferenceCountedUtil { diff --git a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/StringUtil.java b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/StringUtil.java index 20e76675e..8dd89b0cd 100644 --- a/common/src/main/java/com/shieldblaze/expressgateway/common/utils/StringUtil.java +++ b/common/src/main/java/com/shieldblaze/expressgateway/common/utils/StringUtil.java @@ -40,7 +40,8 @@ public static boolean isNullOrEmpty(String str) { public static String validateNotNullOrEmpty(String str) { if (str == null) { throw new NullPointerException("String is 'null'"); - } else if (str.isEmpty() || str.isBlank()) { + } + if (str.isEmpty() || str.isBlank()) { throw new IllegalArgumentException("String is empty or blank"); } return str; @@ -58,7 +59,8 @@ public static String validateNotNullOrEmpty(String str) { public static String validateNotNullOrEmpty(String str, String name) { if (str == null) { throw new NullPointerException(name + " is 'null'"); - } else if (str.isEmpty() || str.isBlank()) { + } + if (str.isEmpty() || str.isBlank()) { throw new IllegalArgumentException(name + " is empty or blank"); } return str; diff --git a/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CertificateManagerTest.java b/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CertificateManagerTest.java index 9b6f901db..dbcfe07cb 100644 --- a/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CertificateManagerTest.java +++ b/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CertificateManagerTest.java @@ -56,7 +56,7 @@ static void setUp() throws Exception { ExpressGateway.setInstance(forTest(testingServer.getConnectString())); Curator.init(); - CertificateManager.INSTANCE.isInitialized().get(30, TimeUnit.SECONDS); + CertificateManager.isInitialized().get(30, TimeUnit.SECONDS); } @AfterAll diff --git a/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CuratorUtilsTest.java b/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CuratorUtilsTest.java index 6b67e8b19..3b55d05e6 100644 --- a/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CuratorUtilsTest.java +++ b/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/CuratorUtilsTest.java @@ -18,17 +18,11 @@ package com.shieldblaze.expressgateway.common.zookeeper; import com.shieldblaze.expressgateway.common.ExpressGateway; -import org.apache.curator.test.InstanceSpec; -import org.apache.curator.test.QuorumConfigBuilder; -import org.apache.curator.test.QuorumPeerConfigBuilder; import org.apache.curator.test.TestingServer; -import org.apache.curator.test.ZooKeeperServerEmbeddedAdapter; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.Collections; - import static com.shieldblaze.expressgateway.common.zookeeper.Curator.getInstance; import static com.shieldblaze.expressgateway.common.zookeeper.CuratorUtils.createNew; import static com.shieldblaze.expressgateway.common.zookeeper.CuratorUtils.deleteData; diff --git a/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/ExpressGatewayCustomizedUtil.java b/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/ExpressGatewayCustomizedUtil.java index 1506f5c9c..7901b9fe4 100644 --- a/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/ExpressGatewayCustomizedUtil.java +++ b/common/src/test/java/com/shieldblaze/expressgateway/common/zookeeper/ExpressGatewayCustomizedUtil.java @@ -22,7 +22,11 @@ import java.util.UUID; -class ExpressGatewayCustomizedUtil { +final class ExpressGatewayCustomizedUtil { + + private ExpressGatewayCustomizedUtil() { + // Prevent outside initialization + } static ExpressGateway forTest(String zooKeeperConnectionString) { ExpressGateway.ZooKeeper zooKeeper = new ExpressGateway.ZooKeeper(zooKeeperConnectionString, diff --git a/concurrent/src/main/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStream.java b/concurrent/src/main/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStream.java index b8e6dc3d7..1bc5a9a4e 100644 --- a/concurrent/src/main/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStream.java +++ b/concurrent/src/main/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStream.java @@ -47,7 +47,7 @@ public AsyncEventStream(ExecutorService executorService) { * * @param event Event to publish */ - @SuppressWarnings({"unchecked"}) + @SuppressWarnings("unchecked") @Override public void publish(Event event) { executorService.execute(() -> subscribers.forEach(eventListener -> eventListener.accept(event))); diff --git a/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStreamTest.java b/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStreamTest.java index a75e716ad..c31ef595a 100644 --- a/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStreamTest.java +++ b/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/AsyncEventStreamTest.java @@ -47,7 +47,7 @@ private static final class EventListenerTest implements EventListener { final Set stringsSet = new HashSet<>(); - public EventListenerTest() { + private EventListenerTest() { for (int i = 0; i < 100_000; i++) { stringsSet.add("Meow" + i); } diff --git a/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/EventStreamTest.java b/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/EventStreamTest.java index 7d4865c01..0c9f25733 100644 --- a/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/EventStreamTest.java +++ b/concurrent/src/test/java/com/shieldblaze/expressgateway/concurrent/eventstream/EventStreamTest.java @@ -43,7 +43,7 @@ void testEventStream() { private static final class EventListenerTest implements EventListener { - int expect = 0; + int expect; @Override public void accept(Event event) { diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/Configuration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/Configuration.java index 1dbeb944c..5a685a8b1 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/Configuration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/Configuration.java @@ -33,7 +33,7 @@ public interface Configuration { * @return This configuration instance * @throws IllegalArgumentException If there is an error during validation */ - T validate() throws IllegalArgumentException; + T validate(); /** * Friendly name of this Configuration. diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/ConfigurationContext.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/ConfigurationContext.java index bc02a03cf..bfcb884bd 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/ConfigurationContext.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/ConfigurationContext.java @@ -96,21 +96,4 @@ public static ConfigurationContext create(Configuration... configurations) { transportConfiguration); } - public ConfigurationContext(BufferConfiguration bufferConfiguration, - EventLoopConfiguration eventLoopConfiguration, - EventStreamConfiguration eventStreamConfiguration, - HealthCheckConfiguration healthCheckConfiguration, - HttpConfiguration httpConfiguration, - TlsClientConfiguration tlsClientConfiguration, - TlsServerConfiguration tlsServerConfiguration, - TransportConfiguration transportConfiguration) { - this.bufferConfiguration = bufferConfiguration; - this.eventLoopConfiguration = eventLoopConfiguration; - this.eventStreamConfiguration = eventStreamConfiguration; - this.healthCheckConfiguration = healthCheckConfiguration; - this.httpConfiguration = httpConfiguration; - this.tlsClientConfiguration = tlsClientConfiguration; - this.tlsServerConfiguration = tlsServerConfiguration; - this.transportConfiguration = transportConfiguration; - } } diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/buffer/BufferConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/buffer/BufferConfiguration.java index 86de025b1..9406ffa9b 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/buffer/BufferConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/buffer/BufferConfiguration.java @@ -231,7 +231,7 @@ public int directMemoryCacheAlignment() { * @throws IllegalArgumentException If any value is invalid */ @Override - public BufferConfiguration validate() throws IllegalArgumentException { + public BufferConfiguration validate() { checkPositive(heapArena, "Heap Arena"); checkPositive(directArena, "Direct Arena"); checkPositive(pageSize, "Page Size"); diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventloop/EventLoopConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventloop/EventLoopConfiguration.java index 94e15d98f..2422cea06 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventloop/EventLoopConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventloop/EventLoopConfiguration.java @@ -82,7 +82,8 @@ public int childWorkers() { * @return this class instance * @throws IllegalArgumentException If any value is invalid */ - public EventLoopConfiguration validate() throws IllegalArgumentException { + @Override + public EventLoopConfiguration validate() { NumberUtil.checkPositive(parentWorkers, "Parent Workers"); NumberUtil.checkPositive(childWorkers, "Child Workers"); validated = true; diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventstream/EventStreamConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventstream/EventStreamConfiguration.java index 20c914a5d..acccc085f 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventstream/EventStreamConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/eventstream/EventStreamConfiguration.java @@ -71,7 +71,8 @@ public EventStream newEventStream() { * @return this class instance * @throws IllegalArgumentException If any value is invalid */ - public EventStreamConfiguration validate() throws IllegalArgumentException { + @Override + public EventStreamConfiguration validate() { NumberUtil.checkPositive(workers, "Workers"); validated = true; return this; diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/healthcheck/HealthCheckConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/healthcheck/HealthCheckConfiguration.java index fbe4fe41e..df83f4967 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/healthcheck/HealthCheckConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/healthcheck/HealthCheckConfiguration.java @@ -82,7 +82,8 @@ public int timeInterval() { * @return this class instance * @throws IllegalArgumentException If any value is invalid */ - public HealthCheckConfiguration validate() throws IllegalArgumentException { + @Override + public HealthCheckConfiguration validate() { NumberUtil.checkPositive(workers, "Workers"); NumberUtil.checkPositive(timeInterval, "TimeInterval"); validated = true; diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/http/HttpConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/http/HttpConfiguration.java index 42cc0d41e..2c7b11fda 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/http/HttpConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/http/HttpConfiguration.java @@ -167,7 +167,8 @@ public int brotliCompressionLevel() { * @return this class instance * @throws IllegalArgumentException If any value is invalid */ - public HttpConfiguration validate() throws IllegalArgumentException { + @Override + public HttpConfiguration validate() { NumberUtil.checkPositive(maxInitialLineLength, "MaxInitialLineLength"); NumberUtil.checkPositive(maxHeaderSize, "MaxHeaderSize"); NumberUtil.checkPositive(maxChunkSize, "MaxChunkSize"); diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPair.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPair.java index bb111d701..6597184dc 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPair.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPair.java @@ -62,7 +62,7 @@ public final class CertificateKeyPair implements Runnable, Closeable { private final PrivateKey privateKey; private final boolean useOCSPStapling; - private byte[] ocspStaplingData = null; + private byte[] ocspStaplingData; private ScheduledFuture scheduledFuture; private SslContext sslContext; @@ -229,7 +229,7 @@ public CertificateKeyPair init(TlsConfiguration tlsConfiguration) throws SSLExce } } - this.sslContext = sslContextBuilder.build(); + sslContext = sslContextBuilder.build(); return this; } @@ -257,7 +257,6 @@ public void run() { return; } } catch (Exception ex) { - ex.printStackTrace(); logger.error(ex); } ocspStaplingData = null; diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/IntermediateCrypto.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/IntermediateCrypto.java index 38c07f4be..10311ff06 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/IntermediateCrypto.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/IntermediateCrypto.java @@ -3,7 +3,7 @@ import java.util.List; /** - * https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28recommended.29 + * ... */ public final class IntermediateCrypto { @@ -18,4 +18,8 @@ public final class IntermediateCrypto { Cipher.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, Cipher.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ); + + private IntermediateCrypto() { + // Prevent outside initialization + } } diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/ModernCrypto.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/ModernCrypto.java index c274a968f..50ccc01e3 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/ModernCrypto.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/ModernCrypto.java @@ -3,7 +3,7 @@ import java.util.List; /** - * https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility + * ... */ public final class ModernCrypto { @@ -14,4 +14,8 @@ public final class ModernCrypto { Cipher.TLS_AES_128_GCM_SHA256, Cipher.TLS_CHACHA20_POLY1305_SHA256 ); + + private ModernCrypto() { + // Prevent outside initialization + } } diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/OCSPClient.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/OCSPClient.java index 596ccd161..abc458ff4 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/OCSPClient.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/OCSPClient.java @@ -67,6 +67,10 @@ final class OCSPClient { private static final String OCSP_REQUEST_TYPE = "application/ocsp-request"; private static final String OCSP_RESPONSE_TYPE = "application/ocsp-response"; + private OCSPClient() { + // Prevent outside initialization + } + static OCSPResp response(X509Certificate x509Certificate, X509Certificate issuer) throws Exception { CertificateID certificateID = new CertificateID(new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuer), x509Certificate.getSerialNumber()); diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/Protocol.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/Protocol.java index eef6b6d36..143936ab3 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/Protocol.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/Protocol.java @@ -49,13 +49,15 @@ static String[] getProtocols(List protocols) { } public static Protocol get(String protocol) { - if (protocol.equalsIgnoreCase("TLSv1.1")) { + if ("TLSv1.1".equalsIgnoreCase(protocol)) { return TLS_1_1; - } else if (protocol.equalsIgnoreCase("TLSv1.2")) { + } + if ("TLSv1.2".equalsIgnoreCase(protocol)) { return TLS_1_2; - } else if (protocol.equalsIgnoreCase("TLSv1.3")) { + } + if ("TLSv1.3".equalsIgnoreCase(protocol)) { return TLS_1_3; } - throw new NoSuchElementException("Invalid Protocol: " + protocol); + throw new NoSuchElementException("Invalid Protocol: " + protocol); } } diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsClientConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsClientConfiguration.java index 96ea031d2..87efa3d32 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsClientConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsClientConfiguration.java @@ -46,7 +46,7 @@ public final class TlsClientConfiguration extends TlsConfiguration { } @Override - public TlsConfiguration validate() throws IllegalArgumentException, NullPointerException { + public TlsConfiguration validate() { super.validate(); validated = true; return this; diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfiguration.java index 9c6050030..16a50c1de 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfiguration.java @@ -38,7 +38,7 @@ public abstract class TlsConfiguration implements Configuration certificateKeyPairMap = new HashMap<>(); @JsonProperty("enabled") - private boolean enabled = false; + private boolean enabled; @JsonProperty("ciphers") protected List ciphers; @@ -121,7 +121,7 @@ public CertificateKeyPair mapping(String fqdn) { // If `null` then it means mapping was not found with FQDN. // We'll try wildcard now. if (certificateKeyPair == null) { - fqdn = "*" + fqdn.substring(fqdn.indexOf(".")); + fqdn = '*' + fqdn.substring(fqdn.indexOf('.')); certificateKeyPair = certificateKeyPairMap.get(fqdn); if (certificateKeyPair != null) { return certificateKeyPair; @@ -278,7 +278,8 @@ public boolean acceptAllCerts() { * @throws IllegalArgumentException If any value is invalid * @throws NullPointerException If any value is null */ - public TlsConfiguration validate() throws IllegalArgumentException, NullPointerException { + @Override + public TlsConfiguration validate() { ListUtil.checkNonEmpty(ciphers, "Ciphers"); ListUtil.checkNonEmpty(protocols, "Protocols"); Objects.requireNonNull(mutualTLS, "MutualTLS"); diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsServerConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsServerConfiguration.java index 227b4f5bd..578145f20 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsServerConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/tls/TlsServerConfiguration.java @@ -47,7 +47,7 @@ public final class TlsServerConfiguration extends TlsConfiguration { } @Override - public TlsConfiguration validate() throws IllegalArgumentException, NullPointerException { + public TlsConfiguration validate() { super.validate(); validated = true; return this; diff --git a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/transport/TransportConfiguration.java b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/transport/TransportConfiguration.java index 3a2b4e39f..1fd5a84be 100644 --- a/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/transport/TransportConfiguration.java +++ b/configuration/src/main/java/com/shieldblaze/expressgateway/configuration/transport/TransportConfiguration.java @@ -146,7 +146,7 @@ public RecvByteBufAllocator recvByteBufAllocator() { * TCP Connection Backlog */ public TransportConfiguration setTcpConnectionBacklog(int TCPConnectionBacklog) { - this.tcpConnectionBacklog = TCPConnectionBacklog; + tcpConnectionBacklog = TCPConnectionBacklog; return this; } @@ -192,7 +192,7 @@ public TransportConfiguration setSocketSendBufferSize(int socketSendBufferSize) * TCP Fast Open Maximum Pending Requests */ public TransportConfiguration setTcpFastOpenMaximumPendingRequests(int TCPFastOpenMaximumPendingRequests) { - this.tcpFastOpenMaximumPendingRequests = TCPFastOpenMaximumPendingRequests; + tcpFastOpenMaximumPendingRequests = TCPFastOpenMaximumPendingRequests; return this; } @@ -240,7 +240,8 @@ public int connectionIdleTimeout() { * @throws IllegalArgumentException If any value is invalid * @throws NullPointerException If any value is null */ - public TransportConfiguration validate() throws IllegalArgumentException, NullPointerException { + @Override + public TransportConfiguration validate() { Objects.requireNonNull(transportType, "Transport Type"); Objects.requireNonNull(receiveBufferAllocationType, "Receive Buffer Allocation Type"); Objects.requireNonNull(receiveBufferSizes, "Receive Buffer Sizes"); @@ -251,7 +252,8 @@ public TransportConfiguration validate() throws IllegalArgumentException, NullPo if (transportType == TransportType.EPOLL && !Epoll.isAvailable()) { throw new IllegalArgumentException("Epoll is not available"); - } else if (transportType == TransportType.IO_URING && !IOUring.isAvailable()) { + } + if (transportType == TransportType.IO_URING && !IOUring.isAvailable()) { throw new IllegalArgumentException("IOUring is not available"); } @@ -262,7 +264,8 @@ public TransportConfiguration validate() throws IllegalArgumentException, NullPo if (receiveBufferSizes[2] > 65535) { throw new IllegalArgumentException("Maximum Receive Buffer Size Cannot Be Greater Than 65535"); - } else if (receiveBufferSizes[2] < 64) { + } + if (receiveBufferSizes[2] < 64) { throw new IllegalArgumentException("Maximum Receive Buffer Size Cannot Be Less Than 64"); } @@ -271,7 +274,7 @@ public TransportConfiguration validate() throws IllegalArgumentException, NullPo } if (receiveBufferSizes[1] < 64 || receiveBufferSizes[1] > receiveBufferSizes[2] || receiveBufferSizes[1] < receiveBufferSizes[0]) { - throw new IllegalArgumentException("Initial Receive Buffer Must Be In Range Of " + receiveBufferSizes[0] + "-" + receiveBufferSizes[2]); + throw new IllegalArgumentException("Initial Receive Buffer Must Be In Range Of " + receiveBufferSizes[0] + '-' + receiveBufferSizes[2]); } } else { if (receiveBufferSizes.length != 1) { diff --git a/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPairTest.java b/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPairTest.java index 712ce9b19..745e5de2e 100644 --- a/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPairTest.java +++ b/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/CertificateKeyPairTest.java @@ -40,7 +40,7 @@ class CertificateKeyPairTest { @Test - void clientECCCertificateKeyTest() throws CertificateException, SSLException { + void clientECCCertificateKeyTest() throws Exception { SelfSignedCertificate selfSignedCertificate = new SelfSignedCertificate("www.shieldblaze.com", "EC", 256); CertificateKeyPair certificateKeyPair = CertificateKeyPair.forClient(Collections.singletonList(selfSignedCertificate.cert()), selfSignedCertificate.key()); @@ -55,7 +55,7 @@ void clientECCCertificateKeyTest() throws CertificateException, SSLException { } @Test - void clientRSACertificateKeyTest() throws CertificateException, SSLException { + void clientRSACertificateKeyTest() throws Exception { SelfSignedCertificate selfSignedCertificate = new SelfSignedCertificate("www.shieldblaze.com", "RSA", 2048); CertificateKeyPair certificateKeyPair = CertificateKeyPair.forClient(Collections.singletonList(selfSignedCertificate.cert()), selfSignedCertificate.key()); @@ -71,7 +71,7 @@ void clientRSACertificateKeyTest() throws CertificateException, SSLException { @Test @Disabled("Need Certificate with it's Private Key to run this test") - void ocspStaplingTest() throws IOException, CertificateException, InterruptedException { + void ocspStaplingTest() throws Exception { OpenSsl.ensureAvailability(); SelfSignedCertificate selfSignedCertificate = new SelfSignedCertificate("www.shieldblaze.com", "EC", 256); diff --git a/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfigurationTest.java b/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfigurationTest.java index f02b05a4a..ebdc19bf6 100644 --- a/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfigurationTest.java +++ b/configuration/src/test/java/com/shieldblaze/expressgateway/configuration/tls/TlsConfigurationTest.java @@ -79,7 +79,7 @@ void sessionCacheSizeTest() { } @Test - void addMappingTest() throws CertificateException, SSLException { + void addMappingTest() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate("www.shieldblaze.com", "EC", 256); CertificateKeyPair certificateKeyPair = CertificateKeyPair.forServer(Collections.singletonList(ssc.cert()), ssc.key(), false); @@ -91,7 +91,7 @@ void addMappingTest() throws CertificateException, SSLException { } @Test - void addMappingWildcardTest() throws CertificateException, SSLException { + void addMappingWildcardTest() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate("www.shieldblaze.com", "EC", 256); CertificateKeyPair certificateKeyPair = CertificateKeyPair.forServer(Collections.singletonList(ssc.cert()), ssc.key(), false); @@ -104,7 +104,7 @@ void addMappingWildcardTest() throws CertificateException, SSLException { } @Test - void removeMappingTest() throws CertificateException, SSLException { + void removeMappingTest() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate("www.shieldblaze.com", "EC", 256); CertificateKeyPair certificateKeyPair = CertificateKeyPair.forServer(Collections.singletonList(ssc.cert()), ssc.key(), false); diff --git a/core/src/main/java/com/shieldblaze/expressgateway/core/factory/BootstrapFactory.java b/core/src/main/java/com/shieldblaze/expressgateway/core/factory/BootstrapFactory.java index a08ae01cc..7576a04f6 100644 --- a/core/src/main/java/com/shieldblaze/expressgateway/core/factory/BootstrapFactory.java +++ b/core/src/main/java/com/shieldblaze/expressgateway/core/factory/BootstrapFactory.java @@ -87,7 +87,7 @@ public static Bootstrap udp(ConfigurationContext configurationContext, EventLoop .channelFactory(() -> { if (configurationContext.transportConfiguration().transportType() == TransportType.IO_URING) { IOUringDatagramChannel datagramChannel = new IOUringDatagramChannel(); - datagramChannel.config().setOption(IOUringChannelOption.SO_REUSEPORT, true); + datagramChannel.config().setOption(UnixChannelOption.SO_REUSEPORT, true); return datagramChannel; } else if (configurationContext.transportConfiguration().transportType() == TransportType.EPOLL) { EpollDatagramChannel datagramChannel = new EpollDatagramChannel(); diff --git a/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/ConnectionTimeoutHandler.java b/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/ConnectionTimeoutHandler.java index 75b3212e1..6565e56bd 100644 --- a/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/ConnectionTimeoutHandler.java +++ b/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/ConnectionTimeoutHandler.java @@ -64,7 +64,7 @@ public enum State { * @param isUpstream Set to {@code true} if this Instance is placed in Upstream Pipeline */ public ConnectionTimeoutHandler(Duration timeout, boolean isUpstream) { - this.timeoutNanos = timeout.toNanos(); + timeoutNanos = timeout.toNanos(); this.isUpstream = isUpstream; } diff --git a/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/SNIHandler.java b/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/SNIHandler.java index 4f136a008..4dc5cfbfe 100644 --- a/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/SNIHandler.java +++ b/core/src/main/java/com/shieldblaze/expressgateway/core/handlers/SNIHandler.java @@ -67,7 +67,7 @@ protected void onLookupComplete(ChannelHandlerContext ctx, String hostname, Futu replaceHandler(ctx, certificateKeyPair); } - protected void replaceHandler(ChannelHandlerContext ctx, CertificateKeyPair certificateKeyPair) { + private void replaceHandler(ChannelHandlerContext ctx, CertificateKeyPair certificateKeyPair) { SslHandler sslHandler = null; try { sslHandler = new TLSHandler(certificateKeyPair.sslContext().newHandler(ctx.alloc()).engine()); diff --git a/core/src/main/java/com/shieldblaze/expressgateway/core/loadbalancer/L4LoadBalancer.java b/core/src/main/java/com/shieldblaze/expressgateway/core/loadbalancer/L4LoadBalancer.java index ce5dcd892..6c4220bd8 100644 --- a/core/src/main/java/com/shieldblaze/expressgateway/core/loadbalancer/L4LoadBalancer.java +++ b/core/src/main/java/com/shieldblaze/expressgateway/core/loadbalancer/L4LoadBalancer.java @@ -76,11 +76,11 @@ public abstract class L4LoadBalancer { * @param channelHandler {@link ChannelHandler} to use for handling traffic * @throws NullPointerException If a required parameter if {@code null} */ - public L4LoadBalancer(String name, - @NonNull InetSocketAddress bindAddress, - @NonNull L4FrontListener l4FrontListener, - @NonNull ConfigurationContext configurationContext, - ChannelHandler channelHandler) { + protected L4LoadBalancer(String name, + @NonNull InetSocketAddress bindAddress, + @NonNull L4FrontListener l4FrontListener, + @NonNull ConfigurationContext configurationContext, + ChannelHandler channelHandler) { if (name != null && !name.isEmpty()) { this.name = name; @@ -89,11 +89,11 @@ public L4LoadBalancer(String name, this.bindAddress = bindAddress; this.l4FrontListener = l4FrontListener; this.configurationContext = configurationContext; - this.eventStream = configurationContext.eventStreamConfiguration().newEventStream(); + eventStream = configurationContext.eventStreamConfiguration().newEventStream(); this.channelHandler = channelHandler; - this.byteBufAllocator = new PooledByteBufAllocatorFactory(configurationContext.bufferConfiguration()).instance(); - this.eventLoopFactory = new EventLoopFactory(configurationContext); + byteBufAllocator = new PooledByteBufAllocatorFactory(configurationContext.bufferConfiguration()).instance(); + eventLoopFactory = new EventLoopFactory(configurationContext); l4FrontListener.l4LoadBalancer(this); } diff --git a/healthcheck/src/main/java/com/shieldblaze/expressgateway/healthcheck/HealthCheck.java b/healthcheck/src/main/java/com/shieldblaze/expressgateway/healthcheck/HealthCheck.java index 089fd8f78..10b35866d 100644 --- a/healthcheck/src/main/java/com/shieldblaze/expressgateway/healthcheck/HealthCheck.java +++ b/healthcheck/src/main/java/com/shieldblaze/expressgateway/healthcheck/HealthCheck.java @@ -40,7 +40,7 @@ public abstract class HealthCheck implements Runnable { * @param socketAddress {@link InetSocketAddress} of remote host to check * @param timeout Timeout in seconds for health check */ - public HealthCheck(InetSocketAddress socketAddress, Duration timeout) { + protected HealthCheck(InetSocketAddress socketAddress, Duration timeout) { this(socketAddress, timeout, 100); } @@ -51,10 +51,10 @@ public HealthCheck(InetSocketAddress socketAddress, Duration timeout) { * @param timeout Timeout for health check * @param samples Number of samples to use for evaluating Health of remote host */ - public HealthCheck(InetSocketAddress socketAddress, Duration timeout, int samples) { + protected HealthCheck(InetSocketAddress socketAddress, Duration timeout, int samples) { this.socketAddress = socketAddress; this.timeout = (int) timeout.toMillis(); - this.queue = EvictingQueue.create(samples); + queue = EvictingQueue.create(samples); } /** diff --git a/healthcheck/src/test/java/com/shieldblaze/expressgateway/healthcheck/l7/HTTPServer.java b/healthcheck/src/test/java/com/shieldblaze/expressgateway/healthcheck/l7/HTTPServer.java index 35e97533f..b472ee9fb 100644 --- a/healthcheck/src/test/java/com/shieldblaze/expressgateway/healthcheck/l7/HTTPServer.java +++ b/healthcheck/src/test/java/com/shieldblaze/expressgateway/healthcheck/l7/HTTPServer.java @@ -24,13 +24,13 @@ import java.net.ServerSocket; import java.net.Socket; -final class HTTPServer extends Thread{ +final class HTTPServer extends Thread { - private final static String CRLF = "\r\n"; + private static final String CRLF = "\r\n"; private final String responseStatus; private final int port; - public HTTPServer(String responseStatus, int port) { + HTTPServer(String responseStatus, int port) { this.responseStatus = responseStatus; this.port = port; } @@ -39,14 +39,14 @@ public HTTPServer(String responseStatus, int port) { public void run() { try (ServerSocket serverSocket = new ServerSocket(port, 1000, InetAddress.getByName("127.0.0.1"))) { Socket clientSocket = serverSocket.accept(); - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true); + PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())), true); out.write("HTTP/1.1 " + responseStatus + CRLF); - out.write("Server: Apache/0.8.4"+ CRLF); - out.write("Content-Type: text/html"+ CRLF); - out.write("Content-Length: 17"+ CRLF); + out.write("Server: Apache/0.8.4" + CRLF); + out.write("Content-Type: text/html" + CRLF); + out.write("Content-Length: 17" + CRLF); out.write(CRLF); - out.write("OK"+ CRLF); + out.write("OK" + CRLF); out.flush(); } catch (Exception ex) { ex.printStackTrace(); diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/DownstreamHandler.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/DownstreamHandler.java index cb80b9859..1469afb50 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/DownstreamHandler.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/DownstreamHandler.java @@ -239,7 +239,7 @@ private void normalizeInboundHttp11ToHttp2(Object o) { Http2DataFrame dataFrame = new DefaultHttp2DataFrame(httpContent.content(), false); dataFrame.stream(httpConnection.lastTranslatedStreamProperty().clientStream()); - Http2Headers http2Headers = HttpConversionUtil.toHttp2Headers(lastHttpContent.trailingHeaders(), true); + Http2Headers http2Headers = toHttp2Headers(lastHttpContent.trailingHeaders(), true); Http2HeadersFrame http2HeadersFrame = new DefaultHttp2HeadersFrame(http2Headers, true); http2HeadersFrame.stream(httpConnection.lastTranslatedStreamProperty().clientStream()); httpConnection.clearTranslatedStreamProperty(); diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Headers.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Headers.java index 0876a081d..a51fb18d8 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Headers.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Headers.java @@ -21,4 +21,8 @@ public final class Headers { public static final String X_FORWARDED_FOR = "x-forwarded-for"; public static final String X_FORWARDED_PROTO = "x-forwarded-proto"; + + private Headers() { + // Prevent outside initialization + } } diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http11ServerInboundHandler.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http11ServerInboundHandler.java index 679799e57..fdcaff410 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http11ServerInboundHandler.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http11ServerInboundHandler.java @@ -67,7 +67,7 @@ public class Http11ServerInboundHandler extends ChannelInboundHandlerAdapter imp public Http11ServerInboundHandler(HTTPLoadBalancer httpLoadBalancer, boolean isTLSConnection) { this.httpLoadBalancer = httpLoadBalancer; - this.bootstrapper = new Bootstrapper(httpLoadBalancer); + bootstrapper = new Bootstrapper(httpLoadBalancer); this.isTLSConnection = isTLSConnection; } @@ -150,7 +150,7 @@ private WebSocketUpgradeProperty validateWebSocketRequest(ChannelHandlerContext } // If 'Connection:Upgrade' and 'Upgrade:WebSocket' then begin WebSocket Upgrade Process. - if (headers.get(CONNECTION).equalsIgnoreCase("Upgrade") && headers.get(UPGRADE).equalsIgnoreCase("WebSocket")) { + if ("Upgrade".equalsIgnoreCase(headers.get(CONNECTION)) && "WebSocket".equalsIgnoreCase(headers.get(UPGRADE))) { // Handshake for WebSocket String uri = webSocketURL(httpRequest); @@ -163,7 +163,7 @@ private WebSocketUpgradeProperty validateWebSocketRequest(ChannelHandlerContext handshaker.handshake(ctx.channel(), httpRequest); } - return new WebSocketUpgradeProperty(((InetSocketAddress) ctx.channel().remoteAddress()), URI.create(uri), subProtocol, ctx.channel()); + return new WebSocketUpgradeProperty((InetSocketAddress) ctx.channel().remoteAddress(), URI.create(uri), subProtocol, ctx.channel()); } else { return null; } @@ -185,7 +185,6 @@ public void channelInactive(ChannelHandlerContext ctx) { close(); } - @SuppressWarnings("StatementWithEmptyBody") @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { try { diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http2ServerInboundHandler.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http2ServerInboundHandler.java index 60c7b5cf3..8e72b20f8 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http2ServerInboundHandler.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/Http2ServerInboundHandler.java @@ -54,7 +54,7 @@ public final class Http2ServerInboundHandler extends ChannelInboundHandlerAdapte public Http2ServerInboundHandler(HTTPLoadBalancer httpLoadBalancer, boolean isTLSConnection) { this.httpLoadBalancer = httpLoadBalancer; - this.bootstrapper = new Bootstrapper(httpLoadBalancer); + bootstrapper = new Bootstrapper(httpLoadBalancer); this.isTLSConnection = isTLSConnection; } diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/alpn/ALPNHandlerBuilder.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/alpn/ALPNHandlerBuilder.java index 182c3ad83..8602d0a34 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/alpn/ALPNHandlerBuilder.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/alpn/ALPNHandlerBuilder.java @@ -64,7 +64,7 @@ public ALPNHandlerBuilder withHTTP2ChannelHandler(String name, ChannelHandler ch * @return {@linkplain ALPNHandler Instance} */ public ALPNHandler build() { - if (!(HTTP1ChannelHandlers.size() > 0 || HTTP2ChannelHandlers.size() > 0)) { + if (!(!HTTP1ChannelHandlers.isEmpty() || !HTTP2ChannelHandlers.isEmpty())) { throw new IllegalArgumentException("There must be at least one Handler for both HTTP/2 and HTTP/1.1"); } return new ALPNHandler(HTTP1ChannelHandlers, HTTP2ChannelHandlers); diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/compression/CompressionUtil.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/compression/CompressionUtil.java index 9ddc637ab..9fcd7b3a6 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/compression/CompressionUtil.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/compression/CompressionUtil.java @@ -69,13 +69,17 @@ public static boolean isCompressible(String contentType) { public static String checkCompressibleForHttp2(Http2Headers headers, String acceptEncoding, long compressionThreshold) { if (headers.contains(CONTENT_ENCODING)) { return null; - } else if (acceptEncoding == null) { + } + if (acceptEncoding == null) { return null; - } else if (!headers.contains(CONTENT_TYPE)) { + } + if (!headers.contains(CONTENT_TYPE)) { return null; - } else if (!MIME_TYPES.contains(headers.get(CONTENT_TYPE).toString().split(";")[0])) { + } + if (!MIME_TYPES.contains(headers.get(CONTENT_TYPE).toString().split(";")[0])) { return null; - } else if (headers.contains(CONTENT_LENGTH)) { + } + if (headers.contains(CONTENT_LENGTH)) { if (!(headers.getLong(CONTENT_LENGTH, -1) >= compressionThreshold)) { return null; } @@ -141,4 +145,8 @@ private static String determineEncoding(String acceptEncoding) { } return null; } + + private CompressionUtil() { + // Prevent outside initialization + } } diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/Bootstrapper.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/Bootstrapper.java index 790549017..2c79d6ee7 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/Bootstrapper.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/Bootstrapper.java @@ -49,8 +49,8 @@ final class Bootstrapper { Bootstrapper(HTTPLoadBalancer httpLoadBalancer) { this.httpLoadBalancer = httpLoadBalancer; - this.eventLoopGroup = httpLoadBalancer.eventLoopFactory().childGroup(); - this.byteBufAllocator = httpLoadBalancer.byteBufAllocator(); + eventLoopGroup = httpLoadBalancer.eventLoopFactory().childGroup(); + byteBufAllocator = httpLoadBalancer.byteBufAllocator(); } WebSocketConnection newInit(Node node, WebSocketUpgradeProperty wsProperty) { diff --git a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketDownstreamHandler.java b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketDownstreamHandler.java index 5a2fdfb15..2ffa75ffa 100644 --- a/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketDownstreamHandler.java +++ b/protocol-http/src/main/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketDownstreamHandler.java @@ -55,7 +55,6 @@ public void channelInactive(ChannelHandlerContext ctx) { close(); } - @SuppressWarnings("StatementWithEmptyBody") @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { try { diff --git a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/BrotliCompressionTest.java b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/BrotliCompressionTest.java index 1aea39838..71d3ff8f5 100644 --- a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/BrotliCompressionTest.java +++ b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/BrotliCompressionTest.java @@ -53,7 +53,7 @@ static void shutdown() { } @Test - void brotliOnlyTest() throws IOException, InterruptedException { + void brotliOnlyTest() throws Exception { HttpRequest httpRequest = HttpRequest.newBuilder() .GET() .uri(URI.create("https://localhost:9110")) @@ -72,7 +72,7 @@ void brotliOnlyTest() throws IOException, InterruptedException { } @Test - void brotliAndGzipTest() throws IOException, InterruptedException { + void brotliAndGzipTest() throws Exception { HttpRequest httpRequest = HttpRequest.newBuilder() .GET() .uri(URI.create("https://localhost:9110")) @@ -91,7 +91,7 @@ void brotliAndGzipTest() throws IOException, InterruptedException { } @Test - void brotliGzipAndDeflateTest() throws IOException, InterruptedException { + void brotliGzipAndDeflateTest() throws Exception { HttpRequest httpRequest = HttpRequest.newBuilder() .GET() .uri(URI.create("https://localhost:9110")) diff --git a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/DeflateCompressionTest.java b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/DeflateCompressionTest.java index e0226d96e..f5bd824c9 100644 --- a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/DeflateCompressionTest.java +++ b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/DeflateCompressionTest.java @@ -53,7 +53,7 @@ static void shutdown() { } @Test - void deflateOnlyTest() throws DataFormatException, IOException, InterruptedException { + void deflateOnlyTest() throws Exception { HttpRequest httpRequest = HttpRequest.newBuilder() .GET() .uri(URI.create("https://localhost:9110")) diff --git a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/GzipCompressionTest.java b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/GzipCompressionTest.java index 1a34a118c..889e11685 100644 --- a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/GzipCompressionTest.java +++ b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/GzipCompressionTest.java @@ -53,7 +53,7 @@ static void shutdown() { } @Test - void gzipOnlyTest() throws IOException, InterruptedException { + void gzipOnlyTest() throws Exception { HttpRequest httpRequest = HttpRequest.newBuilder() .GET() .uri(URI.create("https://localhost:9110")) @@ -72,7 +72,7 @@ void gzipOnlyTest() throws IOException, InterruptedException { } @Test - void gzipAndDeflateTest() throws IOException, InterruptedException { + void gzipAndDeflateTest() throws Exception { HttpRequest httpRequest = HttpRequest.newBuilder() .GET() .uri(URI.create("https://localhost:9110")) diff --git a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/TestableHttpLoadBalancer.java b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/TestableHttpLoadBalancer.java index ba928eddd..52981215a 100644 --- a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/TestableHttpLoadBalancer.java +++ b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/TestableHttpLoadBalancer.java @@ -155,9 +155,9 @@ public Builder withTlsBackendEnabled(boolean tlsBackendEnabled) { public TestableHttpLoadBalancer build() { TestableHttpLoadBalancer testableHttpLoadBalancer = new TestableHttpLoadBalancer(); - testableHttpLoadBalancer.tlsClientEnabled = this.tlsClientEnabled; - testableHttpLoadBalancer.tlsServerEnabled = this.tlsServerEnabled; - testableHttpLoadBalancer.tlsBackendEnabled = this.tlsBackendEnabled; + testableHttpLoadBalancer.tlsClientEnabled = tlsClientEnabled; + testableHttpLoadBalancer.tlsServerEnabled = tlsServerEnabled; + testableHttpLoadBalancer.tlsBackendEnabled = tlsBackendEnabled; return testableHttpLoadBalancer; } } diff --git a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketHttpUpgradeHandler.java b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketHttpUpgradeHandler.java index 6f089ba13..3c26ac123 100644 --- a/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketHttpUpgradeHandler.java +++ b/protocol-http/src/test/java/com/shieldblaze/expressgateway/protocol/http/websocket/WebSocketHttpUpgradeHandler.java @@ -43,7 +43,7 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) { } } - private String uri(FullHttpRequest msg) { + private static String uri(FullHttpRequest msg) { return "ws://" + msg.headers().get(HttpHeaderNames.HOST) + msg.uri(); } } diff --git a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/Bootstrapper.java b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/Bootstrapper.java index 69af03571..faade19b9 100644 --- a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/Bootstrapper.java +++ b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/Bootstrapper.java @@ -41,8 +41,8 @@ final class Bootstrapper { Bootstrapper(L4LoadBalancer l4LoadBalancer) { this.l4LoadBalancer = l4LoadBalancer; - this.eventLoopGroup = l4LoadBalancer.eventLoopFactory().childGroup(); - this.byteBufAllocator = l4LoadBalancer.byteBufAllocator(); + eventLoopGroup = l4LoadBalancer.eventLoopFactory().childGroup(); + byteBufAllocator = l4LoadBalancer.byteBufAllocator(); } TCPConnection newInit(Node node, Channel channel) { diff --git a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/DownstreamHandler.java b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/DownstreamHandler.java index 387380159..05e149a3c 100644 --- a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/DownstreamHandler.java +++ b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/DownstreamHandler.java @@ -37,7 +37,7 @@ final class DownstreamHandler extends ChannelInboundHandlerAdapter { DownstreamHandler(Channel upstream, Node node) { this.upstream = upstream; this.node = node; - this.upstreamAddress = (InetSocketAddress) upstream.remoteAddress(); + upstreamAddress = (InetSocketAddress) upstream.remoteAddress(); } @Override @@ -45,13 +45,17 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { upstream.writeAndFlush(msg, upstream.voidPromise()); // Write Data back to Client } + /** + * Downstream Channel is closed, so we close the Upstream Channel as well. + */ @Override public void channelInactive(ChannelHandlerContext ctx) { if (logger.isInfoEnabled()) { logger.info("Closing Upstream {} and Downstream {} Channel", - upstreamAddress.getAddress().getHostAddress() + ":" + upstreamAddress.getPort(), - node.socketAddress().getAddress().getHostAddress() + ":" + node.socketAddress().getPort()); + upstreamAddress.getAddress().getHostAddress() + ':' + upstreamAddress.getPort(), + node.socketAddress().getAddress().getHostAddress() + ':' + node.socketAddress().getPort()); } + upstream.close(); // Close Upstream Channel ctx.channel().close(); // Close Downstream Channel } diff --git a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/ServerInitializer.java b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/ServerInitializer.java index b1abaf646..a83e27bf8 100644 --- a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/ServerInitializer.java +++ b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/ServerInitializer.java @@ -44,20 +44,22 @@ protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(l4LoadBalancer.connectionTracker()); - Duration timeout = Duration.ofMillis(l4LoadBalancer.configurationContext() - .transportConfiguration() - .connectionIdleTimeout()); - + // Add Connection Timeout Handler + Duration timeout = Duration.ofMillis(l4LoadBalancer.configurationContext().transportConfiguration().connectionIdleTimeout()); pipeline.addLast(new ConnectionTimeoutHandler(timeout, true)); boolean available = l4LoadBalancer.configurationContext().tlsServerConfiguration().enabled(); - logger.debug("TLS for Server available: {}", available); + // Add SNI Handler if TLS is enabled if (available) { pipeline.addLast(new SNIHandler(l4LoadBalancer.configurationContext().tlsServerConfiguration())); } + // Add Upstream Handler to handle Upstream Connections pipeline.addLast(new UpstreamHandler(l4LoadBalancer)); + + // Log TLS availability + logger.debug("TLS for Server available: {}", available); } @Override diff --git a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPConnection.java b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPConnection.java index 643c33ed9..bd394408e 100644 --- a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPConnection.java +++ b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPConnection.java @@ -19,14 +19,23 @@ import com.shieldblaze.expressgateway.backend.Connection; import com.shieldblaze.expressgateway.backend.Node; +import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; +/** + * Downstream {@link Connection} for TCP Protocol + */ final class TCPConnection extends Connection { TCPConnection(Node node) { super(node); } + /** + * Process Backlog + * + * @param channelFuture If the {@link ChannelFuture} is successful, write the backlog to the {@link Channel} + */ @Override protected void processBacklog(ChannelFuture channelFuture) { if (channelFuture.isSuccess()) { diff --git a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPListener.java b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPListener.java index 42cb3a457..d7da47d16 100644 --- a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPListener.java +++ b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/TCPListener.java @@ -52,8 +52,8 @@ public class TCPListener extends L4FrontListener { public L4FrontListenerStartupEvent start() { L4FrontListenerStartupEvent l4FrontListenerStartupEvent = new L4FrontListenerStartupEvent(); - // If ChannelFutureList is not 0 then this listener is already started and we won't start it again. - if (channelFutures.size() != 0) { + // If ChannelFutureList is not empty then this listener is already started and we won't start it again. + if (!channelFutures.isEmpty()) { l4FrontListenerStartupEvent.markFailure(new IllegalArgumentException("Listener has already started and cannot be restarted.")); return l4FrontListenerStartupEvent; } @@ -83,7 +83,7 @@ public L4FrontListenerStartupEvent start() { .channelFactory(() -> { if (transportConfiguration.transportType() == TransportType.IO_URING) { IOUringServerSocketChannel serverSocketChannel = new IOUringServerSocketChannel(); - serverSocketChannel.config().setOption(IOUringChannelOption.SO_REUSEPORT, true); + serverSocketChannel.config().setOption(UnixChannelOption.SO_REUSEPORT, true); return serverSocketChannel; } else if (transportConfiguration.transportType() == TransportType.EPOLL) { EpollServerSocketChannel serverSocketChannel = new EpollServerSocketChannel(); @@ -128,7 +128,16 @@ public L4FrontListenerStartupEvent start() { public L4FrontListenerStopEvent stop() { L4FrontListenerStopEvent l4FrontListenerStopEvent = new L4FrontListenerStopEvent(); + // If ChannelFutureList is empty then this listener is already stopped and we won't stop it again. + if (channelFutures.isEmpty()) { + l4FrontListenerStopEvent.markFailure(new IllegalArgumentException("Listener has already stopped and cannot be stopped again.")); + return l4FrontListenerStopEvent; + } + + // Close all ChannelFutures channelFutures.forEach(channelFuture -> channelFuture.channel().close()); + + // Add listener to last ChannelFuture to notify all listeners channelFutures.get(channelFutures.size() - 1).channel().closeFuture().addListener(future -> { if (future.isSuccess()) { channelFutures.clear(); diff --git a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/UpstreamHandler.java b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/UpstreamHandler.java index 1880fc600..a2e086495 100644 --- a/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/UpstreamHandler.java +++ b/protocol-tcp/src/main/java/com/shieldblaze/expressgateway/protocol/tcp/UpstreamHandler.java @@ -45,6 +45,7 @@ final class UpstreamHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { try { + // Get the next node from the cluster to handle this request L4Response response = (L4Response) l4LoadBalancer.defaultCluster().nextNode(new L4Request((InetSocketAddress) ctx.channel().remoteAddress())); // Close the connection since we have no node available to handle this request @@ -53,6 +54,7 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { return; } + // Create a new TCPConnection and add it to the node tcpConnection = bootstrapper.newInit(response.node(), ctx.channel()); response.node().addConnection(tcpConnection); } catch (Exception ex) { @@ -73,20 +75,22 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { @Override public void channelInactive(ChannelHandlerContext ctx) { if (logger.isInfoEnabled()) { - InetSocketAddress socketAddress = ((InetSocketAddress) ctx.channel().remoteAddress()); + InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress(); if (tcpConnection == null || tcpConnection.socketAddress() == null) { - logger.info("Closing Upstream {}", socketAddress.getAddress().getHostAddress() + ":" + socketAddress.getPort()); + logger.info("Closing Upstream {}", socketAddress.getAddress().getHostAddress() + ':' + socketAddress.getPort()); } else { logger.info("Closing Upstream {} and Downstream {} Channel", - socketAddress.getAddress().getHostAddress() + ":" + socketAddress.getPort(), - tcpConnection.socketAddress().getAddress().getHostAddress() + ":" + tcpConnection.socketAddress().getPort()); + socketAddress.getAddress().getHostAddress() + ':' + socketAddress.getPort(), + tcpConnection.socketAddress().getAddress().getHostAddress() + ':' + tcpConnection.socketAddress().getPort()); } } + // Close the upstream channel if it is active if (ctx.channel().isActive()) { ctx.channel().close(); } + // Close the downstream channel if it is active if (tcpConnection != null && tcpConnection.state() == Connection.State.CONNECTED_AND_ACTIVE) { tcpConnection.close(); } diff --git a/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/DownstreamHandler.java b/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/DownstreamHandler.java index b5add7237..e694fb9ef 100644 --- a/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/DownstreamHandler.java +++ b/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/DownstreamHandler.java @@ -50,8 +50,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { public void channelInactive(ChannelHandlerContext ctx) { if (logger.isDebugEnabled()) { logger.debug("Closing Upstream {} and Downstream {} Channel", - socketAddress.getAddress().getHostAddress() + ":" + socketAddress.getPort(), - udpConnection.socketAddress().getAddress().getHostAddress() + ":" + udpConnection.socketAddress().getPort()); + socketAddress.getAddress().getHostAddress() + ':' + socketAddress.getPort(), + udpConnection.socketAddress().getAddress().getHostAddress() + ':' + udpConnection.socketAddress().getPort()); } udpConnection.close(); diff --git a/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UDPListener.java b/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UDPListener.java index 1f37afa02..e2cf921ea 100644 --- a/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UDPListener.java +++ b/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UDPListener.java @@ -47,7 +47,7 @@ public L4FrontListenerStartupEvent start() { L4FrontListenerStartupEvent l4FrontListenerStartupEvent = new L4FrontListenerStartupEvent(); // If ChannelFutureList is not 0 then this listener is already started and we won't start it again. - if (channelFutures.size() != 0) { + if (!channelFutures.isEmpty()) { l4FrontListenerStartupEvent.markFailure(new IllegalArgumentException("Listener has already started and cannot be restarted.")); return l4FrontListenerStartupEvent; } @@ -123,7 +123,7 @@ public L4FrontListenerShutdownEvent shutdown() { l4LoadBalancer().eventLoopFactory().parentGroup().shutdownGracefully(); l4LoadBalancer().eventLoopFactory().childGroup().shutdownGracefully(); shutdownEvent.markSuccess(null); - }, GlobalExecutors.INSTANCE.executorService()); + }, GlobalExecutors.executorService()); return shutdownEvent; } diff --git a/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UpstreamHandler.java b/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UpstreamHandler.java index 3da3be58f..9a4561515 100644 --- a/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UpstreamHandler.java +++ b/protocol-udp/src/main/java/com/shieldblaze/expressgateway/protocol/udp/UpstreamHandler.java @@ -29,6 +29,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import java.io.Closeable; import java.net.InetSocketAddress; import java.time.Duration; import java.util.Map; @@ -45,7 +46,7 @@ final class UpstreamHandler extends ChannelInboundHandlerAdapter implements Entr UpstreamHandler(L4LoadBalancer l4LoadBalancer) { this.l4LoadBalancer = l4LoadBalancer; - this.bootstrapper = new Bootstrapper(l4LoadBalancer, l4LoadBalancer.eventLoopFactory().childGroup(), l4LoadBalancer.byteBufAllocator()); + bootstrapper = new Bootstrapper(l4LoadBalancer, l4LoadBalancer.eventLoopFactory().childGroup(), l4LoadBalancer.byteBufAllocator()); connectionMap = new SelfExpiringMap<>( new ConcurrentHashMap<>(), Duration.ofMillis(l4LoadBalancer.configurationContext().transportConfiguration().connectionIdleTimeout()), @@ -79,7 +80,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.info("Closing All Upstream and Downstream Channels"); - ((SelfExpiringMap) connectionMap).close(); + ((Closeable) connectionMap).close(); connectionMap.forEach((socketAddress, udpConnection) -> udpConnection.close()); connectionMap.clear(); } diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/ExceptionHandlerController.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/ExceptionHandlerController.java index b098fe7ed..949f58a12 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/ExceptionHandlerController.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/ExceptionHandlerController.java @@ -27,7 +27,7 @@ @ControllerAdvice public class ExceptionHandlerController { - @ExceptionHandler(value = Exception.class) + @ExceptionHandler(Exception.class) public ResponseEntity handler(Exception ex) { return FastBuilder.error(ErrorBase.INVALID_REQUEST, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); } diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterHandler.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterHandler.java index 182bce361..d20da4ccf 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterHandler.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterHandler.java @@ -60,7 +60,7 @@ public final class ClusterHandler { @PostMapping(value = "/create", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity create(@RequestParam String id, @RequestBody ClusterContext clusterContext) { + public static ResponseEntity create(@RequestParam String id, @RequestBody ClusterContext clusterContext) { LoadBalancerContext context = CoreContext.get(id); L4LoadBalancer l4LoadBalancer = context.l4LoadBalancer(); @@ -122,50 +122,50 @@ public ResponseEntity delete(@RequestParam String id, @RequestParam Stri * and {@link SessionPersistence} will be applied. * @param clusterContext {@link ClusterContext} Instance */ - private void determineLoadBalance(L4LoadBalancer l4LoadBalancer, ClusterBuilder clusterBuilder, ClusterContext clusterContext) { + private static void determineLoadBalance(L4LoadBalancer l4LoadBalancer, ClusterBuilder clusterBuilder, ClusterContext clusterContext) { // Determine LoadBalance and SessionPersistence for L4 and L7/HTTP - if (l4LoadBalancer.type().equalsIgnoreCase("L4")) { + if ("L4".equalsIgnoreCase(l4LoadBalancer.type())) { LoadBalance loadBalance; SessionPersistence sessionPersistence; - if (clusterContext.sessionPersistence().equalsIgnoreCase("FiveTupleHash")) { + if ("FiveTupleHash".equalsIgnoreCase(clusterContext.sessionPersistence())) { sessionPersistence = new FourTupleHash(); - } else if (clusterContext.sessionPersistence().equalsIgnoreCase("SourceIPHash")) { + } else if ("SourceIPHash".equalsIgnoreCase(clusterContext.sessionPersistence())) { sessionPersistence = new SourceIPHash(); - } else if (clusterContext.sessionPersistence().equalsIgnoreCase("NOOP")) { + } else if ("NOOP".equalsIgnoreCase(clusterContext.sessionPersistence())) { sessionPersistence = NOOPSessionPersistence.INSTANCE; } else { throw new IllegalArgumentException("Invalid SessionPersistence: " + clusterContext.sessionPersistence()); } - if (clusterContext.loadBalance().equalsIgnoreCase("LeastConnection")) { + if ("LeastConnection".equalsIgnoreCase(clusterContext.loadBalance())) { loadBalance = new LeastConnection(sessionPersistence); - } else if (clusterContext.loadBalance().equalsIgnoreCase("LeastLoad")) { + } else if ("LeastLoad".equalsIgnoreCase(clusterContext.loadBalance())) { loadBalance = new LeastLoad(sessionPersistence); - } else if (clusterContext.loadBalance().equalsIgnoreCase("Random")) { + } else if ("Random".equalsIgnoreCase(clusterContext.loadBalance())) { loadBalance = new Random(sessionPersistence); - } else if (clusterContext.loadBalance().equalsIgnoreCase("RoundRobin")) { + } else if ("RoundRobin".equalsIgnoreCase(clusterContext.loadBalance())) { loadBalance = new RoundRobin(sessionPersistence); } else { throw new IllegalArgumentException("Invalid LoadBalance: " + clusterContext.loadBalance()); } clusterBuilder.withLoadBalance(loadBalance); - } else if (l4LoadBalancer.type().equalsIgnoreCase("L7/HTTP")) { + } else if ("L7/HTTP".equalsIgnoreCase(l4LoadBalancer.type())) { LoadBalance loadBalance; SessionPersistence sessionPersistence; - if (clusterContext.sessionPersistence().equalsIgnoreCase("StickySession")) { + if ("StickySession".equalsIgnoreCase(clusterContext.sessionPersistence())) { sessionPersistence = new StickySession(); - } else if (clusterContext.sessionPersistence().equalsIgnoreCase("NOOP")) { + } else if ("NOOP".equalsIgnoreCase(clusterContext.sessionPersistence())) { sessionPersistence = com.shieldblaze.expressgateway.backend.strategy.l7.http.sessionpersistence.NOOPSessionPersistence.INSTANCE; } else { throw new IllegalArgumentException("Invalid SessionPersistence: " + clusterContext.sessionPersistence()); } - if (clusterContext.loadBalance().equalsIgnoreCase("HTTPRandom")) { + if ("HTTPRandom".equalsIgnoreCase(clusterContext.loadBalance())) { loadBalance = new HTTPRandom(sessionPersistence); - } else if (clusterContext.loadBalance().equalsIgnoreCase("HTTPRoundRobin")) { + } else if ("HTTPRoundRobin".equalsIgnoreCase(clusterContext.loadBalance())) { loadBalance = new HTTPRoundRobin(sessionPersistence); } else { throw new IllegalArgumentException("Invalid LoadBalance: " + clusterContext.loadBalance()); diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/configuration/CertificateKeyPairHolder.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/configuration/CertificateKeyPairHolder.java index 9275f6288..f91780266 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/configuration/CertificateKeyPairHolder.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/configuration/CertificateKeyPairHolder.java @@ -58,7 +58,7 @@ public void setCertificates(List certificates) { } public void setPrivateKeyAsString(String privateKey) { - this.privateKeyAsString = Objects.requireNonNull(privateKey, "PrivateKey"); + privateKeyAsString = Objects.requireNonNull(privateKey, "PrivateKey"); this.privateKey = PrivateKeyUtil.parsePrivateKey(privateKey); } diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/loadbalancer/LoadBalancerHandler.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/loadbalancer/LoadBalancerHandler.java index e0da01534..44981b091 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/loadbalancer/LoadBalancerHandler.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/api/loadbalancer/LoadBalancerHandler.java @@ -65,9 +65,9 @@ public ResponseEntity startL4LoadBalancer(@RequestBody LoadBalancerStart // Determine the L4 Protocol (TCP/UDP) L4FrontListener l4FrontListener; - if (ctx.protocol() != null && ctx.protocol().equalsIgnoreCase("tcp")) { + if (ctx.protocol() != null && "tcp".equalsIgnoreCase(ctx.protocol())) { l4FrontListener = new TCPListener(); - } else if (ctx.protocol() != null && ctx.protocol().equalsIgnoreCase("udp")) { + } else if (ctx.protocol() != null && "udp".equalsIgnoreCase(ctx.protocol())) { l4FrontListener = new UDPListener(); } else { // If Protocol is not 'TCP' or 'UDP' then throw error. diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/exceptions/InvalidLoadBalancerStartRequestException.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/exceptions/InvalidLoadBalancerStartRequestException.java index 33f02a5cf..2dc49176b 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/exceptions/InvalidLoadBalancerStartRequestException.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/exceptions/InvalidLoadBalancerStartRequestException.java @@ -19,12 +19,17 @@ import com.shieldblaze.expressgateway.restapi.api.loadbalancer.LoadBalancerHandler; +import java.io.Serial; + /** * This exception is fired when {@link LoadBalancerHandler} receives * invalid Load Balancer start request. */ public final class InvalidLoadBalancerStartRequestException extends Exception { + @Serial + private static final long serialVersionUID = 3601889734250297574L; + public InvalidLoadBalancerStartRequestException() { } diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/FastBuilder.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/FastBuilder.java index ad500dcbd..b4a03693d 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/FastBuilder.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/FastBuilder.java @@ -23,6 +23,10 @@ public final class FastBuilder { MULTI_VALUE_MAP.set(HttpHeaderNames.CONTENT_TYPE.toString(), HttpHeaderValues.APPLICATION_JSON.toString()); } + private FastBuilder() { + // Prevent outside initialization + } + /** * Build error {@link ResponseEntity} with {@link APIResponse.APIResponseBuilder#isSuccess(boolean)} set to {@code false} * and {@link Error} built using {@link ErrorBase} diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/APIResponse.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/APIResponse.java index 2fecb39b4..48b9e0445 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/APIResponse.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/APIResponse.java @@ -15,7 +15,7 @@ public final class APIResponse { private final JsonObject finalResponse; private APIResponse(APIResponseBuilder APIResponseBuilder) { - this.finalResponse = APIResponseBuilder.finalResponse; + finalResponse = APIResponseBuilder.finalResponse; } /** @@ -49,7 +49,7 @@ public static final class APIResponseBuilder { private boolean Success; public APIResponseBuilder isSuccess(boolean isSuccess) { - this.Success = isSuccess; + Success = isSuccess; return this; } @@ -64,23 +64,23 @@ public APIResponseBuilder withError(ErrorMessage errorMessage) { } public APIResponseBuilder withMessages(List messageList) { - this.MessagesList = messageList; + MessagesList = messageList; return this; } public APIResponseBuilder withMessage(Message message) { - this.Message = message; + Message = message; return this; } public APIResponseBuilder withResult(Result result) { - this.ResultList = Collections.singletonList(result); + ResultList = Collections.singletonList(result); return this; } public APIResponseBuilder withResults(List resultList) { - this.ResultList = resultList; + ResultList = resultList; return this; } @@ -102,7 +102,7 @@ public APIResponse build() { * Build Error response */ { - if (errorList != null && errorList.size() != 0) { + if (errorList != null && !errorList.isEmpty()) { JsonArray jsonArray = new JsonArray(); for (ErrorMessage error : errorList) { JsonObject errorBody = new JsonObject(); @@ -127,7 +127,7 @@ public APIResponse build() { * Build Message response */ { - if (MessagesList != null && MessagesList.size() > 0) { + if (MessagesList != null && !MessagesList.isEmpty()) { JsonArray jsonArray = new JsonArray(); for (Message message : MessagesList) { JsonObject errorBody = new JsonObject(); @@ -150,7 +150,7 @@ public APIResponse build() { * Build Result response */ { - if (ResultList != null && ResultList.size() > 0) { + if (ResultList != null && !ResultList.isEmpty()) { JsonObject resultBody = new JsonObject(); for (Result result : ResultList) { if (result.getMessage() instanceof JsonElement) { diff --git a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/ErrorMessage.java b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/ErrorMessage.java index fcdee6004..0b568e660 100644 --- a/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/ErrorMessage.java +++ b/rest-api/src/main/java/com/shieldblaze/expressgateway/restapi/response/builder/ErrorMessage.java @@ -42,8 +42,8 @@ public ErrorBuilder withErrorBase(ErrorBase errorBase) { public com.shieldblaze.expressgateway.restapi.response.builder.ErrorMessage build() { if (errorBase != null) { - this.ErrorCode = errorBase.code(); - this.ErrorMessage = errorBase.message(); + ErrorCode = errorBase.code(); + ErrorMessage = errorBase.message(); } return new ErrorMessage(this); diff --git a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/CustomOkHttpClient.java b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/CustomOkHttpClient.java index e91f62e3b..320a200b5 100644 --- a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/CustomOkHttpClient.java +++ b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/CustomOkHttpClient.java @@ -58,4 +58,7 @@ public X509Certificate[] getAcceptedIssuers() { } public static final OkHttpClient INSTANCE = builder.hostnameVerifier((hostname, session) -> true).build(); + + private CustomOkHttpClient() { + } } diff --git a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterConfigurationEndpointHandlerTest.java b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterConfigurationEndpointHandlerTest.java index 194b4b23e..b93aeec51 100644 --- a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterConfigurationEndpointHandlerTest.java +++ b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/cluster/ClusterConfigurationEndpointHandlerTest.java @@ -120,7 +120,7 @@ public void deleteL4ClusterTest() throws IOException { @Test @Order(3) - public void addL7ClusterTest() throws IOException, InterruptedException { + public void addL7ClusterTest() throws Exception { l7LoadBalancerTest.startLoadBalancer(); l7LoadBalancerTest.verifyRunning(); diff --git a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/BufferTest.java b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/BufferTest.java index fab4fb409..ce3b3c5b4 100644 --- a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/BufferTest.java +++ b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/BufferTest.java @@ -28,6 +28,7 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; @@ -61,16 +62,7 @@ static void teardown() { @Order(1) @Test void applyConfigurationTest() throws IOException { - JsonObject jsonBody = new JsonObject(); - jsonBody.addProperty("preferDirect", true); - jsonBody.addProperty("heapArena", 12); - jsonBody.addProperty("directArena", 12); - jsonBody.addProperty("pageSize", 16384); - jsonBody.addProperty("maxOrder", 11); - jsonBody.addProperty("smallCacheSize", 256); - jsonBody.addProperty("normalCacheSize", 64); - jsonBody.addProperty("useCacheForAllThreads", true); - jsonBody.addProperty("directMemoryCacheAlignment", 0); + JsonObject jsonBody = jsonObject(); Request request = new Request.Builder() .url("https://127.0.0.1:9110/v1/configuration/buffer") @@ -86,6 +78,21 @@ void applyConfigurationTest() throws IOException { } } + @NotNull + private static JsonObject jsonObject() { + JsonObject jsonBody = new JsonObject(); + jsonBody.addProperty("preferDirect", true); + jsonBody.addProperty("heapArena", 12); + jsonBody.addProperty("directArena", 12); + jsonBody.addProperty("pageSize", 16384); + jsonBody.addProperty("maxOrder", 11); + jsonBody.addProperty("smallCacheSize", 256); + jsonBody.addProperty("normalCacheSize", 64); + jsonBody.addProperty("useCacheForAllThreads", true); + jsonBody.addProperty("directMemoryCacheAlignment", 0); + return jsonBody; + } + @Order(2) @Test void getDefaultConfigurationTest() throws IOException { @@ -117,16 +124,7 @@ void getDefaultConfigurationTest() throws IOException { @Order(3) @Test void getConfigurationTest() throws IOException { - JsonObject jsonBody = new JsonObject(); - jsonBody.addProperty("preferDirect", true); - jsonBody.addProperty("heapArena", 256); - jsonBody.addProperty("directArena", 512); - jsonBody.addProperty("pageSize", 16384); - jsonBody.addProperty("maxOrder", 66); - jsonBody.addProperty("smallCacheSize", 512); - jsonBody.addProperty("normalCacheSize", 128); - jsonBody.addProperty("useCacheForAllThreads", true); - jsonBody.addProperty("directMemoryCacheAlignment", 0); + JsonObject jsonBody = object(); Request request = new Request.Builder() .url("https://127.0.0.1:9110/v1/configuration/buffer") @@ -162,4 +160,19 @@ void getConfigurationTest() throws IOException { assertEquals(jsonBody.get("directMemoryCacheAlignment").getAsInt(), bufferObject.get("directMemoryCacheAlignment").getAsInt()); } } + + @NotNull + private static JsonObject object() { + JsonObject jsonBody = new JsonObject(); + jsonBody.addProperty("preferDirect", true); + jsonBody.addProperty("heapArena", 256); + jsonBody.addProperty("directArena", 512); + jsonBody.addProperty("pageSize", 16384); + jsonBody.addProperty("maxOrder", 66); + jsonBody.addProperty("smallCacheSize", 512); + jsonBody.addProperty("normalCacheSize", 128); + jsonBody.addProperty("useCacheForAllThreads", true); + jsonBody.addProperty("directMemoryCacheAlignment", 0); + return jsonBody; + } } diff --git a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/TransportTest.java b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/TransportTest.java index 468a9341d..27437be5e 100644 --- a/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/TransportTest.java +++ b/rest-api/src/test/java/com/shieldblaze/expressgateway/restapi/api/configuration/TransportTest.java @@ -141,7 +141,7 @@ void getDefaultConfiguration() throws IOException { JsonObject bufferObject = responseJson.get("Result").getAsJsonObject().get("TransportConfiguration").getAsJsonObject(); JsonArray sizes = bufferObject.get("receiveBufferSizes").getAsJsonArray(); - int[] receiveSizes = new int[]{sizes.get(0).getAsInt(), sizes.get(1).getAsInt(), sizes.get(2).getAsInt()}; + int[] receiveSizes = {sizes.get(0).getAsInt(), sizes.get(1).getAsInt(), sizes.get(2).getAsInt()}; assertEquals(transportDefault.transportType().toString(), bufferObject.get("transportType").getAsString()); assertEquals(transportDefault.receiveBufferAllocationType().toString(), bufferObject.get("receiveBufferAllocationType").getAsString()); @@ -198,10 +198,10 @@ void getConfiguration() throws IOException { JsonObject bufferObject = responseJson.get("Result").getAsJsonObject().get("TransportConfiguration").getAsJsonObject(); JsonArray sizesA = jsonBody.get("receiveBufferSizes").getAsJsonArray(); - int[] receiveSizesIntA = new int[]{sizesA.get(0).getAsInt(), sizesA.get(1).getAsInt(), sizesA.get(2).getAsInt()}; + int[] receiveSizesIntA = {sizesA.get(0).getAsInt(), sizesA.get(1).getAsInt(), sizesA.get(2).getAsInt()}; JsonArray sizesB = bufferObject.get("receiveBufferSizes").getAsJsonArray(); - int[] receiveSizesIntB = new int[]{sizesB.get(0).getAsInt(), sizesB.get(1).getAsInt(), sizesB.get(2).getAsInt()}; + int[] receiveSizesIntB = {sizesB.get(0).getAsInt(), sizesB.get(1).getAsInt(), sizesB.get(2).getAsInt()}; assertEquals(jsonBody.get("transportType").getAsString(), bufferObject.get("transportType").getAsString()); assertEquals(jsonBody.get("receiveBufferAllocationType").getAsString(), bufferObject.get("receiveBufferAllocationType").getAsString()); diff --git a/service-discovery-client/src/test/java/com/shieldblaze/expressgateway/servicediscovery/client/ServiceDiscoveryClientTest.java b/service-discovery-client/src/test/java/com/shieldblaze/expressgateway/servicediscovery/client/ServiceDiscoveryClientTest.java index 33acf3a78..a604fea20 100644 --- a/service-discovery-client/src/test/java/com/shieldblaze/expressgateway/servicediscovery/client/ServiceDiscoveryClientTest.java +++ b/service-discovery-client/src/test/java/com/shieldblaze/expressgateway/servicediscovery/client/ServiceDiscoveryClientTest.java @@ -74,13 +74,13 @@ static void shutdown() throws IOException { @Order(1) @Test - void register() throws IOException, InterruptedException { + void register() throws Exception { ServiceDiscoveryClient.register(); } @Order(2) @Test - void deregister() throws IOException, InterruptedException { + void deregister() throws Exception { ServiceDiscoveryClient.deregister(); } } diff --git a/shaded-dependencies/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java b/shaded-dependencies/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java index 5720779ac..9d709eb8a 100644 --- a/shaded-dependencies/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java +++ b/shaded-dependencies/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java @@ -54,7 +54,7 @@ * {@link Http2FrameCodecBuilder}. It's recommended for channel handlers to inherit from the * {@link Http2ChannelDuplexHandler}, as it provides additional functionality like iterating over all active streams or * creating outbound streams. - * + *

*

Stream Lifecycle

*

* The frame codec delivers and writes frames for active streams. An active stream is closed when either side sends a @@ -64,7 +64,7 @@ *

{@link Http2StreamFrame}s read from the channel always a {@link Http2FrameStream} object set, while when writing a * {@link Http2StreamFrame} the application code needs to set a {@link Http2FrameStream} object using * {@link Http2StreamFrame#stream(Http2FrameStream)}. - * + *

*

Flow control

*

* The frame codec automatically increments stream and connection flow control windows. @@ -78,12 +78,12 @@ *

The connection-level flow control window can be changed by writing a {@link Http2WindowUpdateFrame} with the * desired window size increment in bytes and the stream identifier set to {@code 0}. By default the initial * connection-level flow control window is the same as initial stream-level flow control window. - * + *

*

New inbound Streams

*

* The first frame of an HTTP/2 stream must be an {@link Http2HeadersFrame}, which will have an {@link Http2FrameStream} * object attached. - * + *

*

New outbound Streams

*

* A outbound HTTP/2 stream can be created by first instantiating a new {@link Http2FrameStream} object via @@ -102,11 +102,11 @@ * } else { * // Stream failed to become active. Handle error. * if (f.cause() instanceof Http2NoMoreStreamIdsException) { - * + *

* } else if (f.cause() instanceof Http2GoAwayException) { - * + *

* } else { - * + *

* } * } * } @@ -125,21 +125,21 @@ * get closed or a GO_AWAY frame might be received. In the first case, all writes of buffered streams will fail with a * {@link Http2ChannelClosedException}. In the second case, all writes of buffered streams with an identifier less than * the last stream identifier of the GO_AWAY frame will fail with a {@link Http2GoAwayException}. - * + *

*

Error Handling

*

* Exceptions and errors are propagated via {@link ChannelInboundHandler#exceptionCaught}. Exceptions that apply to * a specific HTTP/2 stream are wrapped in a {@link Http2FrameStreamException} and have the corresponding * {@link Http2FrameStream} object attached. - * + *

*

Reference Counting

*

* Some {@link Http2StreamFrame}s implement the {@link ReferenceCounted} interface, as they carry * reference counted objects (e.g. {@link ByteBuf}s). The frame codec will call {@link ReferenceCounted#retain()} before * propagating a reference counted object through the pipeline, and thus an application handler needs to release such - * an object after having consumed it. For more information on reference counting take a look at - * https://netty.io/wiki/reference-counted-objects.html - * + * an object after having consumed it. For more information on rcounting take a look at + * https://netty.io/wiki/reference-counted-objects.html + *

*

HTTP Upgrade

*

* Server-side HTTP to HTTP/2 upgrade is supported in conjunction with {@link Http2ServerUpgradeCodec}; the necessary @@ -720,12 +720,12 @@ private Http2FrameStream requireStream(int streamId) { } } - private void onUpgradeEvent(ChannelHandlerContext ctx, UpgradeEvent evt) { + private static void onUpgradeEvent(ChannelHandlerContext ctx, UpgradeEvent evt) { ctx.fireUserEventTriggered(evt); } - private void onHttp2StreamWritabilityChanged(ChannelHandlerContext ctx, DefaultHttp2FrameStream stream, - @SuppressWarnings("unused") boolean writable) { + private static void onHttp2StreamWritabilityChanged(ChannelHandlerContext ctx, DefaultHttp2FrameStream stream, + @SuppressWarnings("unused") boolean writable) { ctx.fireUserEventTriggered(stream.writabilityChanged); } diff --git a/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicHttpServerTest.java b/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicHttpServerTest.java index 0e547aed7..228c7366f 100644 --- a/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicHttpServerTest.java +++ b/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicHttpServerTest.java @@ -198,7 +198,7 @@ public void sendHttp11AndWebSocketsMultiplexingTraffic() throws Exception { OK_HTTP_CLIENT.newWebSocket(request, new WebSocketListener() { - private int framesSent = 0; + private int framesSent; private final byte[] randomData = new byte[dataSize]; @Override diff --git a/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicTcpUdpServerTest.java b/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicTcpUdpServerTest.java index 2c179bda3..a30ab816b 100644 --- a/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicTcpUdpServerTest.java +++ b/testsuite/src/test/java/com/shieldblaze/expressgateway/testsuite/standalone/BasicTcpUdpServerTest.java @@ -433,6 +433,6 @@ void sendTcpTrafficInMultiplexingWayAndMarkBackendOfflineWithDrainingConnection( node.drainConnections(); assertThat(latch.await(1, TimeUnit.MINUTES)).isTrue(); - assertThat(TCP_FRAMES.getAndSet(0)).isBetween(1, (frames * threads)); + assertThat(TCP_FRAMES.getAndSet(0)).isBetween(1, frames * threads); } }