diff --git a/.github/skills/generate-javadoc.md b/.github/skills/generate-javadoc.md new file mode 100644 index 00000000..31d8dd93 --- /dev/null +++ b/.github/skills/generate-javadoc.md @@ -0,0 +1,122 @@ +# Skill: Generate Javadoc + +## Purpose +Generate comprehensive Javadocs for public API interfaces and classes in a specified module, following consistent documentation standards. + +## Trigger +When the user asks to: +- Generate javadocs for a module +- Add documentation to public APIs +- Document interfaces/classes with `@since` tags + +## Requirements + +### What to Document +1. **Public API interfaces and classes only** - files in main source packages +2. **Skip implementation classes** - files in `impl/` packages are NOT documented +3. **Skip test classes** - files in `src/test/` are NOT documented + +### Javadoc Standards +Each documented element must include: + +1. **Class/Interface level:** + - Short description of purpose + - `@param` for type parameters (if generic) + - `@author JavaSaBr` + - `@since 10.0.0` + +2. **Method level:** + - Short description for ALL methods + - `@param` and `@return` only for **non-trivial** methods + - `@since 10.0.0` + - `@throws` only when explicitly thrown + +3. **Constants/Fields:** + - Short description + - `@since 10.0.0` + +### Example Format + +```java +/** + * An immutable array interface that provides type-safe, indexed access to elements. + * + * @param the type of elements in this array + * @author JavaSaBr + * @since 10.0.0 + */ +public interface Array extends Iterable { + + /** + * Creates an empty immutable array of the specified type. + * + * @param the type of elements + * @param type the component type of the array + * @return an empty immutable array + * @since 10.0.0 + */ + static Array empty(Class type) { + // ... + } + + /** + * Returns the number of elements in this array. + * + * @return the number of elements + * @since 10.0.0 + */ + int size(); + + /** + * Returns the element at the specified index. + * + * @param index the index of the element to return + * @return the element at the specified index + * @throws IndexOutOfBoundsException if the index is out of range + * @since 10.0.0 + */ + E get(int index); +} +``` + +## Execution Steps + +1. **Analyze module structure:** + ```bash + ls -la /src/main/java// + ``` + +2. **Identify public API files:** + - List all `.java` files in main packages + - Exclude `impl/` subdirectories + - Exclude `package-info.java` (optional to document) + +3. **Read each file** to understand existing documentation state + +4. **Add Javadocs** using `replace_string_in_file` tool: + - Add class-level Javadoc with description, `@author`, `@since` + - Add method-level Javadocs with description and `@since` + - Add `@param`/`@return` only for non-trivial methods + +5. **Validate changes:** + ```bash + ./gradlew ::compileJava + ``` + +6. **Run full build:** + ```bash + ./gradlew ::build + ``` + +7. **Update summary file** at `./summary.md` with documented files + +## Output +- All public API files documented with proper Javadocs +- Build passes successfully +- Summary file updated with documentation status + +## Notes +- Use existing code style from the project +- Preserve existing Javadocs that are already complete (just add `@since` if missing) +- Group related edits to minimize tool calls +- Check for errors after editing each file diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java index f7aa7467..6757451d 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java @@ -1,4 +1,3 @@ - package javasabr.rlib.collections.array; import java.io.Serializable; @@ -91,12 +90,12 @@ static LongArray of(long... elements) { /** * Creates an immutable copy of the specified long array. * - * @param intArray the array to copy + * @param array the array to copy * @return an immutable copy * @since 10.0.0 */ - static LongArray copyOf(LongArray intArray) { - return new ImmutableLongArray(intArray.toArray()); + static LongArray copyOf(LongArray array) { + return new ImmutableLongArray(array.toArray()); } /** diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableIntArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableIntArray.java index 4a74dd1c..5e6b750f 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableIntArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableIntArray.java @@ -33,7 +33,7 @@ public interface UnsafeMutableIntArray extends UnsafeIntArray, MutableIntArray { * @return the removed value * @since 10.0.0 */ - int unsafeRemoveByInex(int index); + int unsafeRemoveByIndex(int index); /** * Sets the value at the specified index without bounds checking. diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableLongArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableLongArray.java index 9f26bd1c..e4a68aac 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableLongArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/UnsafeMutableLongArray.java @@ -33,7 +33,7 @@ public interface UnsafeMutableLongArray extends UnsafeLongArray, MutableLongArra * @return the removed value * @since 10.0.0 */ - long unsafeRemoveByInex(int index); + long unsafeRemoveByIndex(int index); /** * Sets the value at the specified index without bounds checking. diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractIntArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractIntArray.java index e493b9d9..9b69d3de 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractIntArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractIntArray.java @@ -61,7 +61,7 @@ public boolean contains(int value) { @Override public boolean containsAll(IntArray array) { if (array.isEmpty()) { - return false; + return true; } int[] wrapped = array.asUnsafe().wrapped(); @@ -77,7 +77,7 @@ public boolean containsAll(IntArray array) { @Override public boolean containsAll(int[] array) { if (array.length < 1) { - return false; + return true; } for (int value : array) { if (!contains(value)) { diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractLongArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractLongArray.java index 5b340d94..9005e9ae 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractLongArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractLongArray.java @@ -61,7 +61,7 @@ public boolean contains(long value) { @Override public boolean containsAll(LongArray array) { if (array.isEmpty()) { - return false; + return true; } long[] wrapped = array.asUnsafe().wrapped(); for (int i = 0, length = array.size(); i < length; i++) { @@ -75,7 +75,7 @@ public boolean containsAll(LongArray array) { @Override public boolean containsAll(long[] array) { if (array.length < 1) { - return false; + return true; } for (long value : array) { if (!contains(value)) { diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableIntArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableIntArray.java index 05b76381..62a69aca 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableIntArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableIntArray.java @@ -66,7 +66,7 @@ public UnsafeMutableIntArray unsafeSet(int index, int value) { @Override public int removeByIndex(int index) { checkIndex(index); - return unsafeRemoveByInex(index); + return unsafeRemoveByIndex(index); } @Override @@ -75,7 +75,7 @@ public boolean remove(int value) { if (index < 0) { return false; } - unsafeRemoveByInex(index); + unsafeRemoveByIndex(index); return true; } @@ -108,7 +108,7 @@ public boolean removeAll(int[] array) { } @Override - public int unsafeRemoveByInex(int index) { + public int unsafeRemoveByIndex(int index) { int numMoved = size() - index - 1; int[] wrapped = wrapped(); int value = wrapped[index]; diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableLongArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableLongArray.java index 30b53043..960018cf 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableLongArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractMutableLongArray.java @@ -66,7 +66,7 @@ public UnsafeMutableLongArray unsafeSet(int index, long value) { @Override public long removeByIndex(int index) { checkIndex(index); - return unsafeRemoveByInex(index); + return unsafeRemoveByIndex(index); } @Override @@ -75,7 +75,7 @@ public boolean remove(long value) { if (index < 0) { return false; } - unsafeRemoveByInex(index); + unsafeRemoveByIndex(index); return true; } @@ -108,7 +108,7 @@ public boolean removeAll(long[] array) { } @Override - public long unsafeRemoveByInex(int index) { + public long unsafeRemoveByIndex(int index) { int numMoved = size() - index - 1; long[] wrapped = wrapped(); long value = wrapped[index]; diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/deque/DequeFactory.java b/rlib-collections/src/main/java/javasabr/rlib/collections/deque/DequeFactory.java index c713797f..114347db 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/deque/DequeFactory.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/deque/DequeFactory.java @@ -33,7 +33,7 @@ public static Deque linkedListBased() { * @return a new array based deque * @since 10.0.0 */ - public static Deque arrayBasedBased(Class type) { + public static Deque arrayBased(Class type) { return new DefaultArrayBasedDeque<>(type); } @@ -46,7 +46,7 @@ public static Deque arrayBasedBased(Class type) { * @return a new array based deque * @since 10.0.0 */ - public static Deque arrayBasedBased(Class type, int capacity) { + public static Deque arrayBased(Class type, int capacity) { return new DefaultArrayBasedDeque<>(type, capacity); } } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/gc/optimized/GcOptimizedMutableHashBasedIntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/gc/optimized/GcOptimizedMutableHashBasedIntToRefDictionary.java index 945f4efd..950e1c74 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/gc/optimized/GcOptimizedMutableHashBasedIntToRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/gc/optimized/GcOptimizedMutableHashBasedIntToRefDictionary.java @@ -34,7 +34,7 @@ public GcOptimizedMutableHashBasedIntToRefDictionary(int initCapacity, float loa //noinspection unchecked this.entries = new ReusableLinkedHashIntToRefEntry[initCapacity]; this.threshold = (int) (initCapacity * loadFactor); - this.entryPool = DequeFactory.arrayBasedBased(ReusableLinkedHashIntToRefEntry.class); + this.entryPool = DequeFactory.arrayBased(ReusableLinkedHashIntToRefEntry.class); } @Override diff --git a/rlib-collections/src/test/java/javasabr/rlib/collections/deque/DequeTest.java b/rlib-collections/src/test/java/javasabr/rlib/collections/deque/DequeTest.java index 40310619..01a2c533 100644 --- a/rlib-collections/src/test/java/javasabr/rlib/collections/deque/DequeTest.java +++ b/rlib-collections/src/test/java/javasabr/rlib/collections/deque/DequeTest.java @@ -420,7 +420,7 @@ void shouldCheckContains(Deque deque) { @Test void shouldRebalanceIndexesAddLastRemoveFirst() { // given: - Deque deque = DequeFactory.arrayBasedBased(String.class, 15); + Deque deque = DequeFactory.arrayBased(String.class, 15); Field head = ReflectionUtils.getUnsafeField(deque, "head"); Field tail = ReflectionUtils.getUnsafeField(deque, "tail"); var generator = new AtomicInteger(); @@ -541,7 +541,7 @@ void shouldRebalanceIndexesAddLastRemoveFirst() { @Test void shouldRebalanceIndexesAddFirstRemoveLast() { // given: - Deque deque = DequeFactory.arrayBasedBased(String.class, 15); + Deque deque = DequeFactory.arrayBased(String.class, 15); Field head = ReflectionUtils.getUnsafeField(deque, "head"); Field tail = ReflectionUtils.getUnsafeField(deque, "tail"); var generator = new AtomicInteger(); @@ -707,6 +707,6 @@ void shouldCorrectlyIterate2Deque(Deque deque) { private static Stream generateDeque() { return Stream.of( Arguments.of(DequeFactory.linkedListBased()), - Arguments.of(DequeFactory.arrayBasedBased(String.class, 15))); + Arguments.of(DequeFactory.arrayBased(String.class, 15))); } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java b/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java index d713c3f1..3d094221 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java @@ -3,49 +3,79 @@ import java.nio.ByteBuffer; /** - * The interface to implement a buffer allocator for network things. + * The interface to implement a buffer allocator for network operations. * * @author JavaSaBr + * @since 10.0.0 */ public interface BufferAllocator { /** - * Get a new read buffer to use. + * Gets a new read buffer to use for receiving data. + * + * @return a read buffer + * @since 10.0.0 */ ByteBuffer takeReadBuffer(); /** - * Get a new pending buffer to use. + * Gets a new pending buffer to use for storing partial packet data. + * + * @return a pending buffer + * @since 10.0.0 */ ByteBuffer takePendingBuffer(); /** - * Get a new write buffer to use. + * Gets a new write buffer to use for sending data. + * + * @return a write buffer + * @since 10.0.0 */ ByteBuffer takeWriteBuffer(); /** - * Get a new buffer with requested capacity. + * Gets a new buffer with the requested capacity. + * + * @param bufferSize the requested buffer size + * @return a buffer with the specified capacity + * @since 10.0.0 */ ByteBuffer takeBuffer(int bufferSize); /** - * Store an already used read buffer. + * Stores an already used read buffer for reuse. + * + * @param buffer the read buffer to store + * @return this allocator for method chaining + * @since 10.0.0 */ BufferAllocator putReadBuffer(ByteBuffer buffer); /** - * Store an already used pending buffer. + * Stores an already used pending buffer for reuse. + * + * @param buffer the pending buffer to store + * @return this allocator for method chaining + * @since 10.0.0 */ BufferAllocator putPendingBuffer(ByteBuffer buffer); /** - * Store an already used write buffer. + * Stores an already used write buffer for reuse. + * + * @param buffer the write buffer to store + * @return this allocator for method chaining + * @since 10.0.0 */ BufferAllocator putWriteBuffer(ByteBuffer buffer); /** - * Store an already used byte buffer. + * Stores an already used byte buffer for reuse. + * + * @param buffer the buffer to store + * @return this allocator for method chaining + * @since 10.0.0 */ BufferAllocator putBuffer(ByteBuffer buffer); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/Connection.java b/rlib-network/src/main/java/javasabr/rlib/network/Connection.java index 6426ddae..40662e0c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/Connection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/Connection.java @@ -7,12 +7,24 @@ import reactor.core.publisher.Flux; /** - * The interface to implement an async connection. + * The interface to implement an asynchronous network connection. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface Connection> { + /** + * Represents a received packet event containing the connection, packet, and validity status. + * + * @param the connection type + * @param the packet type + * @param connection the connection that received the packet + * @param packet the received packet + * @param valid whether the packet is valid + * @since 10.0.0 + */ record ReceivedPacketEvent(C connection, R packet, boolean valid) { @Override public String toString() { @@ -21,54 +33,84 @@ public String toString() { } /** - * Get a remote address of this connection. + * Gets the remote address of this connection. + * + * @return the remote address as a string + * @since 10.0.0 */ String remoteAddress(); /** - * Get a timestamp of last write/read activity. + * Gets the timestamp of last write/read activity. + * + * @return the last activity timestamp in milliseconds + * @since 10.0.0 */ long lastActivity(); /** - * Close this connection if this connection is still opened. + * Closes this connection if it is still open. + * + * @since 10.0.0 */ void close(); /** - * @return true if this connection is already closed. + * Checks if this connection is already closed. + * + * @return true if this connection is closed + * @since 10.0.0 */ boolean closed(); /** - * Send a packet to connection's owner in background. + * Sends a packet to the connection's owner in the background. + * + * @param packet the packet to send + * @since 10.0.0 */ void sendInBackground(WritableNetworkPacket packet); /** - * Send a packet to connection's owner with async feedback of this action. + * Sends a packet to the connection's owner with async feedback. * - * @return the async result with true if the packet was sent or false if sending was failed. + * @param packet the packet to send + * @return a future with true if sent successfully, false otherwise + * @since 10.0.0 */ CompletableFuture sendAsync(WritableNetworkPacket packet); /** - * Register a consumer to handle received valid packets. + * Registers a consumer to handle received valid packets. + * + * @param consumer the consumer to handle valid packets + * @since 10.0.0 */ void onReceiveValidPacket(BiConsumer> consumer); /** - * Register a consumer to handle received invalid packets. + * Registers a consumer to handle received invalid packets. + * + * @param consumer the consumer to handle invalid packets + * @since 10.0.0 */ void onReceiveInvalidPacket(BiConsumer> consumer); /** - * Get a stream of received packet events. + * Gets a stream of received packet events. + * + * @return a reactive stream of packet events + * @since 10.0.0 */ Flux>> receivedEvents(); /** - * Get a stream of received packet events with expected packet type. + * Gets a stream of received packet events filtered by expected packet type. + * + * @param the expected packet type + * @param packetType the packet type class + * @return a reactive stream of packet events + * @since 10.0.0 */ default > Flux> receivedEvents(Class packetType) { return receivedEvents() @@ -77,17 +119,28 @@ default > Flux> rec } /** - * Get a stream of received valid packets. + * Gets a stream of received valid packets. + * + * @return a reactive stream of valid packets + * @since 10.0.0 */ Flux> receivedValidPackets(); /** - * Get a stream of received invalid packets. + * Gets a stream of received invalid packets. + * + * @return a reactive stream of invalid packets + * @since 10.0.0 */ Flux> receivedInvalidPackets(); /** - * Get a stream of received valid packets with expected type. + * Gets a stream of received valid packets filtered by expected type. + * + * @param the expected packet type + * @param packetType the packet type class + * @return a reactive stream of valid packets + * @since 10.0.0 */ default > Flux receivedValidPackets(Class packetType) { return receivedValidPackets() @@ -96,7 +149,12 @@ default > Flux receivedValidPackets(Class< } /** - * Get a stream of received invalid packets with expected type. + * Gets a stream of received invalid packets filtered by expected type. + * + * @param the expected packet type + * @param packetType the packet type class + * @return a reactive stream of invalid packets + * @since 10.0.0 */ default > Flux receivedInvalidPackets(Class packetType) { return receivedInvalidPackets() diff --git a/rlib-network/src/main/java/javasabr/rlib/network/Network.java b/rlib-network/src/main/java/javasabr/rlib/network/Network.java index 3c8b8443..ec91b9e1 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/Network.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/Network.java @@ -5,18 +5,40 @@ /** * The interface to implement an asynchronous network. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface Network> { + /** + * Gets the scheduled executor service for this network. + * + * @return the scheduled executor service + * @since 10.0.0 + */ ScheduledExecutorService scheduledExecutor(); + /** + * Gets the network configuration. + * + * @return the network config + * @since 10.0.0 + */ NetworkConfig config(); + /** + * Executes a task in the network thread. + * + * @param task the task to execute + * @since 10.0.0 + */ void inNetworkThread(Runnable task); /** - * Shutdown this network. + * Shuts down this network and releases all resources. + * + * @since 10.0.0 */ void shutdown(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java b/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java index 9b45cc62..79d94a8c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java @@ -7,12 +7,18 @@ import lombok.experimental.Accessors; /** - * The interface to implement a network config. + * The interface to implement a network configuration. * * @author JavaSaBr + * @since 10.0.0 */ public interface NetworkConfig { + /** + * Simple implementation of network configuration using Lombok builder. + * + * @since 10.0.0 + */ @Builder @Getter @Accessors(fluent = true, chain = false) @@ -52,82 +58,123 @@ public String threadGroupName() { }; /** - * Get a thread constructor which should be used to create network threads. + * Gets the thread constructor for creating network threads. + * + * @return the thread constructor + * @since 10.0.0 */ default ThreadConstructor threadConstructor() { return Thread::new; } /** - * Get a priority of network threads. + * Gets the priority of network threads. * - * @return the priority of network threads. + * @return the thread priority + * @since 10.0.0 */ default int threadPriority() { return Thread.NORM_PRIORITY; } /** - * Get a group name of network threads. + * Gets the group name of network threads. + * + * @return the thread group name + * @since 10.0.0 */ default String threadGroupName() { return "NetworkThread"; } /** - * Get a group name of scheduling network threads. + * Gets the group name of scheduled network threads. + * + * @return the scheduled thread group name + * @since 10.0.0 */ default String scheduledThreadGroupName() { return "ScheduledNetworkThread"; } /** - * Get size of buffer with will be used to collect received data from network. + * Gets the size of buffer used to collect received data from network. + * + * @return the read buffer size in bytes + * @since 10.0.0 */ default int readBufferSize() { return 2048; } /** - * Gets size of buffer with pending reading data. Pending buffer allows to construct a packet with bigger data part than - * {@link #readBufferSize()}. It should be at least 2x of {@link #readBufferSize()} + * Gets the size of buffer for pending reading data. The pending buffer allows constructing + * a packet with bigger data part than {@link #readBufferSize()}. + * It should be at least 2x of {@link #readBufferSize()}. + * + * @return the pending buffer size in bytes + * @since 10.0.0 */ default int pendingBufferSize() { return readBufferSize() * 2; } /** - * Gets a size of buffer which will be used for packet serialization. + * Gets the size of buffer used for packet serialization. + * + * @return the write buffer size in bytes + * @since 10.0.0 */ default int writeBufferSize() { return 2048; } /** - * Gets the max size of one single network packet. + * Gets the maximum size of a single network packet. + * + * @return the max packet size in bytes + * @since 10.0.0 */ default int maxPacketSize() { return 5 * 1024 * 1024; } /** - * Gets a timeout for retry read/write operation. + * Gets the timeout for retry read/write operations. + * + * @return the retry delay in milliseconds + * @since 10.0.0 */ default int retryDelayInMs() { return 1000; } /** - * Gets a max allowed empty reads from socket channel before closing a connection. + * Gets the maximum allowed empty reads from socket channel before closing a connection. + * + * @return the max empty reads count + * @since 10.0.0 */ default int maxEmptyReadsBeforeClose() { return 3; } + /** + * Gets the byte order for network data. + * + * @return the byte order + * @since 10.0.0 + */ default ByteOrder byteOrder() { return ByteOrder.BIG_ENDIAN; } + /** + * Checks if direct byte buffers should be used. + * + * @return true if direct buffers should be used + * @since 10.0.0 + */ default boolean useDirectByteBuffer() { return false; } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java b/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java index bbd5c2c9..7c68be7f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java @@ -4,14 +4,17 @@ import org.jspecify.annotations.Nullable; /** - * The interface to implement a network cryptor. + * The interface to implement network data encryption and decryption. * * @author JavaSaBr + * @since 10.0.0 */ public interface NetworkCryptor { /** - * Default NULL implementation of the network crypt. + * Default NULL implementation that performs no encryption or decryption. + * + * @since 10.0.0 */ NetworkCryptor NULL = new NetworkCryptor() { @@ -29,23 +32,25 @@ public ByteBuffer encrypt(ByteBuffer data, int length, ByteBuffer toStore) { }; /** - * Decrypt data. + * Decrypts data from the source buffer. * - * @param data the buffer with data to decrypt. - * @param length the data length. - * @param toStore the buffer to store decrypted data. - * @return the buffer with decrypted data or null if don't need to decrypt anything. + * @param data the buffer with data to decrypt + * @param length the data length + * @param toStore the buffer to store decrypted data + * @return the buffer with decrypted data or null if decryption is not needed + * @since 10.0.0 */ @Nullable ByteBuffer decrypt(ByteBuffer data, int length, ByteBuffer toStore); /** - * Encrypt data. + * Encrypts data from the source buffer. * - * @param data the buffer with data to encrypt. - * @param length the data length. - * @param toStore the buffer to store encrypted data. - * @return the buffer with encrypted data or null if don't need to decrypt encrypt. + * @param data the buffer with data to encrypt + * @param length the data length + * @param toStore the buffer to store encrypted data + * @return the buffer with encrypted data or null if encryption is not needed + * @since 10.0.0 */ @Nullable ByteBuffer encrypt(ByteBuffer data, int length, ByteBuffer toStore); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java b/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java index 187ec72b..0c09b9a5 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java @@ -16,19 +16,38 @@ import lombok.experimental.UtilityClass; /** - * Class with factory methods to build client/server networks. + * Factory class with methods to build client and server networks. * * @author JavaSaBr + * @since 10.0.0 */ @UtilityClass public final class NetworkFactory { + /** + * Creates a new client network with custom connection factory. + * + * @param the connection type + * @param networkConfig the network configuration + * @param channelToConnection the function to create connections from channels + * @return a new client network + * @since 10.0.0 + */ public static > ClientNetwork clientNetwork( NetworkConfig networkConfig, BiFunction, AsynchronousSocketChannel, C> channelToConnection) { return new DefaultClientNetwork<>(networkConfig, channelToConnection); } + /** + * Creates a new server network with custom connection factory. + * + * @param the connection type + * @param networkConfig the server network configuration + * @param channelToConnection the function to create connections from channels + * @return a new server network + * @since 10.0.0 + */ public static > ServerNetwork serverNetwork( ServerNetworkConfig networkConfig, BiFunction, AsynchronousSocketChannel, C> channelToConnection) { @@ -36,14 +55,21 @@ public static > ServerNetwork serverNetwork( } /** - * Create a string packet based asynchronous client network. + * Creates a string packet based asynchronous client network with default configuration. + * + * @return a new string data client network + * @since 10.0.0 */ public static ClientNetwork stringDataClientNetwork() { return stringDataClientNetwork(NetworkConfig.DEFAULT_CLIENT); } /** - * Create a string packet based asynchronous client network. + * Creates a string packet based asynchronous client network with custom configuration. + * + * @param networkConfig the network configuration + * @return a new string data client network + * @since 10.0.0 */ public static ClientNetwork stringDataClientNetwork( NetworkConfig networkConfig) { @@ -51,7 +77,12 @@ public static ClientNetwork stringDataClientNetwork( } /** - * Create a string packet based asynchronous client network. + * Creates a string packet based asynchronous client network with custom configuration and allocator. + * + * @param networkConfig the network configuration + * @param bufferAllocator the buffer allocator + * @return a new string data client network + * @since 10.0.0 */ public static ClientNetwork stringDataClientNetwork( NetworkConfig networkConfig, @@ -62,7 +93,11 @@ public static ClientNetwork stringDataClientNetwork( } /** - * Create id based packet default asynchronous client network. + * Creates an ID-based packet default asynchronous client network. + * + * @param packetRegistry the packet registry + * @return a new default client network + * @since 10.0.0 */ public static ClientNetwork defaultClientNetwork( ReadableNetworkPacketRegistry, DefaultConnection> packetRegistry) { @@ -73,7 +108,13 @@ public static ClientNetwork defaultClientNetwork( } /** - * Create id based packet default asynchronous client network. + * Creates an ID-based packet default asynchronous client network with custom configuration. + * + * @param networkConfig the network configuration + * @param bufferAllocator the buffer allocator + * @param packetRegistry the packet registry + * @return a new default client network + * @since 10.0.0 */ public static ClientNetwork defaultClientNetwork( NetworkConfig networkConfig, @@ -85,8 +126,13 @@ public static ClientNetwork defaultClientNetwork( } /** - * Create string packet based asynchronous secure client network. + * Creates a string packet based asynchronous secure client network. * + * @param networkConfig the network configuration + * @param bufferAllocator the buffer allocator + * @param sslContext the SSL context + * @return a new SSL string data client network + * @since 10.0.0 */ public static ClientNetwork stringDataSslClientNetwork( NetworkConfig networkConfig, @@ -98,14 +144,21 @@ public static ClientNetwork stringDataSslClientNetwork( } /** - * Create string packet based asynchronous server network. + * Creates a string packet based asynchronous server network with default configuration. + * + * @return a new string data server network + * @since 10.0.0 */ public static ServerNetwork stringDataServerNetwork() { return stringDataServerNetwork(ServerNetworkConfig.DEFAULT_SERVER); } /** - * Create string packet based asynchronous server network. + * Creates a string packet based asynchronous server network with custom configuration. + * + * @param networkConfig the server network configuration + * @return a new string data server network + * @since 10.0.0 */ public static ServerNetwork stringDataServerNetwork( ServerNetworkConfig networkConfig) { @@ -113,7 +166,12 @@ public static ServerNetwork stringDataServerNetwork( } /** - * Create string packet based asynchronous server network. + * Creates a string packet based asynchronous server network with custom configuration and allocator. + * + * @param networkConfig the server network configuration + * @param bufferAllocator the buffer allocator + * @return a new string data server network + * @since 10.0.0 */ public static ServerNetwork stringDataServerNetwork( ServerNetworkConfig networkConfig, @@ -124,7 +182,13 @@ public static ServerNetwork stringDataServerNetwork( } /** - * Create string packet based asynchronous secure server network. + * Creates a string packet based asynchronous secure server network. + * + * @param networkConfig the server network configuration + * @param bufferAllocator the buffer allocator + * @param sslContext the SSL context + * @return a new SSL string data server network + * @since 10.0.0 */ public static ServerNetwork stringDataSslServerNetwork( ServerNetworkConfig networkConfig, @@ -136,7 +200,11 @@ public static ServerNetwork stringDataSslServerNetwork( } /** - * Create id based packet default asynchronous server network. + * Creates an ID-based packet default asynchronous server network. + * + * @param packetRegistry the packet registry + * @return a new default server network + * @since 10.0.0 */ public static ServerNetwork defaultServerNetwork( ReadableNetworkPacketRegistry, DefaultConnection> packetRegistry) { @@ -147,7 +215,13 @@ public static ServerNetwork defaultServerNetwork( } /** - * Create id based packet default asynchronous server network. + * Creates an ID-based packet default asynchronous server network with custom configuration. + * + * @param networkConfig the server network configuration + * @param bufferAllocator the buffer allocator + * @param packetRegistry the packet registry + * @return a new default server network + * @since 10.0.0 */ public static ServerNetwork defaultServerNetwork( ServerNetworkConfig networkConfig, diff --git a/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java b/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java index ab090343..dc21a9cb 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java @@ -7,12 +7,18 @@ import lombok.experimental.Accessors; /** - * The interface to implement a server network config. + * The interface to implement a server network configuration. * * @author JavaSaBr + * @since 10.0.0 */ public interface ServerNetworkConfig extends NetworkConfig { + /** + * Simple implementation of server network configuration using Lombok builder. + * + * @since 10.0.0 + */ @Builder @Getter @Accessors(fluent = true, chain = false) @@ -63,21 +69,30 @@ public String scheduledThreadGroupName() { }; /** - * Get a minimal size of network thread executor. + * Gets the minimal size of network thread executor. + * + * @return the minimum thread pool size + * @since 10.0.0 */ default int threadGroupMinSize() { return 1; } /** - * Get a maximum size of network thread executor. + * Gets the maximum size of network thread executor. + * + * @return the maximum thread pool size + * @since 10.0.0 */ default int threadGroupMaxSize() { return threadGroupMinSize(); } /** - * Get a size of network scheduled thread executor. + * Gets the size of network scheduled thread executor. + * + * @return the scheduled thread pool size + * @since 10.0.0 */ default int scheduledThreadGroupSize() { return 1; diff --git a/rlib-network/src/main/java/javasabr/rlib/network/UnsafeConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/UnsafeConnection.java index 46f37847..b72051cf 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/UnsafeConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/UnsafeConnection.java @@ -2,13 +2,43 @@ import java.nio.channels.AsynchronousSocketChannel; +/** + * An unsafe connection interface providing direct access to internal network components. + * Use with caution as modifications may affect connection stability. + * + * @param the connection type + * @since 10.0.0 + */ public interface UnsafeConnection> extends Connection { + /** + * Gets the network this connection belongs to. + * + * @return the network + * @since 10.0.0 + */ Network network(); + /** + * Gets the buffer allocator used by this connection. + * + * @return the buffer allocator + * @since 10.0.0 + */ BufferAllocator bufferAllocator(); + /** + * Gets the underlying asynchronous socket channel. + * + * @return the socket channel + * @since 10.0.0 + */ AsynchronousSocketChannel channel(); + /** + * Called when the connection is established. + * + * @since 10.0.0 + */ void onConnected(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/annotation/NetworkPacketDescription.java b/rlib-network/src/main/java/javasabr/rlib/network/annotation/NetworkPacketDescription.java index 7c75856e..c2627d54 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/annotation/NetworkPacketDescription.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/annotation/NetworkPacketDescription.java @@ -7,13 +7,21 @@ import java.lang.annotation.Target; /** - * The annotation to describe a network packet. + * Annotation to describe a network packet with its unique identifier. * * @author JavaSaBr + * @since 10.0.0 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface NetworkPacketDescription { + + /** + * The unique identifier for this packet type. + * + * @return the packet ID + * @since 10.0.0 + */ int id(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/client/ClientNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/client/ClientNetwork.java index 586c43ef..f04c52ce 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/client/ClientNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/client/ClientNetwork.java @@ -9,35 +9,55 @@ import reactor.core.publisher.Mono; /** - * Interface to implement a client network. + * Interface to implement a client network for connecting to servers. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface ClientNetwork> extends Network { /** - * Connect to a server by the address. + * Connects to a server synchronously by the address. + * + * @param serverAddress the server address + * @return the established connection + * @since 10.0.0 */ C connect(InetSocketAddress serverAddress); /** - * Connect to a server by the address. + * Connects to a server asynchronously by the address. + * + * @param serverAddress the server address + * @return a future containing the established connection + * @since 10.0.0 */ CompletableFuture connectAsync(InetSocketAddress serverAddress); /** - * Connect to a server by the address. + * Connects to a server reactively by the address. + * + * @param serverAddress the server address + * @return a mono containing the established connection + * @since 10.0.0 */ Mono connectReactive(InetSocketAddress serverAddress); /** - * Get a current connection to a server or null. + * Gets the current connection to a server. + * + * @return the current connection or null if not connected + * @since 10.0.0 */ @Nullable C currentConnection(); /** - * Get a current connection to a server or empty. + * Gets the current connection to a server as an optional. + * + * @return an optional containing the current connection + * @since 10.0.0 */ Optional currentConnectionOptional(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/exception/MalformedProtocolException.java b/rlib-network/src/main/java/javasabr/rlib/network/exception/MalformedProtocolException.java index 4441f294..1269f438 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/exception/MalformedProtocolException.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/exception/MalformedProtocolException.java @@ -1,6 +1,18 @@ package javasabr.rlib.network.exception; +/** + * Exception thrown when a network protocol is malformed or invalid. + * + * @since 10.0.0 + */ public class MalformedProtocolException extends NetworkException { + + /** + * Constructs a new malformed protocol exception with the specified message. + * + * @param message the error message + * @since 10.0.0 + */ public MalformedProtocolException(String message) { super(message); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/exception/NetworkException.java b/rlib-network/src/main/java/javasabr/rlib/network/exception/NetworkException.java index 0fe81c62..41edbd14 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/exception/NetworkException.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/exception/NetworkException.java @@ -1,15 +1,39 @@ package javasabr.rlib.network.exception; +/** + * Base exception class for network-related errors. + * + * @since 10.0.0 + */ public class NetworkException extends RuntimeException { + /** + * Constructs a new network exception with the specified message. + * + * @param message the error message + * @since 10.0.0 + */ protected NetworkException(String message) { super(message); } + /** + * Constructs a new network exception with the specified message and cause. + * + * @param message the error message + * @param cause the cause of the exception + * @since 10.0.0 + */ protected NetworkException(String message, Throwable cause) { super(message, cause); } + /** + * Constructs a new network exception with the specified cause. + * + * @param cause the cause of the exception + * @since 10.0.0 + */ protected NetworkException(Throwable cause) { super(cause); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/exception/UserDefinedNetworkException.java b/rlib-network/src/main/java/javasabr/rlib/network/exception/UserDefinedNetworkException.java index 47932ef1..c19014cd 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/exception/UserDefinedNetworkException.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/exception/UserDefinedNetworkException.java @@ -1,14 +1,39 @@ package javasabr.rlib.network.exception; +/** + * Base exception class for user-defined network errors. + * + * @since 10.0.0 + */ public class UserDefinedNetworkException extends NetworkException { + + /** + * Constructs a new user-defined network exception with the specified message. + * + * @param message the error message + * @since 10.0.0 + */ protected UserDefinedNetworkException(String message) { super(message); } + /** + * Constructs a new user-defined network exception with the specified message and cause. + * + * @param message the error message + * @param cause the cause of the exception + * @since 10.0.0 + */ protected UserDefinedNetworkException(String message, Throwable cause) { super(message, cause); } + /** + * Constructs a new user-defined network exception with the specified cause. + * + * @param cause the cause of the exception + * @since 10.0.0 + */ protected UserDefinedNetworkException(Throwable cause) { super(cause); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractConnection.java index 520e4f14..7e8e04c6 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractConnection.java @@ -79,7 +79,7 @@ public AbstractConnection( this.maxPacketsByRead = maxPacketsByRead; this.lock = new StampedLock(); this.channel = channel; - this.pendingPackets = DequeFactory.arrayBasedBased(WritableNetworkPacket.class); + this.pendingPackets = DequeFactory.arrayBased(WritableNetworkPacket.class); this.network = network; this.closed = new AtomicBoolean(false); this.validPacketSubscribers = ArrayFactory.copyOnModifyArray(BiConsumer.class); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedNetworkPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedNetworkPacket.java index 9f75c928..4af676ba 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedNetworkPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedNetworkPacket.java @@ -4,14 +4,19 @@ import javasabr.rlib.network.annotation.NetworkPacketDescription; /** + * Interface for network packets that have a unique identifier. + * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface IdBasedNetworkPacket> extends NetworkPacket { /** - * Get id of this packet. + * Gets the ID of this packet from its {@link NetworkPacketDescription} annotation. * - * @return the packet type's id. + * @return the packet type's ID + * @since 10.0.0 */ default int packetId() { return getClass() diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadableNetworkPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadableNetworkPacket.java index 9664624d..00eba30b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadableNetworkPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadableNetworkPacket.java @@ -4,13 +4,20 @@ import javasabr.rlib.network.Connection; /** + * Interface for ID-based readable network packets that can create new instances. + * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface IdBasedReadableNetworkPacket> extends ReadableNetworkPacket, IdBasedNetworkPacket { /** - * Create a new instance of this type. + * Creates a new instance of this packet type. + * + * @return a new instance + * @since 10.0.0 */ default IdBasedReadableNetworkPacket newInstance() { return ClassUtils.newInstance(getClass()); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedWritableNetworkPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedWritableNetworkPacket.java index d06c6bee..7c1b87db 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedWritableNetworkPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedWritableNetworkPacket.java @@ -3,7 +3,11 @@ import javasabr.rlib.network.Connection; /** + * Interface for ID-based writable network packets. + * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface IdBasedWritableNetworkPacket> extends WritableNetworkPacket, IdBasedNetworkPacket { diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/MarkerNetworkPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/MarkerNetworkPacket.java index fe98047c..bbfe0b81 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/MarkerNetworkPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/MarkerNetworkPacket.java @@ -1,6 +1,8 @@ package javasabr.rlib.network.packet; /** - * Interface to mark that some specific packet doesn't have any data. + * Marker interface indicating that a packet has no data payload. + * + * @since 10.0.0 */ public interface MarkerNetworkPacket {} diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacket.java index 037500e7..2bf5fdcf 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacket.java @@ -3,14 +3,19 @@ import javasabr.rlib.network.Connection; /** - * The interface to implement a network packet. + * Base interface for all network packets. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface NetworkPacket> { /** - * @return the packet's name. + * Gets the name of this packet. + * + * @return the packet name + * @since 10.0.0 */ String name(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketReader.java index 6111320f..1284fffa 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketReader.java @@ -1,17 +1,24 @@ package javasabr.rlib.network.packet; /** + * Interface for reading network packets from a connection. + * * @author JavaSaBr + * @since 10.0.0 */ public interface NetworkPacketReader { /** - * Activate a process of receiving packets. + * Activates the process of receiving packets. + * + * @since 10.0.0 */ void startRead(); /** - * Close all used resources. + * Closes all used resources. + * + * @since 10.0.0 */ void close(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketWriter.java index a2c1d985..3c05224b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/NetworkPacketWriter.java @@ -1,17 +1,25 @@ package javasabr.rlib.network.packet; /** + * Interface for writing network packets to a connection. + * * @author JavaSaBr + * @since 10.0.0 */ public interface NetworkPacketWriter { /** - * @return true if the writer starting writing new data to channel. + * Tries to send the next packet in the queue. + * + * @return true if the writer started writing new data to the channel + * @since 10.0.0 */ boolean tryToSendNextPacket(); /** - * Close all used resources. + * Closes all used resources. + * + * @since 10.0.0 */ void close(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadableNetworkPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadableNetworkPacket.java index 72407a02..8aeaa4eb 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadableNetworkPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadableNetworkPacket.java @@ -4,18 +4,22 @@ import javasabr.rlib.network.Connection; /** - * The interface to implement a readable network packet. + * Interface for network packets that can be read from a byte buffer. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface ReadableNetworkPacket> extends NetworkPacket { /** - * Read packet's data from byte buffer. + * Reads packet data from the byte buffer. * - * @param buffer the buffer with received data. - * @param remainingDataLength the expected remaining data length. - * @return true if reading was success. + * @param connection the connection this packet was received from + * @param buffer the buffer with received data + * @param remainingDataLength the expected remaining data length + * @return true if reading was successful + * @since 10.0.0 */ boolean read(C connection, ByteBuffer buffer, int remainingDataLength); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReusableWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReusableWritablePacket.java index ccbd5262..708d5e0a 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReusableWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReusableWritablePacket.java @@ -5,53 +5,71 @@ import javasabr.rlib.reusable.pool.Pool; /** - * The interface to implement a reusable writable packet. + * Interface for reusable writable packets that can be pooled. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface ReusableWritablePacket> extends WritableNetworkPacket, Reusable { /** - * Handle completion of packet sending. + * Handles completion of packet sending. + * + * @since 10.0.0 */ void complete(); /** - * Force complete this packet. + * Forces completion of this packet. + * + * @since 10.0.0 */ void forceComplete(); /** - * Decrease sending count. + * Decreases the sending count by one. + * + * @since 10.0.0 */ void decreaseSends(); /** - * Decrease sending count. + * Decreases the sending count by the specified amount. * - * @param count the count. + * @param count the count to decrease by + * @since 10.0.0 */ void decreaseSends(int count); /** - * Increase sending count. + * Increases the sending count by one. + * + * @since 10.0.0 */ void increaseSends(); /** - * Increase sending count. + * Increases the sending count by the specified amount. * - * @param count the count. + * @param count the count to increase by + * @since 10.0.0 */ void increaseSends(int count); /** - * Set the pool. + * Sets the pool to store this packet when done. * - * @param pool the pool to store used packet. + * @param pool the pool to store used packets + * @since 10.0.0 */ void setPool(Pool> pool); + /** + * Called when this packet is added to the send queue. + * + * @since 10.0.0 + */ default void notifyAddedToSend() { increaseSends(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/WritableNetworkPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/WritableNetworkPacket.java index 1a9d149e..05201689 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/WritableNetworkPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/WritableNetworkPacket.java @@ -4,23 +4,37 @@ import javasabr.rlib.network.Connection; /** - * Interface to implement a writable packet. + * Interface for network packets that can be written to a byte buffer. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface WritableNetworkPacket> extends NetworkPacket { + /** + * Constant indicating unknown expected packet length. + * + * @since 10.0.0 + */ int UNKNOWN_EXPECTED_BYTES = -1; /** - * Write this packet to the buffer. + * Writes this packet to the buffer. * - * @return true if writing was successful. + * @param connection the connection to write to + * @param buffer the buffer to write to + * @return true if writing was successful + * @since 10.0.0 */ boolean write(C connection, ByteBuffer buffer); /** - * @return expected data length of this packet or {@code UNKNOWN_EXPECTED_BYTES}. + * Gets the expected data length of this packet. + * + * @param connection the connection + * @return the expected length or {@link #UNKNOWN_EXPECTED_BYTES} + * @since 10.0.0 */ default int expectedLength(C connection) { return UNKNOWN_EXPECTED_BYTES; diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadableNetworkPacketRegistry.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadableNetworkPacketRegistry.java index ddffaf70..9f7ed998 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadableNetworkPacketRegistry.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadableNetworkPacketRegistry.java @@ -11,21 +11,33 @@ import javasabr.rlib.network.packet.registry.impl.IdBasedReadableNetworkPacketRegistry; /** - * The interface to implement a registry of readable packets. + * Interface to implement a registry of readable network packets. * + * @param the readable packet type + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface ReadableNetworkPacketRegistry, C extends Connection> { /** * Creates a new empty readable packet registry. + * + * @return an empty registry + * @since 10.0.0 */ static ReadableNetworkPacketRegistry empty() { return new IdBasedReadableNetworkPacketRegistry<>(IdBasedReadableNetworkPacket.class); } /** - * Create a new empty readable packet registry. + * Creates a new empty readable packet registry with the specified type. + * + * @param the readable packet type + * @param the connection type + * @param type the packet type class + * @return an empty registry + * @since 10.0.0 */ static < R extends IdBasedReadableNetworkPacket, @@ -34,7 +46,13 @@ C extends Connection> ReadableNetworkPacketRegistry empty(Class type } /** - * Creates a new class path scanning based readable packet registry. + * Creates a new classpath scanning based readable packet registry. + * + * @param the readable packet type + * @param the connection type + * @param baseType the base packet type class + * @return a registry populated with discovered packets + * @since 10.0.0 */ static < R extends IdBasedReadableNetworkPacket, @@ -46,7 +64,14 @@ C extends Connection> ReadableNetworkPacketRegistry classPathBased(Clas } /** - * Creates a new class path scanning based readable packet registry by scanning the main class. + * Creates a new classpath scanning based readable packet registry by scanning the main class. + * + * @param the readable packet type + * @param the connection type + * @param baseType the base packet type class + * @param mainClass the main class to scan from + * @return a registry populated with discovered packets + * @since 10.0.0 */ static < R extends IdBasedReadableNetworkPacket, @@ -60,7 +85,14 @@ C extends Connection> ReadableNetworkPacketRegistry classPathBased( } /** - * Creates a new class path scanning based readable packet registry. + * Creates a new readable packet registry from a classpath scanner. + * + * @param the readable packet type + * @param the connection type + * @param baseType the base packet type class + * @param scanner the classpath scanner + * @return a registry populated with discovered packets + * @since 10.0.0 */ static < R extends IdBasedReadableNetworkPacket, @@ -78,7 +110,14 @@ C extends Connection> ReadableNetworkPacketRegistry scannerBased( } /** - * Creates a new readable packet registry. + * Creates a new readable packet registry from varargs classes. + * + * @param the readable packet type + * @param the connection type + * @param type the packet type class + * @param classes the packet classes to register + * @return a registry with registered packets + * @since 10.0.0 */ @SafeVarargs static < @@ -90,6 +129,17 @@ C extends Connection> ReadableNetworkPacketRegistry of( .register(classes, classes.length); } + /** + * Creates a new readable packet registry from varargs classes with explicit connection type. + * + * @param the readable packet type + * @param the connection type + * @param type the packet type class + * @param connectionType the connection type class + * @param classes the packet classes to register + * @return a registry with registered packets + * @since 10.0.0 + */ @SafeVarargs static < R extends IdBasedReadableNetworkPacket, @@ -102,7 +152,14 @@ C extends Connection> ReadableNetworkPacketRegistry of( } /** - * Creates a new readable packet registry. + * Creates a new readable packet registry from an array of classes. + * + * @param the readable packet type + * @param the connection type + * @param type the packet type class + * @param classes the array of packet classes to register + * @return a registry with registered packets + * @since 10.0.0 */ static < R extends IdBasedReadableNetworkPacket, @@ -114,11 +171,12 @@ C extends Connection> ReadableNetworkPacketRegistry of( } /** - * Resolve a network packet prototype based on packet id. + * Resolves a network packet prototype based on packet ID. * - * @param id the network packet id. - * @return the resolve prototype. - * @throws IllegalArgumentException if can't resolve a prototype by the id. + * @param id the network packet ID + * @return the resolved prototype + * @throws IllegalArgumentException if no prototype found for the ID + * @since 10.0.0 */ R resolvePrototypeById(int id); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/server/ServerNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/server/ServerNetwork.java index 158e672e..f3404e3b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/server/ServerNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/server/ServerNetwork.java @@ -7,29 +7,45 @@ import reactor.core.publisher.Flux; /** - * The interface to implement a server network. + * The interface to implement a server network for accepting client connections. * + * @param the connection type * @author JavaSaBr + * @since 10.0.0 */ public interface ServerNetwork> extends Network { /** - * Start a server using any available address. + * Starts the server using any available address. + * + * @return the bound server address + * @since 10.0.0 */ InetSocketAddress start(); /** - * Start a server by the address. + * Starts the server on the specified address. + * + * @param the server network type + * @param serverAddress the address to bind to + * @return this server network + * @since 10.0.0 */ > S start(InetSocketAddress serverAddress); /** - * Register a consumer of new connections. + * Registers a consumer to handle new connections. + * + * @param consumer the consumer to handle accepted connections + * @since 10.0.0 */ void onAccept(Consumer consumer); /** - * Get a stream of new accepted connections. + * Gets a reactive stream of new accepted connections. + * + * @return a flux of accepted connections + * @since 10.0.0 */ Flux accepted(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java b/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java index 71e21c6c..b980883f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java @@ -22,12 +22,27 @@ import org.jspecify.annotations.Nullable; /** + * Utility class for network operations including SSL context creation, + * hex dump generation, and buffer manipulation. + * * @author JavaSaBr + * @since 10.0.0 */ public class NetworkUtils { + /** + * An empty byte buffer constant. + * + * @since 10.0.0 + */ public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); + /** + * A trust manager that accepts all certificates without validation. + * Use with caution in production environments. + * + * @since 10.0.0 + */ public static class AllTrustManager implements X509TrustManager { public static final X509Certificate[] EMPTY_CERTS = new X509Certificate[0]; @@ -41,16 +56,43 @@ public void checkClientTrusted(X509Certificate[] certificates, String arg1) {} public void checkServerTrusted(X509Certificate[] certificates, String arg1) {} } + /** + * Gets the remote address from an asynchronous socket channel. + * + * @param socketChannel the socket channel + * @return the remote socket address + * @since 10.0.0 + */ public static SocketAddress getRemoteAddress(AsynchronousSocketChannel socketChannel) { return Utils.uncheckedGet(socketChannel, AsynchronousSocketChannel::getRemoteAddress); } + /** + * Creates an SSL context from a PKCS12 key store. + * + * @param keyStoreData the key store input stream + * @param keyStorePassword the key store password + * @return the configured SSL context + * @since 10.0.0 + */ public static SSLContext createSslContext( InputStream keyStoreData, String keyStorePassword) { return createSslContext("PKCS12", keyStoreData, keyStorePassword, null, null, null); } + /** + * Creates an SSL context with custom key store and optional trust store. + * + * @param keyStoreType the key store type (e.g., "PKCS12", "JKS") + * @param keyStoreData the key store input stream + * @param keyStorePassword the key store password + * @param trustStoreType the trust store type or null + * @param trustStoreData the trust store input stream or null + * @param trustStorePassword the trust store password or null + * @return the configured SSL context + * @since 10.0.0 + */ public static SSLContext createSslContext( String keyStoreType, InputStream keyStoreData, @@ -92,6 +134,13 @@ public static SSLContext createSslContext( } } + /** + * Creates an SSL context that trusts all certificates. + * WARNING: Use only for testing or development, not in production. + * + * @return an SSL context that trusts all certificates + * @since 10.0.0 + */ public static SSLContext createAllTrustedClientSslContext() { try { var sslContext = SSLContext.getInstance("TLSv1.2"); @@ -103,11 +152,11 @@ public static SSLContext createAllTrustedClientSslContext() { } /** - * Prepare a string like 'HEX DUMP' by passed byte buffer. + * Prepares a hex dump string from a byte buffer. * - * @param buffer the byte buffer. - * @return the hex dump string. - * @since 9.9.0 + * @param buffer the byte buffer + * @return the hex dump string + * @since 10.0.0 */ public static String hexDump(ByteBuffer buffer) { if (!buffer.hasRemaining()) { @@ -118,12 +167,12 @@ public static String hexDump(ByteBuffer buffer) { } /** - * Prepare a string like 'HEX DUMP' by passed buffer and ssl engine result. + * Prepares a hex dump string from a buffer and SSL engine result. * - * @param buffer the byte buffer. - * @param result the ssl engine result. - * @return the hex dump string. - * @since 9.9.0 + * @param buffer the byte buffer + * @param result the SSL engine result + * @return the hex dump string + * @since 10.0.0 */ public static String hexDump(ByteBuffer buffer, SSLEngineResult result) { if (result.bytesProduced() < 1) { @@ -134,23 +183,25 @@ public static String hexDump(ByteBuffer buffer, SSLEngineResult result) { } /** - * Prepare a string like 'HEX DUMP' by passed array. + * Prepares a hex dump string from a byte array. * - * @param array the bytes array. - * @param length the length. - * @return the hex dump string. + * @param array the byte array + * @param length the length + * @return the hex dump string + * @since 10.0.0 */ public static String hexDump(byte[] array, int length) { return hexDump(array, 0, length); } /** - * Prepare a string like 'HEX DUMP' by passed array. + * Prepares a hex dump string from a byte array with offset. * - * @param array the byte array. - * @param offset the offset. - * @param length the length. - * @return the hex dump string. + * @param array the byte array + * @param offset the offset + * @param length the length + * @return the hex dump string + * @since 10.0.0 */ public static String hexDump(byte[] array, int offset, int length) { @@ -238,21 +289,23 @@ private static StringBuilder hexDigit(StringBuilder builder, byte value) { } /** - * Check a network port to know is available it or not to open a new socket. + * Checks if a network port is available to open a new socket. * - * @param port the port. - * @return true if the port is available. + * @param port the port + * @return true if the port is available + * @since 10.0.0 */ public static boolean isPortAvailable(int port) { return isPortAvailable("*", port); } /** - * Check a network port to know is available it or not to open a new socket. + * Checks if a network port is available on the specified host. * - * @param host the host. - * @param port the port. - * @return true if the port is available. + * @param host the host ("*" for all interfaces) + * @param port the port + * @return true if the port is available + * @since 10.0.0 */ public static boolean isPortAvailable(String host, int port) { try (var ignored = "*".equals(host) @@ -265,10 +318,11 @@ public static boolean isPortAvailable(String host, int port) { } /** - * Get a nearest available network port from a start port. + * Gets the nearest available network port starting from the specified port. * - * @param port the start port. - * @return the nearest available network port or -1. + * @param port the start port + * @return the nearest available network port or -1 if none found + * @since 10.0.0 */ public static int getAvailablePort(int port) { return IntStream @@ -278,7 +332,15 @@ public static int getAvailablePort(int port) { .orElse(-1); } - + /** + * Increases the buffer size and copies existing data to the new buffer. + * + * @param current the current buffer + * @param allocator the buffer allocator + * @param newSize the new buffer size + * @return the new larger buffer with copied data + * @since 10.0.0 + */ public static ByteBuffer increaseBuffer(ByteBuffer current, BufferAllocator allocator, int newSize) { var newBuffer = allocator.takeBuffer(newSize); @@ -291,10 +353,22 @@ public static ByteBuffer increaseBuffer(ByteBuffer current, BufferAllocator allo return newBuffer; } + /** + * Clears a network buffer and sets its limit to 0. + * + * @param networkBuffer the buffer to clean + * @since 10.0.0 + */ public static void cleanNetworkBuffer(ByteBuffer networkBuffer) { networkBuffer.clear().limit(0); } + /** + * Compacts a network buffer if there is data at position > 0. + * + * @param networkBuffer the buffer to compact + * @since 10.0.0 + */ public static void compactNetworkBufferIfNeed(ByteBuffer networkBuffer) { if (networkBuffer.position() > 0) { networkBuffer.compact().limit(networkBuffer.position()); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/util/SslUtils.java b/rlib-network/src/main/java/javasabr/rlib/network/util/SslUtils.java index 45917c19..5574353e 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/util/SslUtils.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/util/SslUtils.java @@ -4,17 +4,43 @@ import javax.net.ssl.SSLEngineResult.HandshakeStatus; import lombok.experimental.UtilityClass; +/** + * Utility class for SSL/TLS operations. + * + * @since 10.0.0 + */ @UtilityClass public class SslUtils { + /** + * Checks if the SSL handshake is complete and ready for encryption. + * + * @param status the handshake status + * @return true if ready to encrypt/decrypt + * @since 10.0.0 + */ public static boolean isReadyToCrypt(HandshakeStatus status) { return status == HandshakeStatus.FINISHED || status == HandshakeStatus.NOT_HANDSHAKING; } + /** + * Checks if the SSL handshake needs further processing. + * + * @param status the handshake status + * @return true if processing is needed + * @since 10.0.0 + */ public static boolean needToProcess(HandshakeStatus status) { return status != HandshakeStatus.FINISHED && status != HandshakeStatus.NOT_HANDSHAKING; } + /** + * Executes all delegated SSL tasks and returns the new handshake status. + * + * @param engine the SSL engine + * @return the handshake status after executing tasks + * @since 10.0.0 + */ public static HandshakeStatus executeSslTasks(SSLEngine engine) { for (Runnable task = engine.getDelegatedTask(); task != null; task = engine.getDelegatedTask()) { task.run();