From 4951646fbd137a979d34632f798bfba2257b2d67 Mon Sep 17 00:00:00 2001 From: javasabr Date: Thu, 7 Aug 2025 20:28:37 +0200 Subject: [PATCH 1/8] start global refactoring --- README.md | 332 +- gradle/libs.versions.toml | 12 +- .../common/classpath/ClassPathScanner.java | 350 +- .../classpath/ClassPathScannerFactory.java | 106 +- .../classpath/impl/ClassPathScannerImpl.java | 682 ++- .../impl/ManifestClassPathScannerImpl.java | 142 +- .../rlib/common/compiler/ByteCode.java | 15 +- .../rlib/common/compiler/Compiler.java | 88 +- .../rlib/common/compiler/CompilerFactory.java | 40 +- .../common/compiler/impl/CompileByteCode.java | 34 +- .../compiler/impl/CompileClassLoader.java | 58 +- .../compiler/impl/CompileJavaFileManager.java | 80 +- .../common/compiler/impl/CompileListener.java | 62 +- .../common/compiler/impl/CompilerImpl.java | 434 +- .../common/compiler/impl/JavaFileSource.java | 80 +- .../common/concurrent/GroupThreadFactory.java | 96 +- .../concurrent/atomic/AtomicInteger.java | 48 - .../concurrent/atomic/AtomicReference.java | 29 - .../atomic/ReusableAtomicInteger.java | 41 + .../atomic/ReusableAtomicReference.java | 26 + .../concurrent/deadlock/DeadLockDetector.java | 152 +- .../concurrent/deadlock/DeadLockListener.java | 15 +- .../executor/PeriodicTaskExecutor.java | 27 +- .../concurrent/executor/TaskExecutor.java | 31 +- .../SingleThreadPeriodicTaskExecutor.java | 454 +- .../impl/SingleThreadTaskExecutor.java | 363 +- .../executor/impl/ThreadPoolTaskExecutor.java | 344 +- .../lock/AsyncReadSyncWriteLock.java | 32 +- .../common/concurrent/lock/LockFactory.java | 120 +- .../common/concurrent/lock/LockUtils.java | 403 +- .../rlib/common/concurrent/lock/Lockable.java | 16 +- .../concurrent/lock/impl/AtomicLock.java | 162 +- .../lock/impl/AtomicReadWriteLock.java | 303 +- .../concurrent/lock/impl/FinalAtomicLock.java | 16 - .../lock/impl/FinalAtomicReadWriteLock.java | 16 - .../lock/impl/FinalReentrantAtomicLock.java | 16 - .../lock/impl/FinalReentrantLock.java | 13 - .../impl/FinalReentrantReadWriteLock.java | 13 - .../lock/impl/FinalStampedLock.java | 11 - .../lock/impl/ReentrantARSWLock.java | 83 +- .../lock/impl/ReentrantAtomicLock.java | 186 +- .../common/concurrent/task/CallableTask.java | 22 +- .../common/concurrent/task/PeriodicTask.java | 40 +- .../common/concurrent/task/SimpleTask.java | 24 +- .../concurrent/util/ConcurrentUtils.java | 273 +- .../common/concurrent/util/ThreadUtils.java | 24 +- .../common/data/AbstractFileDocument.java | 58 +- .../common/data/AbstractStreamDocument.java | 195 +- .../rlib/common/data/DocumentXML.java | 15 +- .../rlib/common/function/BiIntPredicate.java | 2 +- .../common/function/BiObjectIntConsumer.java | 16 +- .../common/function/BooleanFloatConsumer.java | 14 +- .../rlib/common/function/ByteFunction.java | 2 +- .../rlib/common/function/CharSupplier.java | 18 +- .../common/function/DoubleObjectConsumer.java | 14 +- .../common/function/FiveObjectConsumer.java | 26 +- .../function/FloatBiObjectConsumer.java | 2 +- .../rlib/common/function/FloatConsumer.java | 12 +- .../common/function/FloatFloatConsumer.java | 14 +- .../common/function/FloatObjectConsumer.java | 14 +- .../common/function/FourObjectConsumer.java | 24 +- .../rlib/common/function/FunctionInt.java | 14 +- .../rlib/common/function/Functions.java | 72 +- .../common/function/IntBiObjectConsumer.java | 16 +- .../common/function/IntObjectConsumer.java | 14 +- .../common/function/IntObjectPredicate.java | 16 +- .../common/function/LongBiObjectConsumer.java | 16 +- .../common/function/LongObjectConsumer.java | 14 +- .../common/function/LongObjectPredicate.java | 16 +- .../common/function/NotNullBiConsumer.java | 4 +- .../common/function/NotNullBiFunction.java | 4 +- .../common/function/NotNullBiPredicate.java | 4 +- .../rlib/common/function/NotNullConsumer.java | 4 +- .../NotNullFloatBiObjectConsumer.java | 4 +- .../rlib/common/function/NotNullFunction.java | 4 +- .../common/function/NotNullFunctionInt.java | 2 +- .../function/NotNullIntBiObjectConsumer.java | 4 +- .../function/NotNullIntObjectPredicate.java | 2 +- .../function/NotNullLongBiObjectConsumer.java | 4 +- .../function/NotNullLongObjectPredicate.java | 2 +- .../function/NotNullNullableBiFunction.java | 4 +- .../function/NotNullNullableFunction.java | 4 +- .../NotNullNullableTripleFunction.java | 4 +- .../function/NotNullObjectIntPredicate.java | 4 +- .../function/NotNullObjectLongPredicate.java | 4 +- .../common/function/NotNullPredicate.java | 4 +- .../function/NotNullSafeBiConsumer.java | 4 +- .../function/NotNullSafeBiFunction.java | 4 +- .../common/function/NotNullSafeConsumer.java | 4 +- .../common/function/NotNullSafeFactory.java | 4 +- .../common/function/NotNullSafeFunction.java | 4 +- .../common/function/NotNullSafeSupplier.java | 4 +- .../function/NotNullSafeTriFunction.java | 4 +- .../rlib/common/function/NotNullSupplier.java | 4 +- .../function/NotNullTripleConsumer.java | 4 +- .../function/NotNullTriplePredicate.java | 2 +- .../common/function/NullableSupplier.java | 4 +- .../common/function/ObjectFloatConsumer.java | 14 +- .../common/function/ObjectFloatFunction.java | 17 +- .../function/ObjectFloatObjectConsumer.java | 16 +- .../common/function/ObjectIntConsumer.java | 14 +- .../common/function/ObjectIntFunction.java | 17 +- .../function/ObjectIntObjectConsumer.java | 16 +- .../function/ObjectIntObjectFunction.java | 19 +- .../common/function/ObjectIntPredicate.java | 2 +- .../common/function/ObjectLongConsumer.java | 14 +- .../common/function/ObjectLongFunction.java | 16 +- .../function/ObjectLongObjectConsumer.java | 16 +- .../common/function/ObjectLongPredicate.java | 16 +- .../rlib/common/function/SafeBiConsumer.java | 2 +- .../rlib/common/function/SafeBiFunction.java | 2 +- .../rlib/common/function/SafeConsumer.java | 2 +- .../rlib/common/function/SafeFactory.java | 2 +- .../rlib/common/function/SafeFunction.java | 2 +- .../rlib/common/function/SafeRunnable.java | 12 +- .../rlib/common/function/SafeSupplier.java | 2 +- .../rlib/common/function/SafeTriFunction.java | 2 +- .../common/function/SafeTripleConsumer.java | 18 +- .../common/function/SafeTripleFunction.java | 21 +- .../common/function/SixObjectConsumer.java | 35 +- .../rlib/common/function/TripleConsumer.java | 16 +- .../rlib/common/function/TripleFunction.java | 19 +- .../rlib/common/function/TriplePredicate.java | 18 +- .../rlib/common/geom/DirectionType.java | 48 +- .../javasabr/rlib/common/geom/Matrix3f.java | 265 +- .../java/javasabr/rlib/common/geom/Plane.java | 997 +++-- .../javasabr/rlib/common/geom/Polygon.java | 715 ++-- .../rlib/common/geom/Quaternion4f.java | 1723 ++++---- .../java/javasabr/rlib/common/geom/Ray3f.java | 129 +- .../javasabr/rlib/common/geom/Vector2f.java | 920 +++-- .../javasabr/rlib/common/geom/Vector3f.java | 1264 +++--- .../rlib/common/geom/Vector3fBuffer.java | 89 +- .../rlib/common/geom/bounding/Bounding.java | 240 +- .../common/geom/bounding/BoundingFactory.java | 88 +- .../common/geom/bounding/BoundingType.java | 24 +- .../geom/bounding/impl/AbstractBounding.java | 182 +- .../bounding/impl/AxisAlignedBoundingBox.java | 469 ++- .../geom/bounding/impl/BoundingSphere.java | 212 +- .../rlib/common/geom/util/AngleUtils.java | 291 +- .../rlib/common/geom/util/CoordsUtils.java | 452 +- .../rlib/common/geom/util/GeometryUtils.java | 436 +- .../rlib/common/graphics/color/ColorRGBA.java | 475 ++- .../rlib/common/io/ReusableStream.java | 31 +- .../io/impl/RedirectImageOutputStream.java | 89 +- .../common/io/impl/ReuseBytesInputStream.java | 143 +- .../io/impl/ReuseBytesOutputStream.java | 229 +- .../common/manager/InitializeManager.java | 101 +- .../common/monitoring/MemoryMonitoring.java | 401 +- .../common/monitoring/MonitoringManager.java | 145 +- .../common/monitoring/RuntimeMonitoring.java | 131 +- .../plugin/ConfigurablePluginSystem.java | 121 +- .../javasabr/rlib/common/plugin/Plugin.java | 119 +- .../rlib/common/plugin/PluginContainer.java | 284 +- .../rlib/common/plugin/PluginSystem.java | 94 +- .../javasabr/rlib/common/plugin/Version.java | 74 +- .../plugin/annotation/PluginDescription.java | 84 +- .../exception/InitializePluginException.java | 42 +- .../plugin/exception/PluginException.java | 14 +- .../exception/PreloadPluginException.java | 29 +- .../plugin/extension/ExtensionPoint.java | 625 ++- .../extension/ExtensionPointManager.java | 223 +- .../rlib/common/plugin/impl/BasePlugin.java | 88 +- .../common/plugin/impl/BasePluginSystem.java | 913 ++-- .../plugin/impl/PluginSystemFactory.java | 15 +- .../javasabr/rlib/common/util/ArrayUtils.java | 3658 +++++++++-------- .../javasabr/rlib/common/util/AsyncUtils.java | 27 +- .../rlib/common/util/BufferUtils.java | 126 +- .../javasabr/rlib/common/util/ClassUtils.java | 425 +- .../javasabr/rlib/common/util/Copyable.java | 12 +- .../rlib/common/util/CycleBuffer.java | 114 +- .../javasabr/rlib/common/util/DateUtils.java | 136 +- .../javasabr/rlib/common/util/ExtMath.java | 691 ++-- .../javasabr/rlib/common/util/FileUtils.java | 1586 +++---- .../javasabr/rlib/common/util/HasName.java | 16 +- .../javasabr/rlib/common/util/IOUtils.java | 225 +- .../rlib/common/util/NumberUtils.java | 765 ++-- .../rlib/common/util/ObjectUtils.java | 289 +- .../rlib/common/util/PropertyLoader.java | 87 +- .../rlib/common/util/ReflectionUtils.java | 760 ++-- .../javasabr/rlib/common/util/Reloadable.java | 15 +- .../rlib/common/util/StringUtils.java | 771 ++-- .../java/javasabr/rlib/common/util/Utils.java | 654 ++- .../javasabr/rlib/common/util/VarTable.java | 2564 ++++++------ .../rlib/common/util/array/Array.java | 2410 ++++++----- .../common/util/array/ArrayCollectors.java | 243 +- .../common/util/array/ArrayComparator.java | 36 +- .../rlib/common/util/array/ArrayFactory.java | 170 +- .../rlib/common/util/array/ArrayIterator.java | 20 +- .../common/util/array/ConcurrentArray.java | 1608 ++++---- .../util/array/ConcurrentIntegerArray.java | 40 +- .../rlib/common/util/array/IntegerArray.java | 325 +- .../rlib/common/util/array/LongArray.java | 582 +-- .../util/array/MutableIntegerArray.java | 290 +- .../rlib/common/util/array/ReadOnlyArray.java | 90 +- .../rlib/common/util/array/UnsafeArray.java | 82 +- .../common/util/array/impl/AbstractArray.java | 121 +- .../array/impl/AbstractConcurrentArray.java | 387 +- .../impl/ConcurrentAtomicARSWLockArray.java | 58 +- .../ConcurrentAtomicARSWLockArraySet.java | 64 +- .../impl/ConcurrentReentrantRWLockArray.java | 78 +- .../ConcurrentReentrantRWLockArraySet.java | 68 +- .../impl/ConcurrentStampedLockArray.java | 84 +- .../impl/ConcurrentStampedLockArraySet.java | 68 +- .../util/array/impl/CopyOnModifyArray.java | 347 +- .../util/array/impl/DefaultArrayIterator.java | 83 +- .../util/array/impl/DefaultIntegerArray.java | 353 +- .../common/util/array/impl/FastArray.java | 386 +- .../common/util/array/impl/FastArraySet.java | 64 +- .../common/util/array/impl/FastLongArray.java | 380 +- .../util/array/impl/ReadOnlyFastArray.java | 206 +- .../util/array/impl/ReadOnlyIntegerArray.java | 151 +- .../util/array/impl/SortedFastArray.java | 100 +- .../util/array/impl/SynchronizedArray.java | 274 +- .../rlib/common/util/crypt/SymmetryCrypt.java | 186 +- .../AbstractConcurrentIntegerDictionary.java | 128 +- .../AbstractConcurrentLongDictionary.java | 128 +- .../AbstractConcurrentObjectDictionary.java | 128 +- .../util/dictionary/AbstractDictionary.java | 414 +- .../dictionary/AbstractIntegerDictionary.java | 424 +- .../dictionary/AbstractLongDictionary.java | 433 +- .../dictionary/AbstractObjectDictionary.java | 492 ++- ...urrentAtomicARSWLockIntegerDictionary.java | 95 +- ...oncurrentAtomicARSWLockLongDictionary.java | 89 +- ...currentAtomicARSWLockObjectDictionary.java | 95 +- .../util/dictionary/ConcurrentDictionary.java | 98 +- .../ConcurrentIntegerDictionary.java | 20 +- .../dictionary/ConcurrentLongDictionary.java | 20 +- .../ConcurrentObjectDictionary.java | 409 +- ...ConcurrentStampedLockObjectDictionary.java | 63 +- .../common/util/dictionary/Dictionary.java | 150 +- .../util/dictionary/DictionaryCollectors.java | 283 +- .../util/dictionary/DictionaryFactory.java | 160 +- .../util/dictionary/DictionaryUtils.java | 3 +- .../rlib/common/util/dictionary/Entry.java | 62 +- .../dictionary/FastIntegerDictionary.java | 122 +- .../util/dictionary/FastLongDictionary.java | 122 +- .../util/dictionary/FastObjectDictionary.java | 122 +- .../rlib/common/util/dictionary/IntKey.java | 6 +- .../util/dictionary/IntegerDictionary.java | 337 +- .../dictionary/IntegerDictionaryIterator.java | 134 +- .../common/util/dictionary/IntegerEntry.java | 208 +- .../util/dictionary/LongDictionary.java | 333 +- .../dictionary/LongDictionaryIterator.java | 134 +- .../common/util/dictionary/LongEntry.java | 211 +- .../rlib/common/util/dictionary/LongKey.java | 6 +- .../util/dictionary/ObjectDictionary.java | 501 ++- .../dictionary/ObjectDictionaryIterator.java | 132 +- .../common/util/dictionary/ObjectEntry.java | 156 +- .../ReadOnlyFastLongDictionary.java | 40 +- .../ReadOnlyFastObjectDictionary.java | 64 +- .../dictionary/UnsafeIntegerDictionary.java | 26 +- .../util/dictionary/UnsafeLongDictionary.java | 26 +- .../dictionary/UnsafeObjectDictionary.java | 26 +- .../util/linkedlist/ConcurrentLinkedList.java | 67 +- .../common/util/linkedlist/LinkedList.java | 421 +- .../util/linkedlist/LinkedListFactory.java | 49 +- .../linkedlist/impl/AbstractLinkedList.java | 396 +- .../util/linkedlist/impl/FastLinkedList.java | 757 ++-- .../util/linkedlist/impl/IteratorImpl.java | 216 +- .../common/util/linkedlist/impl/Node.java | 142 +- .../linkedlist/impl/SortedLinkedList.java | 42 +- .../rlib/common/util/os/OperatingSystem.java | 224 +- .../util/os/OperatingSystemResolver.java | 416 +- .../javasabr/rlib/common/util/pools/Pool.java | 188 +- .../rlib/common/util/pools/PoolFactory.java | 181 +- .../rlib/common/util/pools/Reusable.java | 41 +- .../rlib/common/util/pools/ReusablePool.java | 3 +- .../impl/ConcurrentAtomicARSWLockPool.java | 20 +- .../ConcurrentAtomicARSWLockReusablePool.java | 20 +- .../util/pools/impl/ConcurrentPool.java | 76 +- .../impl/ConcurrentReentrantRWLockPool.java | 20 +- .../pools/impl/ConcurrentReusablePool.java | 40 +- .../pools/impl/ConcurrentStampedLockPool.java | 19 +- .../ConcurrentStampedLockReusablePool.java | 20 +- .../rlib/common/util/pools/impl/FastPool.java | 68 +- .../util/pools/impl/FastReusablePool.java | 35 +- .../pools/impl/SynchronizedReusablePool.java | 43 +- .../rlib/common/util/random/FastRandom.java | 122 +- .../rlib/common/util/random/Random.java | 117 +- .../common/util/random/RandomFactory.java | 26 +- .../common/util/ref/AbstractReference.java | 3 +- .../rlib/common/util/ref/ByteReference.java | 16 +- .../rlib/common/util/ref/CharReference.java | 16 +- .../rlib/common/util/ref/DoubleReference.java | 16 +- .../rlib/common/util/ref/FloatReference.java | 16 +- .../common/util/ref/GlobalByteReference.java | 8 +- .../common/util/ref/GlobalCharReference.java | 8 +- .../util/ref/GlobalDoubleReference.java | 8 +- .../common/util/ref/GlobalFloatReference.java | 8 +- .../common/util/ref/GlobalIntReference.java | 8 +- .../common/util/ref/GlobalLongReference.java | 8 +- .../util/ref/GlobalObjectReference.java | 8 +- .../common/util/ref/GlobalShortReference.java | 8 +- .../rlib/common/util/ref/IntReference.java | 16 +- .../rlib/common/util/ref/LongReference.java | 16 +- .../rlib/common/util/ref/ObjectReference.java | 16 +- .../rlib/common/util/ref/Reference.java | 3 +- .../common/util/ref/ReferenceFactory.java | 757 ++-- .../rlib/common/util/ref/ShortReference.java | 16 +- .../rlib/common/util/ref/TLByteReference.java | 8 +- .../rlib/common/util/ref/TLCharReference.java | 8 +- .../common/util/ref/TLDoubleReference.java | 8 +- .../common/util/ref/TLFloatReference.java | 8 +- .../rlib/common/util/ref/TLIntReference.java | 8 +- .../rlib/common/util/ref/TLLongReference.java | 8 +- .../common/util/ref/TLObjectReference.java | 8 +- .../common/util/ref/TLShortReference.java | 8 +- .../java/javasabr/rlib/common/BaseTest.java | 29 +- .../classpath/ClasspathScannerTests.java | 20 +- .../rlib/common/compiler/CompilerTests.java | 29 +- .../executor/TestThreadPoolTaskExecutor.java | 46 +- .../TestPrimitiveAtomicReadWriteLock.java | 169 +- .../rlib/common/geom/QuaternionTests.java | 66 +- .../plugin/extension/ExtensionPointTests.java | 40 +- .../plugin/system/PluginSystemTests.java | 19 +- .../rlib/common/util/ArrayUtilsTest.java | 273 +- .../rlib/common/util/BufferUtilsTest.java | 93 +- .../rlib/common/util/DateUtilsTest.java | 154 +- .../rlib/common/util/FileUtilsTest.java | 128 +- .../rlib/common/util/IOUtilsTest.java | 116 +- .../rlib/common/util/NumberUtilsTest.java | 432 +- .../rlib/common/util/ReferencesTest.java | 278 +- .../rlib/common/util/ReflectionUtilsTest.java | 126 +- .../rlib/common/util/StringUtilsTest.java | 221 +- .../javasabr/rlib/common/util/UtilsTest.java | 24 +- .../rlib/common/util/VarTableTest.java | 253 +- .../rlib/common/util/array/ArrayTest.java | 656 ++- .../util/array/ConcurrentArrayTest.java | 476 +-- .../util/array/CopyOnModifyArrayTest.java | 312 +- .../util/array/DefaultIntegerArrayTest.java | 267 +- .../rlib/common/util/array/FastArrayTest.java | 22 +- .../util/array/ReadOnlyIntegerArrayTest.java | 90 +- .../ConcurrentObjectDictionaryTest.java | 159 +- ...urrentStampedLockObjectDictionaryTest.java | 84 +- .../dictionary/FastLongDictionaryTests.java | 81 +- .../util/dictionary/ObjectDictionaryTest.java | 64 +- .../java/source/TestCompileJavaSource.java | 6 +- .../java/javasabr/rlib/fx/CssClasses.java | 18 +- .../java/javasabr/rlib/fx/LoggerClass.java | 3 +- .../rlib/fx/control/dialog/ControlDialog.java | 468 +-- .../control/dialog/ControlDialogSupport.java | 84 +- .../control/dialog/DefaultControlDialog.java | 108 +- .../fx/control/input/FloatArrayTextField.java | 8 +- .../rlib/fx/control/input/FloatTextField.java | 70 +- .../control/input/IntegerArrayTextField.java | 8 +- .../fx/control/input/IntegerTextField.java | 69 +- .../fx/control/input/NumberTextField.java | 157 +- .../input/ScrollableTypedTextField.java | 88 +- .../rlib/fx/control/input/TypedTextField.java | 114 +- .../rlib/fx/dialog/AbstractPopupDialog.java | 229 +- .../rlib/fx/dialog/SimplePopupDialog.java | 119 +- .../rlib/fx/handler/ControlDragHandler.java | 217 +- .../rlib/fx/handler/ControlResizeHandler.java | 198 +- .../rlib/fx/handler/WindowDragHandler.java | 326 +- .../rlib/fx/handler/WindowResizeHandler.java | 248 +- .../javasabr/rlib/fx/impl/DraggablePanel.java | 236 +- .../rlib/fx/impl/SimpleDraggableElement.java | 72 +- .../rlib/fx/impl/SimpleDroppedPanel.java | 102 +- .../rlib/fx/input/InternalContent.java | 140 +- .../java/javasabr/rlib/fx/util/FXUtils.java | 1060 +++-- .../javasabr/rlib/fx/util/FxControlUtils.java | 482 +-- .../java/javasabr/rlib/fx/util/FxUtils.java | 880 ++-- .../rlib/fx/util/ObservableUtils.java | 375 +- .../converter/FloatArrayStringConverter.java | 40 +- .../IntegerArrayStringConverter.java | 40 +- .../LimitedFloatStringConverter.java | 30 +- .../LimitedIntegerStringConverter.java | 42 +- .../LimitedNumberStringConverter.java | 114 +- .../resources/com/ss/rlib/fx/css/classes.css | 1 + .../rlib/fx/SimpleControlDialogTest.java | 110 +- .../rlib/fx/SimplePopupDialogTest.java | 47 +- .../java/javasabr/rlib/logger/api/Logger.java | 895 ++-- .../rlib/logger/api/LoggerFactory.java | 101 +- .../javasabr/rlib/logger/api/LoggerLevel.java | 94 +- .../rlib/logger/api/LoggerListener.java | 22 +- .../rlib/logger/api/LoggerManager.java | 227 +- .../rlib/logger/api/impl/NullLogger.java | 12 +- .../logger/api/impl/NullLoggerFactory.java | 64 +- .../rlib/logger/impl/DefaultLogger.java | 86 +- .../logger/impl/DefaultLoggerFactory.java | 228 +- .../rlib/logger/impl/FolderFileListener.java | 94 +- .../rlib/logger/impl/DefaultLoggerTest.java | 55 +- .../rlib/logger/slf4j/Slf4jLogger.java | 90 +- .../rlib/logger/slf4j/Slf4jLoggerFactory.java | 80 +- .../rlib/logger/slf4j/Slf4jLoggerTest.java | 10 +- .../javasabr/rlib/mail/sender/MailSender.java | 38 +- .../rlib/mail/sender/MailSenderConfig.java | 16 +- .../UncheckedMessagingException.java | 6 +- .../mail/sender/impl/JavaxMailSender.java | 170 +- .../java/javasabr/rlib/mail/BaseMailTest.java | 20 +- .../rlib/mail/sender/JavaxMailSenderTest.java | 41 +- .../rlib/network/BufferAllocator.java | 106 +- .../javasabr/rlib/network/Connection.java | 120 +- .../java/javasabr/rlib/network/Network.java | 8 +- .../javasabr/rlib/network/NetworkConfig.java | 118 +- .../javasabr/rlib/network/NetworkCryptor.java | 62 +- .../javasabr/rlib/network/NetworkFactory.java | 398 +- .../rlib/network/ServerNetworkConfig.java | 124 +- .../rlib/network/UnsafeConnection.java | 2 +- .../network/annotation/PacketDescription.java | 2 +- .../rlib/network/client/ClientNetwork.java | 41 +- .../client/impl/DefaultClientNetwork.java | 145 +- .../rlib/network/impl/AbstractConnection.java | 357 +- .../rlib/network/impl/AbstractNetwork.java | 19 +- .../network/impl/AbstractSSLConnection.java | 43 +- .../network/impl/DefaultBufferAllocator.java | 136 +- .../rlib/network/impl/DefaultConnection.java | 15 +- .../network/impl/DefaultDataConnection.java | 77 +- .../impl/DefaultDataSSLConnection.java | 91 +- .../network/impl/IdBasedPacketConnection.java | 91 +- .../network/impl/PackedIdBasedConnection.java | 24 +- .../network/impl/ReuseBufferAllocator.java | 253 +- .../network/impl/StringDataConnection.java | 21 +- .../network/impl/StringDataSSLConnection.java | 25 +- .../rlib/network/packet/IdBasedPacket.java | 20 +- .../network/packet/IdBasedReadablePacket.java | 30 +- .../javasabr/rlib/network/packet/Packet.java | 12 +- .../rlib/network/packet/PacketReader.java | 16 +- .../rlib/network/packet/PacketWriter.java | 10 +- .../rlib/network/packet/ReadablePacket.java | 18 +- .../packet/ReusableWritablePacket.java | 88 +- .../rlib/network/packet/WritablePacket.java | 238 +- .../impl/AbstractIdBasedReadablePacket.java | 23 +- .../network/packet/impl/AbstractPacket.java | 52 +- .../packet/impl/AbstractPacketReader.java | 761 ++-- .../packet/impl/AbstractPacketWriter.java | 642 ++- .../packet/impl/AbstractReadablePacket.java | 277 +- .../impl/AbstractReusableWritablePacket.java | 377 +- .../packet/impl/AbstractSSLPacketReader.java | 409 +- .../packet/impl/AbstractSSLPacketWriter.java | 342 +- .../packet/impl/AbstractWritablePacket.java | 32 +- .../packet/impl/DefaultPacketReader.java | 71 +- .../packet/impl/DefaultPacketWriter.java | 98 +- .../packet/impl/DefaultReadablePacket.java | 1 - .../packet/impl/DefaultSSLPacketReader.java | 85 +- .../packet/impl/DefaultSSLPacketWriter.java | 110 +- .../packet/impl/IdBasedPacketReader.java | 80 +- .../packet/impl/IdBasedPacketWriter.java | 67 +- .../packet/impl/SSLWritablePacket.java | 16 +- .../packet/impl/StringReadablePacket.java | 32 +- .../packet/impl/StringWritablePacket.java | 28 +- .../packet/impl/WritablePacketWrapper.java | 28 +- .../registry/ReadablePacketRegistry.java | 225 +- .../impl/IdBasedReadablePacketRegistry.java | 299 +- .../rlib/network/server/ServerNetwork.java | 52 +- .../server/impl/DefaultServerNetwork.java | 259 +- .../rlib/network/util/NetworkUtils.java | 502 ++- .../rlib/network/BaseNetworkTest.java | 382 +- .../rlib/network/DefaultNetworkTest.java | 426 +- .../IdBasedReadablePacketRegistryTest.java | 213 +- .../rlib/network/StringNetworkTest.java | 608 +-- .../rlib/network/StringSSLNetworkTest.java | 428 +- .../testcontainers/FakeSMTPTestContainer.java | 166 +- .../FakeSMTPTestContainerTest.java | 63 +- 454 files changed, 38468 insertions(+), 38210 deletions(-) delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicInteger.java delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicReference.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicInteger.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicReference.java delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicLock.java delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicReadWriteLock.java delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantAtomicLock.java delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantLock.java delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantReadWriteLock.java delete mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalStampedLock.java diff --git a/README.md b/README.md index b962711a..3769cf10 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # License # -Please see the file called LICENSE. - [ ![Download](https://api.bintray.com/packages/javasabr/maven/com.spaceshift.rlib.common/images/download.svg) ](https://bintray.com/javasabr/maven/com.spaceshift.rlib.common/_latestVersion) +Please see the file called LICENSE. +[ ![Download](https://api.bintray.com/packages/javasabr/maven/com.spaceshift.rlib.common/images/download.svg) ](https://bintray.com/javasabr/maven/com.spaceshift.rlib.common/_latestVersion) ## How to use for java 21+ @@ -23,7 +23,7 @@ dependencies { implementation 'javasabr:rlib-testcontainers:9.10.0' } ``` - + #### Maven ```xml @@ -62,23 +62,30 @@ dependencies { ``` ## Most interesting parts: + ### Fake SMTP Server ```java - var container = new FakeSMTPTestContainer() - .withSmtpPassword("pwd") - .withSmtpUser("test_user"); - - container.start(); - container.waitForReadyState(); +var container = new FakeSMTPTestContainer() + .withSmtpPassword("pwd") + .withSmtpUser("test_user"); - // sending emails to this server - - // checking API - var count = container.getEmailCountFrom("from@test.com") - // clearing API - container.deleteEmails(); + container. + +start(); + container. + +waitForReadyState(); + +// sending emails to this server + +// checking API +var count = container.getEmailCountFrom("from@test.com") +// clearing API + container. + +deleteEmails(); ``` ### Classpath Scanner API @@ -97,102 +104,148 @@ dependencies { ```java - var javaSource = getClass().getResource("/java/source/TestCompileJavaSource.java"); - - var compiler = CompilerFactory.newDefaultCompiler(); - var compiled = compiler.compile(javaSource.toURI()); - - var instance = ClassUtils.newInstance(compiled[0]); - var method = instance.getClass().getMethod("makeString"); - var result = method.invoke(instance); +var javaSource = getClass().getResource("/java/source/TestCompileJavaSource.java"); + +var compiler = CompilerFactory.newDefaultCompiler(); +var compiled = compiler.compile(javaSource.toURI()); + +var instance = ClassUtils.newInstance(compiled[0]); +var method = instance + .getClass() + .getMethod("makeString"); +var result = method.invoke(instance); ``` ### VarTable API ```java - var vars = VarTable.newInstance(); - vars.set("string", "Hello"); - vars.set("intArray", toIntegerArray(1, 2, 3, 5)); - vars.set("floatStringArray", "1.5,4.2,5.5"); - vars.set("stringEnum", "FLOAT"); - vars.set("enum", ReferenceType.BYTE); - - var string = vars.getString("string"); - var array = vars.getIntegerArray("intArray", ""); - var floatStringArray = vars.getFloatArray("floatStringArray", ","); - var stringEnum = vars.getEnum("stringEnum", ReferenceType.class); - var anEnum = vars.getEnum("enum", ReferenceType.class); - var unsafeGet = vars.get("enum"); +var vars = VarTable.newInstance(); + vars. + +set("string","Hello"); + vars. + +set("intArray",toIntegerArray(1, 2,3,5)); + vars. + +set("floatStringArray","1.5,4.2,5.5"); + vars. + +set("stringEnum","FLOAT"); + vars. + +set("enum",ReferenceType.BYTE); + +var string = vars.getString("string"); +var array = vars.getIntegerArray("intArray", ""); +var floatStringArray = vars.getFloatArray("floatStringArray", ","); +var stringEnum = vars.getEnum("stringEnum", ReferenceType.class); +var anEnum = vars.getEnum("enum", ReferenceType.class); +var unsafeGet = vars.get("enum"); ``` ### Array API ```java - var array = ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4); - array.sort(Integer::compareTo); +var array = ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4); + array. + +sort(Integer::compareTo); + +// performance operations +var unsafe = array.asUnsafe(); +// prepare the wrapped array to have the size + unsafe. - // performance operations - var unsafe = array.asUnsafe(); - // prepare the wrapped array to have the size - unsafe.prepareForSize(10); - unsafe.unsafeAdd(3); - unsafe.unsafeAdd(9); +prepareForSize(10); + unsafe. - var first = array.first(); - var last = array.last(); +unsafeAdd(3); + unsafe. - // remove the element with saving ordering - array.slowRemove(1); - // remove the element without saving ordering - array.fastRemove(1); +unsafeAdd(9); - // search API - Integer searched = array.search(integer -> integer == 2); - searched = array.search(2, (el, arg) -> el == arg); +var first = array.first(); +var last = array.last(); + +// remove the element with saving ordering + array. + +slowRemove(1); +// remove the element without saving ordering + array. + +fastRemove(1); + +// search API +Integer searched = array.search(integer -> integer == 2); +searched =array. + +search(2,(el, arg) ->el ==arg); // foreach API - array.forEach(5, (el, arg) -> System.out.println(el + arg)); - array.forEach(5, 7, (el, firstArg, secondArg) -> System.out.println(el + firstArg + secondArg)); - - // Stream Collector - Array result = IntStream.range(0, 1000) - .mapToObj(value -> value) - .collect(ArrayCollectors.toArray(Integer.class)); + array. + +forEach(5,(el, arg) ->System.out. + +println(el +arg)); + array. + +forEach(5,7,(el, firstArg, secondArg) ->System.out. + +println(el +firstArg+secondArg)); + +// Stream Collector +Array result = IntStream + .range(0, 1000) + .mapToObj(value -> value) + .collect(ArrayCollectors.toArray(Integer.class)); ``` ### Concurrent Array API ```java - var array = ConcurrentArray.of(Integer.class); - var writeStamp = array.writeLock(); - try { - array.addAll(ArrayFactory.toArray(9, 8, 7, 6, 5, 4, 3)); - array.sort(Integer::compareTo); - } finally { - array.writeUnlock(writeStamp); +var array = ConcurrentArray.of(Integer.class); +var writeStamp = array.writeLock(); + try{ + array. + +addAll(ArrayFactory.toArray(9, 8,7,6,5,4,3)); + array. + +sort(Integer::compareTo); + }finally{ + array. + +writeUnlock(writeStamp); } - var readStamp = array.readLock(); - try { - var first = array.first(); - var last = array.last(); - } finally { - array.readUnlock(readStamp); +var readStamp = array.readLock(); + try{ +var first = array.first(); +var last = array.last(); + }finally{ + array. + +readUnlock(readStamp); } - var last = array.getInReadLock(Array::last); - var result = array.getInReadLock(last, (arr, target) -> arr.search(target, Integer::equals)); +var last = array.getInReadLock(Array::last); +var result = array.getInReadLock(last, (arr, target) -> arr.search(target, Integer::equals)); - array.runInWriteLock(result + 1, Collection::add); - - // Stream Collector - ConcurrentArray result = IntStream.range(0, 1000) - .parallel() - .mapToObj(value -> value) - .collect(ArrayCollectors.toConcurrentArray(Integer.class)); + array. + +runInWriteLock(result +1, Collection::add); + +// Stream Collector +ConcurrentArray result = IntStream + .range(0, 1000) + .parallel() + .mapToObj(value -> value) + .collect(ArrayCollectors.toConcurrentArray(Integer.class)); ``` ### Logger API @@ -225,47 +278,86 @@ dependencies { ### Mail Sender ```java - var config = MailSenderConfig.builder() - .from("from@test.com") - .host("smtp.test.com") - .port(smtpPort) - .password(smtpPassword) - .username(smtpUser) - .useAuth(true) - .enableTtls(true) - .sslHost("smtp.test.com") - .build(); - - var javaxConfig = JavaxMailSender.JavaxMailSenderConfig.builder() - .executorKeepAlive(120) - .executorMaxThreads(20) - .executorMinThreads(1) - .build(); - - var sender = new JavaxMailSender(config, javaxConfig); - sender.send("to@test.com", "Test Subject", "Content"); - sender.sendAsync("to@test.com", "Test Subject", "Content") - .thenAccept(aVoid -> System.out.println("done!")); + var config = MailSenderConfig + .builder() + .from("from@test.com") + .host("smtp.test.com") + .port(smtpPort) + .password(smtpPassword) + .username(smtpUser) + .useAuth(true) + .enableTtls(true) + .sslHost("smtp.test.com") + .build(); + +var javaxConfig = JavaxMailSender.JavaxMailSenderConfig + .builder() + .executorKeepAlive(120) + .executorMaxThreads(20) + .executorMinThreads(1) + .build(); + +var sender = new JavaxMailSender(config, javaxConfig); + sender. + +send("to@test.com","Test Subject","Content"); + sender. + +sendAsync("to@test.com","Test Subject","Content") + . + +thenAccept(aVoid ->System.out. + +println("done!")); ``` + ### Network API + #### Simple String Echo Server/Client + ```java - var serverNetwork = NetworkFactory.newStringDataServerNetwork(); - var serverAddress = serverNetwork.start(); - - serverNetwork.accepted() - .flatMap(Connection::receivedEvents) - .subscribe(event -> { - var message = event.packet.getData(); - System.out.println("Received from client: " + message); - event.connection.send(new StringWritablePacket("Echo: " + message)); - }); - - var clientNetwork = newStringDataClientNetwork(); - clientNetwork.connected(serverAddress) - .doOnNext(connection -> IntStream.range(10, 100) - .forEach(length -> connection.send(new StringWritablePacket(StringUtils.generate(length))))) - .flatMapMany(Connection::receivedEvents) - .subscribe(event -> System.out.println("Received from server: " + event.packet.getData())); +var serverNetwork = NetworkFactory.newStringDataServerNetwork(); +var serverAddress = serverNetwork.start(); + + serverNetwork. + +accepted() + . + +flatMap(Connection::receivedEvents) + . + +subscribe(event ->{ +var message = event.packet.getData(); + System.out. + +println("Received from client: "+message); + event.connection. + +send(new StringWritablePacket("Echo: "+message)); + }); + +var clientNetwork = newStringDataClientNetwork(); + clientNetwork. + +connected(serverAddress) + . + +doOnNext(connection ->IntStream. + +range(10,100) + . + +forEach(length ->connection. + +send(new StringWritablePacket(StringUtils.generate(length))))) + . + +flatMapMany(Connection::receivedEvents) + . + +subscribe(event ->System.out. + +println("Received from server: "+event.packet.getData())); ``` diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 3d2ed4fc..c16a80ac 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -28,12 +28,12 @@ lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" } junit-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit-jupiter" } junit-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit-jupiter" } junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junit-platform-launcher" } -slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } -slf4j-simple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } -slf4j-ext = { module = "org.slf4j:slf4j-ext", version.ref = "slf4j" } -jakarta-mail-api = { module = "jakarta.mail:jakarta.mail-api", version.ref = "jakarta-mail" } -angus-mail = { module = "org.eclipse.angus:angus-mail", version.ref = "angus-mail" } -testcontainers = { module = "org.testcontainers:testcontainers", version.ref = "testcontainers" } +slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +slf4j-simple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } +slf4j-ext = { module = "org.slf4j:slf4j-ext", version.ref = "slf4j" } +jakarta-mail-api = { module = "jakarta.mail:jakarta.mail-api", version.ref = "jakarta-mail" } +angus-mail = { module = "org.eclipse.angus:angus-mail", version.ref = "angus-mail" } +testcontainers = { module = "org.testcontainers:testcontainers", version.ref = "testcontainers" } [bundles] junit = ["junit-engine", "junit-api"] diff --git a/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScanner.java b/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScanner.java index a39b946e..0844c296 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScanner.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScanner.java @@ -7,196 +7,194 @@ import javasabr.rlib.common.classpath.impl.ClassPathScannerImpl; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayFactory; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * THe interface to implement a classpath scanner. * * @author JavaSaBr */ +@NullMarked public interface ClassPathScanner { - String JAR_EXTENSION = ".jar"; - - ClassPathScanner NULL_SCANNER = null; - - ClassPathScanner EMPTY_SCANNER = new ClassPathScannerImpl(ClassPathScanner.class.getClassLoader()) { - - @Override - public void addClasses(@NotNull Array> classes) { - } - - @Override - public void addAdditionalPath(@NotNull String path) { - } - - @Override - public void addAdditionalPaths(@NotNull String[] paths) { - } - - @Override - public void addResources(@NotNull Array resources) { - } - - @Override - public void scan(@Nullable Predicate filter) { - } - }; - - URLClassLoader EMPTY_CLASS_LOADER = - new URLClassLoader(new URL[0], ClassPathScanner.class.getClassLoader()); - - URLClassLoader NULL_CLASS_LOADER = null; - - /** - * Add some classes to this scanner. - * - * @param classes the classes. - */ - void addClasses(@NotNull Array> classes); - - /** - * Add some resources to this scanner. - * - * @param resources the resources. - */ - void addResources(@NotNull Array resources); - - /** - * Sets the flat of using system classpath. - * - * @param useSystemClasspath true if need to use system classpath. - */ - void setUseSystemClasspath(boolean useSystemClasspath); - - /** - * Find all implementations of the interface class. - * - * @param interfaceClass the interface class. - * @param the first argument's type. - * @return the list of found implementations. - */ - default @NotNull Array> findImplements(@NotNull Class interfaceClass) { - Array> result = ArrayFactory.newArray(Class.class); - findImplements(result, interfaceClass); - return result; + String JAR_EXTENSION = ".jar"; + + ClassPathScanner NULL_SCANNER = null; + + ClassPathScanner EMPTY_SCANNER = new ClassPathScannerImpl(ClassPathScanner.class.getClassLoader()) { + + @Override + public void addClasses(Array> classes) { } - /** - * Find all implementations of the interface class. - * - * @param container the container. - * @param interfaceClass the interface class. - * @param the interface's type. - */ - void findImplements(@NotNull Array> container, @NotNull Class interfaceClass); - - /** - * Find all inheriting classes of the parent class. - * - * @param parentClass the parent class. - * @param the classes type. - * @return the list of found inherited classes. - */ - default @NotNull Array> findInherited(@NotNull Class parentClass) { - Array> result = ArrayFactory.newArray(Class.class); - findInherited(result, parentClass); - return result; + @Override + public void addAdditionalPath(String path) { } - /** - * Find all inheriting classes of the parent class. - * - * @param container the container. - * @param parentClass the parent class. - * @param the parent classes type. - */ - void findInherited(@NotNull Array> container, @NotNull Class parentClass); - - /** - * Find all classes annotated via specified annotation.
- * Exclude class types:
    - *
  • Interfaces
  • - *
  • Abstract classes
  • - *
  • Annotations
  • - *
- * - * @param annotationClass the annotation class. - * @return the list of found annotated classes. - */ - default @NotNull Array> findAnnotated(@NotNull Class annotationClass) { - Array> result = ArrayFactory.newArray(Class.class); - findAnnotated(result, annotationClass); - return result; + @Override + public void addAdditionalPaths(String[] paths) { } - /** - * Find all classes annotated via specified annotation.
- * Exclude class types:
    - *
  • Interfaces
  • - *
  • Abstract classes
  • - *
  • Annotations
  • - *
- * - * @param container the container. - * @param annotationClass the annotation class. - */ - void findAnnotated(@NotNull Array> container, @NotNull Class annotationClass); - - /** - * Get all found classes. - * - * @param container the container. - */ - void getFoundClasses(@NotNull Array> container); - - /** - * Get all found resources. - * - * @param container the container. - */ - void getFoundResources(@NotNull Array container); - - /** - * Get all found classes. - * - * @return the array of all found classes. - */ - @NotNull Array> getFoundClasses(); - - /** - * Get all found resources. - * - * @return the array of all found resources. - */ - @NotNull Array getFoundResources(); - - /** - * Start scanning classpath. - */ - default void scan() { - scan(null); + @Override + public void addResources(Array resources) { } - /** - * Start scanning classpath. - * - * @param filter the filter. - */ - void scan(@Nullable Predicate filter); - - /** - * Add the additional path to scan. - * - * @param path the additional path. - */ - void addAdditionalPath(@NotNull String path); - - /** - * Add the additional paths to scan. - * - * @param paths the additional paths. - */ - void addAdditionalPaths(@NotNull String[] paths); + @Override + public void scan(Predicate filter) { + } + }; + + URLClassLoader EMPTY_CLASS_LOADER = new URLClassLoader(new URL[0], ClassPathScanner.class.getClassLoader()); + + @Nullable URLClassLoader NULL_CLASS_LOADER = null; + + /** + * Add some classes to this scanner. + * + * @param classes the classes. + */ + void addClasses(Array> classes); + + /** + * Add some resources to this scanner. + * + * @param resources the resources. + */ + void addResources(Array resources); + + /** + * Sets the flat of using system classpath. + * + * @param useSystemClasspath true if need to use system classpath. + */ + void setUseSystemClasspath(boolean useSystemClasspath); + + /** + * Find all implementations of the interface class. + * + * @param interfaceClass the interface class. + * @param the first argument's type. + * @return the list of found implementations. + */ + default Array> findImplements(Class interfaceClass) { + Array> result = ArrayFactory.newArray(Class.class); + findImplements(result, interfaceClass); + return result; + } + + /** + * Find all implementations of the interface class. + * + * @param container the container. + * @param interfaceClass the interface class. + * @param the interface's type. + */ + void findImplements(Array> container, Class interfaceClass); + + /** + * Find all inheriting classes of the parent class. + * + * @param parentClass the parent class. + * @param the classes type. + * @return the list of found inherited classes. + */ + default Array> findInherited(Class parentClass) { + Array> result = ArrayFactory.newArray(Class.class); + findInherited(result, parentClass); + return result; + } + + /** + * Find all inheriting classes of the parent class. + * + * @param container the container. + * @param parentClass the parent class. + * @param the parent classes type. + */ + void findInherited(Array> container, Class parentClass); + + /** + * Find all classes annotated via specified annotation.
Exclude class types:
    + *
  • Interfaces
  • + *
  • Abstract classes
  • + *
  • Annotations
  • + *
+ * + * @param annotationClass the annotation class. + * @return the list of found annotated classes. + */ + default Array> findAnnotated(Class annotationClass) { + Array> result = ArrayFactory.newArray(Class.class); + findAnnotated(result, annotationClass); + return result; + } + + /** + * Find all classes annotated via specified annotation.
Exclude class types:
    + *
  • Interfaces
  • + *
  • Abstract classes
  • + *
  • Annotations
  • + *
+ * + * @param container the container. + * @param annotationClass the annotation class. + */ + void findAnnotated(Array> container, Class annotationClass); + + /** + * Get all found classes. + * + * @param container the container. + */ + void getFoundClasses(Array> container); + + /** + * Get all found resources. + * + * @param container the container. + */ + void getFoundResources(Array container); + + /** + * Get all found classes. + * + * @return the array of all found classes. + */ + Array> getFoundClasses(); + + /** + * Get all found resources. + * + * @return the array of all found resources. + */ + Array getFoundResources(); + + /** + * Start scanning classpath. + */ + default void scan() { + scan(null); + } + + /** + * Start scanning classpath. + * + * @param filter the filter. + */ + void scan(@Nullable Predicate filter); + + /** + * Add the additional path to scan. + * + * @param path the additional path. + */ + void addAdditionalPath(String path); + + /** + * Add the additional paths to scan. + * + * @param paths the additional paths. + */ + void addAdditionalPaths(String[] paths); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java index 8d1990d9..6d80b2c3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java @@ -3,70 +3,70 @@ import javasabr.rlib.common.classpath.impl.ClassPathScannerImpl; import javasabr.rlib.common.classpath.impl.ManifestClassPathScannerImpl; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory of classpath scanners. * * @author JavaSaBr */ +@NullMarked public final class ClassPathScannerFactory { - /** - * Create a new default class path scanner. - * - * @return the new class path scanner. - */ - public static @NotNull ClassPathScanner newDefaultScanner() { - return new ClassPathScannerImpl(ClassPathScannerFactory.class.getClassLoader()); - } + /** + * Create a new default class path scanner. + * + * @return the new class path scanner. + */ + public static ClassPathScanner newDefaultScanner() { + return new ClassPathScannerImpl(ClassPathScannerFactory.class.getClassLoader()); + } - /** - * Create a new default class path scanner. - * - * @param classLoader the class loader. - * @return the new class path scanner. - */ - public static @NotNull ClassPathScanner newDefaultScanner(@NotNull final ClassLoader classLoader) { - return new ClassPathScannerImpl(classLoader); - } + /** + * Create a new default class path scanner. + * + * @param classLoader the class loader. + * @return the new class path scanner. + */ + public static ClassPathScanner newDefaultScanner(ClassLoader classLoader) { + return new ClassPathScannerImpl(classLoader); + } - /** - * Create a new default class path scanner with additional class paths. - * - * @param classLoader the class loader. - * @param additionalPaths the additional class paths. - * @return the new class path scanner. - */ - public static @NotNull ClassPathScanner newDefaultScanner(@NotNull final ClassLoader classLoader, - @NotNull final String[] additionalPaths) { - final ClassPathScannerImpl scanner = new ClassPathScannerImpl(classLoader); - scanner.addAdditionalPaths(additionalPaths); - return scanner; - } + /** + * Create a new default class path scanner with additional class paths. + * + * @param classLoader the class loader. + * @param additionalPaths the additional class paths. + * @return the new class path scanner. + */ + public static ClassPathScanner newDefaultScanner(ClassLoader classLoader, String[] additionalPaths) { + var scanner = new ClassPathScannerImpl(classLoader); + scanner.addAdditionalPaths(additionalPaths); + return scanner; + } - /** - * Create a new manifest class path scanner. - * - * @param rootClass the root class. - * @return the new class path scanner. - */ - public static @NotNull ClassPathScanner newManifestScanner(@NotNull final Class rootClass) { - return new ManifestClassPathScannerImpl(ClassPathScannerFactory.class.getClassLoader(), rootClass, "Class-Path"); - } + /** + * Create a new manifest class path scanner. + * + * @param rootClass the root class. + * @return the new class path scanner. + */ + public static ClassPathScanner newManifestScanner(Class rootClass) { + return new ManifestClassPathScannerImpl(ClassPathScannerFactory.class.getClassLoader(), rootClass, "Class-Path"); + } - /** - * Create a new manifest class path scanner. - * - * @param rootClass the root class. - * @param classPathKey the class path key. - * @return the new class path scanner. - */ - public static @NotNull ClassPathScanner newManifestScanner(@NotNull final Class rootClass, - @NotNull final String classPathKey) { - return new ManifestClassPathScannerImpl(ClassPathScannerFactory.class.getClassLoader(), rootClass, classPathKey); - } + /** + * Create a new manifest class path scanner. + * + * @param rootClass the root class. + * @param classPathKey the class path key. + * @return the new class path scanner. + */ + public static ClassPathScanner newManifestScanner(Class rootClass, String classPathKey) { + return new ManifestClassPathScannerImpl(ClassPathScannerFactory.class.getClassLoader(), rootClass, classPathKey); + } - private ClassPathScannerFactory() { - throw new RuntimeException(); - } + private ClassPathScannerFactory() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ClassPathScannerImpl.java b/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ClassPathScannerImpl.java index 6b3347e4..3a1de57c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ClassPathScannerImpl.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ClassPathScannerImpl.java @@ -26,415 +26,411 @@ import javasabr.rlib.logger.api.LoggerManager; import lombok.AccessLevel; import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of the {@link ClassPathScanner}. * * @author JavaSaBr */ +@NullMarked @Getter(AccessLevel.PRIVATE) public class ClassPathScannerImpl implements ClassPathScanner { - protected static final Logger LOGGER = LoggerManager.getLogger(ClassPathScanner.class); - - private static final String CLASS_PATH = System.getProperty("java.class.path"); - private static final String PATH_SEPARATOR = File.pathSeparator; - private static final String CLASS_EXTENSION = ".class"; - - /** - * The list of additional paths to scan. - */ - private final @NotNull Array additionalPaths; - - /** - * The class loader. - */ - private final @NotNull ClassLoader loader; - - /** - * The found classes. - */ - private @NotNull Class[] classes; - - /** - * The found resources. - */ - private @NotNull String[] resources; - - /** - * The flag of using system classpath. - */ - private boolean useSystemClassPath; - - public ClassPathScannerImpl(@NotNull ClassLoader classLoader) { - this.additionalPaths = ArrayFactory.newArray(String.class); - this.loader = classLoader; - this.classes = new Class[0]; - this.resources = new String[0]; + protected static final Logger LOGGER = LoggerManager.getLogger(ClassPathScanner.class); + + private static final String CLASS_PATH = System.getProperty("java.class.path"); + private static final String PATH_SEPARATOR = File.pathSeparator; + private static final String CLASS_EXTENSION = ".class"; + + /** + * The list of additional paths to scan. + */ + private final Array additionalPaths; + + /** + * The class loader. + */ + private final ClassLoader loader; + + /** + * The found classes. + */ + private Class[] classes; + + /** + * The found resources. + */ + private String[] resources; + + /** + * The flag of using system classpath. + */ + private boolean useSystemClassPath; + + public ClassPathScannerImpl(ClassLoader classLoader) { + this.additionalPaths = ArrayFactory.newArray(String.class); + this.loader = classLoader; + this.classes = new Class[0]; + this.resources = new String[0]; + } + + @Override + public void addClasses(Array> classes) { + this.classes = ArrayUtils.combine(this.classes, classes.toArray(ArrayUtils.EMPTY_CLASS_ARRAY), Class.class); + } + + @Override + public void addResources(Array resources) { + this.resources = ArrayUtils.combine(this.resources, resources.toArray(ArrayUtils.EMPTY_STRING_ARRAY), String.class); + } + + @Override + public void findImplements(Array> container, Class interfaceClass) { + + if (!interfaceClass.isInterface()) { + throw new IllegalArgumentException("Class " + interfaceClass + " is not interface."); } - @Override - public void addClasses(@NotNull Array> classes) { - this.classes = ArrayUtils.combine( - this.classes, - classes.toArray(ArrayUtils.EMPTY_CLASS_ARRAY), - Class.class - ); - } - - @Override - public void addResources(@NotNull Array resources) { - this.resources = ArrayUtils.combine( - this.resources, - resources.toArray(ArrayUtils.EMPTY_STRING_ARRAY), - String.class - ); - } - - @Override - public void findImplements(@NotNull Array> container, @NotNull Class interfaceClass) { - - if (!interfaceClass.isInterface()) { - throw new IllegalArgumentException("Class " + interfaceClass + " is not interface."); - } + for (var cs : getClasses()) { - for (var cs : getClasses()) { + if (cs.isInterface() || !interfaceClass.isAssignableFrom(cs) || isAbstract(cs.getModifiers())) { + continue; + } - if (cs.isInterface() || !interfaceClass.isAssignableFrom(cs) || isAbstract(cs.getModifiers())) { - continue; - } - - container.add(unsafeNNCast(cs)); - } + container.add(unsafeNNCast(cs)); } + } - @Override - public void findInherited(@NotNull Array> container, @NotNull Class parentClass) { + @Override + public void findInherited(Array> container, Class parentClass) { - if (Modifier.isFinal(parentClass.getModifiers())) { - throw new IllegalArgumentException("Class " + parentClass + " is final class."); - } + if (Modifier.isFinal(parentClass.getModifiers())) { + throw new IllegalArgumentException("Class " + parentClass + " is final class."); + } - for (var cs : getClasses()) { + for (var cs : getClasses()) { - if (cs.isInterface() || cs == parentClass || !parentClass.isAssignableFrom(cs) || - isAbstract(cs.getModifiers())) { - continue; - } + if (cs.isInterface() || cs == parentClass || !parentClass.isAssignableFrom(cs) || isAbstract(cs.getModifiers())) { + continue; + } - container.add(unsafeNNCast(cs)); - } + container.add(unsafeNNCast(cs)); } + } - @Override - public void findAnnotated(@NotNull Array> container, @NotNull Class annotationClass) { - for (var cs : getClasses()) { + @Override + public void findAnnotated(Array> container, Class annotationClass) { + for (var cs : getClasses()) { - if (cs.isInterface() || isAbstract(cs.getModifiers()) || cs.isAnnotation() || - !cs.isAnnotationPresent(annotationClass)) { - continue; - } - - container.add(cs); - } - } + if (cs.isInterface() || isAbstract(cs.getModifiers()) || cs.isAnnotation() || !cs.isAnnotationPresent( + annotationClass)) { + continue; + } - @Override - public void getFoundClasses(@NotNull Array> container) { - container.addAll(getClasses()); + container.add(cs); } - - @Override - public void getFoundResources(@NotNull Array container) { - container.addAll(getResources()); + } + + @Override + public void getFoundClasses(Array> container) { + container.addAll(getClasses()); + } + + @Override + public void getFoundResources(Array container) { + container.addAll(getResources()); + } + + @Override + public Array> getFoundClasses() { + return Array.of(getClasses()); + } + + @Override + public Array getFoundResources() { + return Array.of(getResources()); + } + + /** + * Get a list of paths to scan. + * + * @return the list of paths. + */ + protected String[] getPathsToScan() { + + var systemClasspath = useSystemClasspath() ? getClasspathPaths() : ArrayUtils.EMPTY_STRING_ARRAY; + var capacity = additionalPaths.size() + systemClasspath.length; + + var result = Array.ofType(String.class, capacity); + result.addAll(systemClasspath); + result.addAll(additionalPaths); + + return result.toArray(String.class); + } + + /** + * Return true if need to scan the system classpath. + * + * @return true if need to scan the system classpath. + */ + protected boolean useSystemClasspath() { + return useSystemClassPath; + } + + @Override + public void setUseSystemClasspath(boolean useSystemClasspath) { + this.useSystemClassPath = useSystemClasspath; + } + + /** + * Get the list of paths of system classpath. + * + * @return the list of paths of system classpath. + */ + protected String[] getClasspathPaths() { + return CLASS_PATH.split(PATH_SEPARATOR); + } + + /** + * Load a class by its name to container. + * + * @param rootPath the root folder. + * @param file the class file. + * @param name the name. + * @param container the container. + */ + private void loadClass( + @Nullable Path rootPath, + @Nullable Path file, + String name, + Array> container) { + + if (!name.endsWith(CLASS_EXTENSION)) { + return; } - @Override - public @NotNull Array> getFoundClasses() { - return Array.of(getClasses()); - } + String className; + try { - @Override - public @NotNull Array getFoundResources() { - return Array.of(getResources()); - } + StringBuilder result = new StringBuilder(name.length() - CLASS_EXTENSION.length()); - /** - * Get a list of paths to scan. - * - * @return the list of paths. - */ - protected @NotNull String[] getPathsToScan() { + for (int i = 0, length = name.length() - CLASS_EXTENSION.length(); i < length; i++) { - var systemClasspath = useSystemClasspath() ? getClasspathPaths() : ArrayUtils.EMPTY_STRING_ARRAY; - var capacity = additionalPaths.size() + systemClasspath.length; + char ch = name.charAt(i); - var result = Array.ofType(String.class, capacity); - result.addAll(systemClasspath); - result.addAll(additionalPaths); + if (ch == '/' || ch == '\\') { + ch = '.'; + } - return result.toArray(String.class); - } + result.append(ch); + } - /** - * Return true if need to scan the system classpath. - * - * @return true if need to scan the system classpath. - */ - protected boolean useSystemClasspath() { - return useSystemClassPath; - } + className = result.toString(); - @Override - public void setUseSystemClasspath(boolean useSystemClasspath) { - this.useSystemClassPath = useSystemClasspath; + } catch (Exception e) { + LOGGER.warning(name, arg -> "Incorrect replaced " + arg + " to java path, used separator " + File.separator); + return; } - /** - * Get the list of paths of system classpath. - * - * @return the list of paths of system classpath. - */ - protected @NotNull String[] getClasspathPaths() { - return CLASS_PATH.split(PATH_SEPARATOR); + try { + container.add(getLoader().loadClass(className)); + } catch (NoClassDefFoundError error) { + LOGGER.warning( + "Can't load class: " + className + "\n" + "Original name:" + name + "\n" + "Root folder: " + rootPath + "\n" + + "Class file: " + file); + LOGGER.warning(error); + } catch (Throwable e) { + LOGGER.warning(e); } - - /** - * Load a class by its name to container. - * - * @param rootPath the root folder. - * @param file the class file. - * @param name the name. - * @param container the container. - */ - private void loadClass( - @Nullable Path rootPath, - @Nullable Path file, - @NotNull String name, - @NotNull Array> container - ) { - - if (!name.endsWith(CLASS_EXTENSION)) { - return; + } + + /** + * Scan a directory and find here classes, resources or jars. + * + * @param classes the classes container. + * @param resources the resources container. + * @param directory the directory. + */ + private void scanDirectory( + Path rootPath, + Array> classes, + Array resources, + Path directory) { + + try (var stream = Files.newDirectoryStream(directory)) { + for (var file : stream) { + + if (Files.isDirectory(file)) { + scanDirectory(rootPath, classes, resources, file); + continue; } - String className; - try { + String filename = file + .getFileName() + .toString(); - StringBuilder result = new StringBuilder(name.length() - CLASS_EXTENSION.length()); + if (filename.endsWith(JAR_EXTENSION)) { + scanJar(classes, resources, file); + } else if (filename.endsWith(CLASS_EXTENSION)) { - for (int i = 0, length = name.length() - CLASS_EXTENSION.length(); i < length; i++) { + String path = file + .subpath(rootPath.getNameCount(), file.getNameCount()) + .toString(); - char ch = name.charAt(i); + if (path.startsWith(File.separator)) { + path = path.substring(1, path.length()); + } - if (ch == '/' || ch == '\\') { - ch = '.'; - } + loadClass(rootPath, file, path, classes); - result.append(ch); - } + } else if (!filename.endsWith(Compiler.SOURCE_EXTENSION)) { - className = result.toString(); + String path = file + .subpath(rootPath.getNameCount(), file.getNameCount()) + .toString(); - } catch (Exception e) { - LOGGER.warning(name, arg -> - "Incorrect replaced " + arg + " to java path, used separator " + File.separator); - return; - } + if (path.startsWith(File.separator)) { + path = path.substring(1, path.length()); + } - try { - container.add(getLoader().loadClass(className)); - } catch (NoClassDefFoundError error) { - LOGGER.warning("Can't load class: " + className + "\n" + "Original name:" + name + - "\n" + "Root folder: " + rootPath + "\n" + "Class file: " + file); - LOGGER.warning(error); - } catch (Throwable e) { - LOGGER.warning(e); + resources.add(path); } - } - - /** - * Scan a directory and find here classes, resources or jars. - * - * @param classes the classes container. - * @param resources the resources container. - * @param directory the directory. - */ - private void scanDirectory( - @NotNull Path rootPath, - @NotNull Array> classes, - @NotNull Array resources, - @NotNull Path directory - ) { - - try (var stream = Files.newDirectoryStream(directory)) { - for (var file : stream) { + } - if (Files.isDirectory(file)) { - scanDirectory(rootPath, classes, resources, file); - continue; - } - - String filename = file.getFileName().toString(); - - if (filename.endsWith(JAR_EXTENSION)) { - scanJar(classes, resources, file); - } else if (filename.endsWith(CLASS_EXTENSION)) { - - String path = file.subpath(rootPath.getNameCount(), file.getNameCount()).toString(); - - if (path.startsWith(File.separator)) { - path = path.substring(1, path.length()); - } - - loadClass(rootPath, file, path, classes); - - } else if (!filename.endsWith(Compiler.SOURCE_EXTENSION)) { - - String path = file.subpath(rootPath.getNameCount(), file.getNameCount()).toString(); - - if (path.startsWith(File.separator)) { - path = path.substring(1, path.length()); - } - - resources.add(path); - } - } - - } catch (IOException ex) { - LOGGER.warning(ex); - } + } catch (IOException ex) { + LOGGER.warning(ex); + } + } + + /** + * Scan a .jar to load classes. + * + * @param classes the classes container. + * @param resources the resources container. + * @param jarFile the .jar file. + */ + private void scanJar(Array> classes, Array resources, Path jarFile) { + + if (!Files.exists(jarFile)) { + LOGGER.warning(jarFile, arg -> "Not exists " + arg); + return; } - /** - * Scan a .jar to load classes. - * - * @param classes the classes container. - * @param resources the resources container. - * @param jarFile the .jar file. - */ - private void scanJar(@NotNull Array> classes, @NotNull Array resources, @NotNull Path jarFile) { - - if (!Files.exists(jarFile)) { - LOGGER.warning(jarFile, arg -> "Not exists " + arg); - return; - } - - var rout = new ReuseBytesOutputStream(); - var rin = new ReuseBytesInputStream(); + var rout = new ReuseBytesOutputStream(); + var rin = new ReuseBytesInputStream(); - var buffer = new byte[128]; + var buffer = new byte[128]; - try (var jin = new JarInputStream(Files.newInputStream(jarFile))) { - scanJarInputStream(classes, resources, rout, rin, buffer, jin); - } catch (ZipException e) { - LOGGER.warning(jarFile, arg -> "Can't open zip file " + arg); - LOGGER.warning(e); - } catch (IOException e) { - LOGGER.warning(e); - } + try (var jin = new JarInputStream(Files.newInputStream(jarFile))) { + scanJarInputStream(classes, resources, rout, rin, buffer, jin); + } catch (ZipException e) { + LOGGER.warning(jarFile, arg -> "Can't open zip file " + arg); + LOGGER.warning(e); + } catch (IOException e) { + LOGGER.warning(e); } - - private void scanJarInputStream( - @NotNull Array> classes, - @NotNull Array resources, - @NotNull ReuseBytesOutputStream rout, - @NotNull ReuseBytesInputStream rin, @NotNull byte[] buffer, - @NotNull JarInputStream jin - ) throws IOException { - - for (var entry = jin.getNextJarEntry(); entry != null; entry = jin.getNextJarEntry()) { - - if (entry.isDirectory()) { - continue; - } - - String name = entry.getName(); - - if (name.endsWith(JAR_EXTENSION)) { - rout.reset(); - IOUtils.copy(jin, rout, buffer, false); - rin.initFor(rout.getData(), 0, rout.size()); - scanJar(classes, resources, rin); - } else if (name.endsWith(CLASS_EXTENSION)) { - loadClass(null, null, name, classes); - } else if (!name.endsWith(Compiler.SOURCE_EXTENSION)) { - resources.add(name); - } - } + } + + private void scanJarInputStream( + Array> classes, + Array resources, + ReuseBytesOutputStream rout, + ReuseBytesInputStream rin, + byte[] buffer, + JarInputStream jin) throws IOException { + + for (var entry = jin.getNextJarEntry(); entry != null; entry = jin.getNextJarEntry()) { + + if (entry.isDirectory()) { + continue; + } + + String name = entry.getName(); + + if (name.endsWith(JAR_EXTENSION)) { + rout.reset(); + IOUtils.copy(jin, rout, buffer, false); + rin.initFor(rout.getData(), 0, rout.size()); + scanJar(classes, resources, rin); + } else if (name.endsWith(CLASS_EXTENSION)) { + loadClass(null, null, name, classes); + } else if (!name.endsWith(Compiler.SOURCE_EXTENSION)) { + resources.add(name); + } } - - /** - * Scan a .jar to load classes. - * - * @param classes the classes container. - * @param resources the resources container. - * @param jarFile the input stream of a .jar. - */ - private void scanJar( - @NotNull Array> classes, - @NotNull Array resources, - @NotNull InputStream jarFile - ) { - - var rout = new ReuseBytesOutputStream(); - var rin = new ReuseBytesInputStream(); - - var buffer = new byte[128]; - - try (var jin = new JarInputStream(jarFile)) { - scanJarInputStream(classes, resources, rout, rin, buffer, jin); - } catch (final ZipException e) { - LOGGER.warning(jarFile, arg -> "Can't open zip file " + arg); - LOGGER.warning(e); - } catch (final IOException e) { - LOGGER.warning(e); - } + } + + /** + * Scan a .jar to load classes. + * + * @param classes the classes container. + * @param resources the resources container. + * @param jarFile the input stream of a .jar. + */ + private void scanJar(Array> classes, Array resources, InputStream jarFile) { + + var rout = new ReuseBytesOutputStream(); + var rin = new ReuseBytesInputStream(); + + var buffer = new byte[128]; + + try (var jin = new JarInputStream(jarFile)) { + scanJarInputStream(classes, resources, rout, rin, buffer, jin); + } catch (final ZipException e) { + LOGGER.warning(jarFile, arg -> "Can't open zip file " + arg); + LOGGER.warning(e); + } catch (final IOException e) { + LOGGER.warning(e); } + } - @Override - public void scan(@Nullable Predicate filter) { + @Override + public void scan(@Nullable Predicate filter) { - var paths = getPathsToScan(); + var paths = getPathsToScan(); - Array> classes = Array.ofType(Class.class); - Array resources = Array.ofType(String.class); + Array> classes = Array.ofType(Class.class); + Array resources = Array.ofType(String.class); - for (var path : paths) { + for (var path : paths) { - var file = Paths.get(path); + var file = Paths.get(path); - if (!Files.exists(file) || (filter != null && !filter.test(path))) { - continue; - } + if (!Files.exists(file) || (filter != null && !filter.test(path))) { + continue; + } - LOGGER.debug(file, arg -> "Scan " + arg); + LOGGER.debug(file, arg -> "Scan " + arg); - var filename = file.getFileName().toString(); + var filename = file + .getFileName() + .toString(); - if (Files.isDirectory(file)) { - scanDirectory(file, classes, resources, file); - } else if (filename.endsWith(JAR_EXTENSION)) { - scanJar(classes, resources, file); - } - } + if (Files.isDirectory(file)) { + scanDirectory(file, classes, resources, file); + } else if (filename.endsWith(JAR_EXTENSION)) { + scanJar(classes, resources, file); + } + } - this.classes = classes.toArray(ArrayUtils.EMPTY_CLASS_ARRAY); - this.resources = resources.toArray(ArrayUtils.EMPTY_STRING_ARRAY); + this.classes = classes.toArray(ArrayUtils.EMPTY_CLASS_ARRAY); + this.resources = resources.toArray(ArrayUtils.EMPTY_STRING_ARRAY); - LOGGER.debug(getClasses(), getResources(), (arg1, arg2) -> - "Scanned " + arg1.length + " classes and " + arg2.length + " resources."); - } + LOGGER.debug( + getClasses(), + getResources(), + (arg1, arg2) -> "Scanned " + arg1.length + " classes and " + arg2.length + " resources."); + } - @Override - public void addAdditionalPath(@NotNull String path) { - this.additionalPaths.add(path); - } + @Override + public void addAdditionalPath(String path) { + this.additionalPaths.add(path); + } - @Override - public void addAdditionalPaths(@NotNull String[] paths) { - this.additionalPaths.addAll(paths); - } + @Override + public void addAdditionalPaths(String[] paths) { + this.additionalPaths.addAll(paths); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ManifestClassPathScannerImpl.java b/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ManifestClassPathScannerImpl.java index fe5d7175..e145be7e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ManifestClassPathScannerImpl.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/classpath/impl/ManifestClassPathScannerImpl.java @@ -7,96 +7,96 @@ import javasabr.rlib.common.util.Utils; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayFactory; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the {@link ClassPathScanner} with parsing manifest file. * * @author JavaSaBr */ +@NullMarked public class ManifestClassPathScannerImpl extends ClassPathScannerImpl { - /** - * The roo class. - */ - private final @NotNull Class rootClass; - - /** - * The classpath key. - */ - private final @NotNull String classPathKey; - - public ManifestClassPathScannerImpl( - @NotNull ClassLoader classLoader, - @NotNull Class rootClass, - @NotNull String classPathKey - ) { - super(classLoader); - this.rootClass = rootClass; - this.classPathKey = classPathKey; - } - - /** - * Get manifest class path. - * - * @return the class paths. - */ - protected @NotNull String[] getManifestClassPath() { - - var root = Utils.getRootFolderFromClass(rootClass); - var result = Array.ofType(String.class); - - var currentThread = Thread.currentThread(); - var loader = currentThread.getContextClassLoader(); - var urls = Utils.uncheckedGet(loader, arg -> arg.getResources(JarFile.MANIFEST_NAME)); - - while (urls.hasMoreElements()) { - - try { - - var url = urls.nextElement(); - var is = url.openStream(); - - if (is == null) { - LOGGER.warning(url, arg -> "not found input stream for the url " + arg); - continue; - } - - var manifest = new Manifest(is); - var attributes = manifest.getMainAttributes(); + /** + * The roo class. + */ + private final Class rootClass; + + /** + * The classpath key. + */ + private final String classPathKey; + + public ManifestClassPathScannerImpl( + ClassLoader classLoader, + Class rootClass, + String classPathKey) { + super(classLoader); + this.rootClass = rootClass; + this.classPathKey = classPathKey; + } + + /** + * Get manifest class path. + * + * @return the class paths. + */ + protected String[] getManifestClassPath() { + + var root = Utils.getRootFolderFromClass(rootClass); + var result = Array.ofType(String.class); + + var currentThread = Thread.currentThread(); + var loader = currentThread.getContextClassLoader(); + var urls = Utils.uncheckedGet(loader, arg -> arg.getResources(JarFile.MANIFEST_NAME)); + + while (urls.hasMoreElements()) { + + try { + + var url = urls.nextElement(); + var is = url.openStream(); + + if (is == null) { + LOGGER.warning(url, arg -> "not found input stream for the url " + arg); + continue; + } - var value = attributes.getValue(classPathKey); + var manifest = new Manifest(is); + var attributes = manifest.getMainAttributes(); - if (value == null) { - continue; - } + var value = attributes.getValue(classPathKey); - var classpath = value.split(" "); + if (value == null) { + continue; + } - for (var path : classpath) { + var classpath = value.split(" "); - var file = root.resolve(path); + for (var path : classpath) { - if (Files.exists(file)) { - result.add(file.toString()); - } - } + var file = root.resolve(path); - } catch (Exception exc) { - LOGGER.warning(exc); - } + if (Files.exists(file)) { + result.add(file.toString()); + } } - return result.toArray(String.class); + } catch (Exception exc) { + LOGGER.warning(exc); + } } - @Override - protected @NotNull String[] getPathsToScan() { + return result.toArray(String.class); + } - var result = ArrayFactory.newArraySet(String.class); - result.addAll(super.getPathsToScan()); - result.addAll(getManifestClassPath()); + @Override + protected String[] getPathsToScan() { - return result.toArray(String.class); - } + var result = ArrayFactory.newArraySet(String.class); + result.addAll(super.getPathsToScan()); + result.addAll(getManifestClassPath()); + + return result.toArray(String.class); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java index f33cc518..381e478c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java @@ -1,18 +1,19 @@ package javasabr.rlib.common.compiler; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement byte code container. * * @author JavaSaBr */ +@NullMarked public interface ByteCode { - /** - * Get the byte code. - * - * @return the byte code. - */ - @NotNull byte[] getByteCode(); + /** + * Get the byte code. + * + * @return the byte code. + */ + byte[] getByteCode(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java index d10ae6e3..5b02c189 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java @@ -4,61 +4,63 @@ import java.net.URI; import java.nio.file.Path; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a compiler. * * @author JavaSaBr */ +@NullMarked public interface Compiler { - /** - * The constant SOURCE_EXTENSION. - */ - @NotNull String SOURCE_EXTENSION = ".java"; + /** + * The constant SOURCE_EXTENSION. + */ + String SOURCE_EXTENSION = ".java"; - /** - * The constant CLASS_EXTENSION. - */ - @NotNull String CLASS_EXTENSION = ".class"; + /** + * The constant CLASS_EXTENSION. + */ + String CLASS_EXTENSION = ".class"; - /** - * Compile files. - * - * @param files the file list. - * @return the classes list. - */ - @NotNull Class[] compile(@NotNull File... files); + /** + * Compile files. + * + * @param files the file list. + * @return the classes list. + */ + Class[] compile(@NotNull File... files); - /** - * Compile files. - * - * @param paths the file list. - * @return the classes list. - */ - @NotNull Class[] compile(@NotNull Path... paths); + /** + * Compile files. + * + * @param paths the file list. + * @return the classes list. + */ + Class[] compile(@NotNull Path... paths); - /** - * Compile resources. - * - * @param uris the resource list. - * @return the classes list. - */ - @NotNull Class[] compile(@NotNull URI... uris); + /** + * Compile resources. + * + * @param uris the resource list. + * @return the classes list. + */ + Class[] compile(@NotNull URI... uris); - /** - * Compile all classes from directories. - * - * @param files the directory list. - * @return the classes list. - */ - @NotNull Class[] compileDirectory(@NotNull File... files); + /** + * Compile all classes from directories. + * + * @param files the directory list. + * @return the classes list. + */ + Class[] compileDirectory(@NotNull File... files); - /** - * Compile all classes from directories. - * - * @param paths the directory list. - * @return the classes list. - */ - @NotNull Class[] compileDirectory(@NotNull Path... paths); + /** + * Compile all classes from directories. + * + * @param paths the directory list. + * @return the classes list. + */ + Class[] compileDirectory(@NotNull Path... paths); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java index 738d429c..ba0d258d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java @@ -3,33 +3,35 @@ import javasabr.rlib.common.compiler.impl.CompilerImpl; import javax.tools.ToolProvider; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory of java compilers. * * @author JavaSaBr */ +@NullMarked public class CompilerFactory { - /** - * Check availability compiler API in current runtime. - * - * @return true if a compiler is available. - */ - public static boolean isAvailableCompiler() { - return ToolProvider.getSystemJavaCompiler() != null; - } + /** + * Check availability compiler API in current runtime. + * + * @return true if a compiler is available. + */ + public static boolean isAvailableCompiler() { + return ToolProvider.getSystemJavaCompiler() != null; + } - /** - * Create a new default compiler. - * - * @return the new compiler. - */ - public static @NotNull Compiler newDefaultCompiler() { - return new CompilerImpl(true); - } + /** + * Create a new default compiler. + * + * @return the new compiler. + */ + public static Compiler newDefaultCompiler() { + return new CompilerImpl(true); + } - private CompilerFactory() { - throw new RuntimeException(); - } + private CompilerFactory() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java index ef36b458..43466b7f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java @@ -15,24 +15,24 @@ */ public class CompileByteCode extends SimpleJavaFileObject implements ByteCode { - /** - * The stream with byte code. - */ - @NotNull - private final ByteArrayOutputStream outputStream; + /** + * The stream with byte code. + */ + @NotNull + private final ByteArrayOutputStream outputStream; - public CompileByteCode(@NotNull final String name) { - super(URI.create("byte:///" + name.replace('/', '.') + Compiler.CLASS_EXTENSION), Kind.CLASS); - this.outputStream = new ByteArrayOutputStream(); - } + public CompileByteCode(@NotNull final String name) { + super(URI.create("byte:///" + name.replace('/', '.') + Compiler.CLASS_EXTENSION), Kind.CLASS); + this.outputStream = new ByteArrayOutputStream(); + } - @Override - public @NotNull byte[] getByteCode() { - return outputStream.toByteArray(); - } + @Override + public @NotNull byte[] getByteCode() { + return outputStream.toByteArray(); + } - @Override - public @NotNull OutputStream openOutputStream() { - return outputStream; - } + @Override + public @NotNull OutputStream openOutputStream() { + return outputStream; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java index aa42a3f2..7fdacb3f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java @@ -14,37 +14,37 @@ */ public class CompileClassLoader extends ClassLoader { - /** - * The list of byte codes of loaded classes. - */ - @NotNull - private final Array byteCode; - - public CompileClassLoader() { - this.byteCode = ArrayFactory.newArray(ByteCode.class); + /** + * The list of byte codes of loaded classes. + */ + @NotNull + private final Array byteCode; + + public CompileClassLoader() { + this.byteCode = ArrayFactory.newArray(ByteCode.class); + } + + /** + * Add a new compiled class. + * + * @param byteCode the byte code + */ + public synchronized void addByteCode(@NotNull ByteCode byteCode) { + this.byteCode.add(byteCode); + } + + @Override + protected synchronized @Nullable Class findClass(@NotNull String name) { + + if (byteCode.isEmpty()) { + return null; } - /** - * Add a new compiled class. - * - * @param byteCode the byte code - */ - public synchronized void addByteCode(@NotNull ByteCode byteCode) { - this.byteCode.add(byteCode); + for (var byteCode : this.byteCode) { + var content = byteCode.getByteCode(); + return Utils.uncheckedGet(() -> defineClass(name, content, 0, content.length)); } - @Override - protected synchronized @Nullable Class findClass(@NotNull String name) { - - if (byteCode.isEmpty()) { - return null; - } - - for (var byteCode : this.byteCode) { - var content = byteCode.getByteCode(); - return Utils.uncheckedGet(() -> defineClass(name, content, 0, content.length)); - } - - return null; - } + return null; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java index e802af62..9e33fd9f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java @@ -16,50 +16,54 @@ */ public class CompileJavaFileManager extends ForwardingJavaFileManager { - /** - * The list of names of loaded classes. - */ - @NotNull - private final Array classNames; + /** + * The list of names of loaded classes. + */ + @NotNull + private final Array classNames; - /** - * The loaded of compiled classes. - */ - @NotNull - private final CompileClassLoader loader; + /** + * The loaded of compiled classes. + */ + @NotNull + private final CompileClassLoader loader; - public CompileJavaFileManager(@NotNull final StandardJavaFileManager fileManager, - @NotNull final CompileClassLoader loader) { - super(fileManager); - this.loader = loader; - this.classNames = ArrayFactory.newArray(String.class); - } + public CompileJavaFileManager( + @NotNull final StandardJavaFileManager fileManager, + @NotNull final CompileClassLoader loader) { + super(fileManager); + this.loader = loader; + this.classNames = ArrayFactory.newArray(String.class); + } - /** - * Clear the list of names of loaded classes. - */ - public void clear() { - classNames.clear(); - } + /** + * Clear the list of names of loaded classes. + */ + public void clear() { + classNames.clear(); + } - /** - * Get class names. - * - * @return the list of names of loaded classes. - */ - public @NotNull String[] getClassNames() { - return classNames.toArray(new String[classNames.size()]); - } + /** + * Get class names. + * + * @return the list of names of loaded classes. + */ + public @NotNull String[] getClassNames() { + return classNames.toArray(new String[classNames.size()]); + } - @Override - public JavaFileObject getJavaFileForOutput(@NotNull final Location location, @NotNull final String name, - @NotNull final Kind kind, @NotNull final FileObject sibling) { + @Override + public JavaFileObject getJavaFileForOutput( + @NotNull final Location location, + @NotNull final String name, + @NotNull final Kind kind, + @NotNull final FileObject sibling) { - final CompileByteCode byteCode = new CompileByteCode(name); + final CompileByteCode byteCode = new CompileByteCode(name); - loader.addByteCode(byteCode); - classNames.add(name); + loader.addByteCode(byteCode); + classNames.add(name); - return byteCode; - } + return byteCode; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java index ceb9f40b..d62be3df 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java @@ -17,35 +17,35 @@ */ public class CompileListener implements DiagnosticListener { - /** - * The list of diagnostic reports. - */ - @NotNull - private final Array> diagnostics; - - public CompileListener() { - this.diagnostics = ArrayFactory.newArray(Diagnostic.class); - } - - /** - * Clear reports. - */ - public void clear() { - diagnostics.clear(); - } - - /** - * Get diagnostics. - * - * @return the list of diagnostic reports. - */ - public @NotNull Diagnostic[] getDiagnostics() { - final Diagnostic[] array = diagnostics.toArray(Diagnostic.class); - return notNull(unsafeCast(array)); - } - - @Override - public void report(@NotNull final Diagnostic diagnostic) { - diagnostics.add(diagnostic); - } + /** + * The list of diagnostic reports. + */ + @NotNull + private final Array> diagnostics; + + public CompileListener() { + this.diagnostics = ArrayFactory.newArray(Diagnostic.class); + } + + /** + * Clear reports. + */ + public void clear() { + diagnostics.clear(); + } + + /** + * Get diagnostics. + * + * @return the list of diagnostic reports. + */ + public @NotNull Diagnostic[] getDiagnostics() { + final Diagnostic[] array = diagnostics.toArray(Diagnostic.class); + return notNull(unsafeCast(array)); + } + + @Override + public void report(@NotNull final Diagnostic diagnostic) { + diagnostics.add(diagnostic); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java index b7cd1105..3b4b2037 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java @@ -29,256 +29,270 @@ */ public class CompilerImpl implements Compiler { - @NotNull - private static final Logger LOGGER = LoggerManager.getLogger(Compiler.class); - - /** - * The constant EMPTY_CLASSES. - */ - @NotNull - private static final Class[] EMPTY_CLASSES = new Class[0]; - - /** - * The compile listener. - */ - @NotNull - private final CompileListener listener; - - /** - * The java compiler. - */ - @NotNull - private final JavaCompiler compiler; - - /** - * The class loader. - */ - @NotNull - private final CompileClassLoader loader; - - /** - * The java files manager. - */ - @NotNull - private final CompileJavaFileManager fileManager; - - /** - * The flag of showing reports. - */ - private final boolean showDiagnostic; - - public CompilerImpl(final boolean showDiagnostic) { - this.compiler = ToolProvider.getSystemJavaCompiler(); - this.listener = new CompileListener(); - this.loader = new CompileClassLoader(); - - final StandardJavaFileManager standardJavaFileManager = compiler.getStandardFileManager(listener, null, null); - - this.fileManager = new CompileJavaFileManager(standardJavaFileManager, loader); - this.showDiagnostic = showDiagnostic; + @NotNull + private static final Logger LOGGER = LoggerManager.getLogger(Compiler.class); + + /** + * The constant EMPTY_CLASSES. + */ + @NotNull + private static final Class[] EMPTY_CLASSES = new Class[0]; + + /** + * The compile listener. + */ + @NotNull + private final CompileListener listener; + + /** + * The java compiler. + */ + @NotNull + private final JavaCompiler compiler; + + /** + * The class loader. + */ + @NotNull + private final CompileClassLoader loader; + + /** + * The java files manager. + */ + @NotNull + private final CompileJavaFileManager fileManager; + + /** + * The flag of showing reports. + */ + private final boolean showDiagnostic; + + public CompilerImpl(final boolean showDiagnostic) { + this.compiler = ToolProvider.getSystemJavaCompiler(); + this.listener = new CompileListener(); + this.loader = new CompileClassLoader(); + + final StandardJavaFileManager standardJavaFileManager = compiler.getStandardFileManager(listener, null, null); + + this.fileManager = new CompileJavaFileManager(standardJavaFileManager, loader); + this.showDiagnostic = showDiagnostic; + } + + @Override + public @NotNull Class[] compile(@NotNull final File... files) { + if (files.length < 1) { + return EMPTY_CLASSES; } - @Override - public @NotNull Class[] compile(@NotNull final File... files) { - if (files.length < 1) return EMPTY_CLASSES; + final Array javaSource = Arrays + .stream(files) + .map(JavaFileSource::new) + .collect(ArrayCollectors.toArray(JavaFileObject.class)); - final Array javaSource = Arrays.stream(files) - .map(JavaFileSource::new) - .collect(ArrayCollectors.toArray(JavaFileObject.class)); + return compile(null, javaSource); + } - return compile(null, javaSource); + @Override + public @NotNull Class[] compile(@NotNull final Path... paths) { + if (paths.length < 1) { + return EMPTY_CLASSES; } - @Override - public @NotNull Class[] compile(@NotNull final Path... paths) { - if (paths.length < 1) return EMPTY_CLASSES; + final Array javaSource = Arrays + .stream(paths) + .map(JavaFileSource::new) + .collect(ArrayCollectors.toArray(JavaFileObject.class)); - final Array javaSource = Arrays.stream(paths) - .map(JavaFileSource::new) - .collect(ArrayCollectors.toArray(JavaFileObject.class)); + return compile(null, javaSource); + } - return compile(null, javaSource); - } - - @Override - public @NotNull Class[] compile(@NotNull final URI... uris) { + @Override + public @NotNull Class[] compile(@NotNull final URI... uris) { - final Array javaSource = Arrays.stream(uris) - .map(JavaFileSource::new) - .collect(ArrayCollectors.toArray(JavaFileObject.class)); + final Array javaSource = Arrays + .stream(uris) + .map(JavaFileSource::new) + .collect(ArrayCollectors.toArray(JavaFileObject.class)); - return compile(null, javaSource); - } + return compile(null, javaSource); + } - /** - * Compile the list of sources with the list of options. - * - * @param options the compile options. - * @param source the list of sources. - * @return the list of compiled classes. - */ - protected synchronized @NotNull Class[] compile(@Nullable final Iterable options, - @NotNull final Iterable source) { + /** + * Compile the list of sources with the list of options. + * + * @param options the compile options. + * @param source the list of sources. + * @return the list of compiled classes. + */ + protected synchronized @NotNull Class[] compile( + @Nullable final Iterable options, + @NotNull final Iterable source) { - final JavaCompiler compiler = getCompiler(); + final JavaCompiler compiler = getCompiler(); - final CompileJavaFileManager fileManager = getFileManager(); - final CompileListener listener = getListener(); - final CompileClassLoader loader = getLoader(); + final CompileJavaFileManager fileManager = getFileManager(); + final CompileListener listener = getListener(); + final CompileClassLoader loader = getLoader(); - try { + try { - final CompilationTask task = compiler.getTask(null, fileManager, listener, options, null, source); - task.call(); + final CompilationTask task = compiler.getTask(null, fileManager, listener, options, null, source); + task.call(); - final Diagnostic[] diagnostics = listener.getDiagnostics(); + final Diagnostic[] diagnostics = listener.getDiagnostics(); - if (isShowDiagnostic() && diagnostics.length > 0) { + if (isShowDiagnostic() && diagnostics.length > 0) { - LOGGER.warning("errors:"); + LOGGER.warning("errors:"); - for (final Diagnostic diagnostic : diagnostics) { - LOGGER.warning(String.valueOf(diagnostic)); - } - } + for (final Diagnostic diagnostic : diagnostics) { + LOGGER.warning(String.valueOf(diagnostic)); + } + } - final Array> result = ArrayFactory.newArray(Class.class); - final String[] classNames = fileManager.getClassNames(); + final Array> result = ArrayFactory.newArray(Class.class); + final String[] classNames = fileManager.getClassNames(); - for (final String className : classNames) { - try { - final Class cs = Class.forName(className, false, loader); - result.add(cs); - } catch (final ClassNotFoundException e) { - LOGGER.warning(e); - } - } + for (final String className : classNames) { + try { + final Class cs = Class.forName(className, false, loader); + result.add(cs); + } catch (final ClassNotFoundException e) { + LOGGER.warning(e); + } + } - return result.toArray(new Class[result.size()]); + return result.toArray(new Class[result.size()]); - } finally { - listener.clear(); - fileManager.clear(); - } + } finally { + listener.clear(); + fileManager.clear(); } - - /** - * Compile classes from a directory. - * - * @param container the container. - * @param directory the directory. - */ - private void compileDirectory(@NotNull final Array> container, @NotNull final File directory) { - - final File[] files = directory.listFiles(); - if (files == null || files.length < 1) return; - - for (final File file : files) { - if (file.isDirectory()) { - compileDirectory(container, file); - } else if (file.getName().endsWith(Compiler.SOURCE_EXTENSION)) { - container.addAll(compile(file)); - } - } + } + + /** + * Compile classes from a directory. + * + * @param container the container. + * @param directory the directory. + */ + private void compileDirectory(@NotNull final Array> container, @NotNull final File directory) { + + final File[] files = directory.listFiles(); + if (files == null || files.length < 1) { + return; } - @Override - public @NotNull Class[] compileDirectory(@NotNull final File... files) { - - final Array> container = ArrayFactory.newArray(Class.class); - - for (final File directory : files) { - - if (!directory.exists() || !directory.isDirectory()) { - continue; - } - - compileDirectory(container, directory); - } - - return container.toArray(new Class[container.size()]); + for (final File file : files) { + if (file.isDirectory()) { + compileDirectory(container, file); + } else if (file + .getName() + .endsWith(Compiler.SOURCE_EXTENSION)) { + container.addAll(compile(file)); + } } + } - /** - * Compile classes from a directory. - * - * @param container the container. - * @param directory the directory. - */ - private void compileDirectory(@NotNull final Array> container, @NotNull final Path directory) { - try (DirectoryStream stream = Files.newDirectoryStream(directory)) { - - for (final Path path : stream) { - if (Files.isDirectory(path)) { - compileDirectory(container, path); - } else if (path.toString().endsWith(Compiler.SOURCE_EXTENSION)) { - container.addAll(compile(path)); - } - } - - } catch (IOException e) { - LOGGER.warning(e); - } - } + @Override + public @NotNull Class[] compileDirectory(@NotNull final File... files) { - @Override - public @NotNull Class[] compileDirectory(@NotNull Path... paths) { + final Array> container = ArrayFactory.newArray(Class.class); - final Array> container = ArrayFactory.newArray(Class.class); + for (final File directory : files) { - for (final Path path : paths) { + if (!directory.exists() || !directory.isDirectory()) { + continue; + } - if (!Files.exists(path) || !Files.isDirectory(path)) { - continue; - } + compileDirectory(container, directory); + } - compileDirectory(container, path); + return container.toArray(new Class[container.size()]); + } + + /** + * Compile classes from a directory. + * + * @param container the container. + * @param directory the directory. + */ + private void compileDirectory(@NotNull final Array> container, @NotNull final Path directory) { + try (DirectoryStream stream = Files.newDirectoryStream(directory)) { + + for (final Path path : stream) { + if (Files.isDirectory(path)) { + compileDirectory(container, path); + } else if (path + .toString() + .endsWith(Compiler.SOURCE_EXTENSION)) { + container.addAll(compile(path)); } + } - return container.toArray(new Class[container.size()]); - + } catch (IOException e) { + LOGGER.warning(e); } + } - /** - * Gets compiler. - * - * @return the java compiler. - */ - protected @NotNull JavaCompiler getCompiler() { - return compiler; - } + @Override + public @NotNull Class[] compileDirectory(@NotNull Path... paths) { - /** - * Gets file manager. - * - * @return the java files manager. - */ - protected @NotNull CompileJavaFileManager getFileManager() { - return fileManager; - } + final Array> container = ArrayFactory.newArray(Class.class); - /** - * Gets listener. - * - * @return the compile listener. - */ - protected @NotNull CompileListener getListener() { - return listener; - } + for (final Path path : paths) { - /** - * Gets loader. - * - * @return the class loader. - */ - protected @NotNull CompileClassLoader getLoader() { - return loader; - } + if (!Files.exists(path) || !Files.isDirectory(path)) { + continue; + } - /** - * @return true id need o show reports. - */ - private boolean isShowDiagnostic() { - return showDiagnostic; + compileDirectory(container, path); } + + return container.toArray(new Class[container.size()]); + + } + + /** + * Gets compiler. + * + * @return the java compiler. + */ + protected @NotNull JavaCompiler getCompiler() { + return compiler; + } + + /** + * Gets file manager. + * + * @return the java files manager. + */ + protected @NotNull CompileJavaFileManager getFileManager() { + return fileManager; + } + + /** + * Gets listener. + * + * @return the compile listener. + */ + protected @NotNull CompileListener getListener() { + return listener; + } + + /** + * Gets loader. + * + * @return the class loader. + */ + protected @NotNull CompileClassLoader getLoader() { + return loader; + } + + /** + * @return true id need o show reports. + */ + private boolean isShowDiagnostic() { + return showDiagnostic; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java index c7302b77..bd7f1cb9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java @@ -16,53 +16,53 @@ */ public class JavaFileSource extends SimpleJavaFileObject { - protected JavaFileSource(@NotNull final File file) { - super(file.toURI(), Kind.SOURCE); - } - - protected JavaFileSource(@NotNull final Path path) { - super(path.toUri(), Kind.SOURCE); - } + protected JavaFileSource(@NotNull final File file) { + super(file.toURI(), Kind.SOURCE); + } - protected JavaFileSource(@NotNull final URI uri) { - super(uri, Kind.SOURCE); - } + protected JavaFileSource(@NotNull final Path path) { + super(path.toUri(), Kind.SOURCE); + } - @Override - public boolean equals(final Object obj) { + protected JavaFileSource(@NotNull final URI uri) { + super(uri, Kind.SOURCE); + } - if (this == obj) { - return true; - } else if (obj == null) { - return false; - } else if (getClass() != obj.getClass()) { - return false; - } + @Override + public boolean equals(final Object obj) { - final JavaFileSource other = (JavaFileSource) obj; + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } - if (uri == null) { - if (other.uri != null) { - return false; - } - } else if (!uri.equals(other.uri)) { - return false; - } + final JavaFileSource other = (JavaFileSource) obj; - return true; + if (uri == null) { + if (other.uri != null) { + return false; + } + } else if (!uri.equals(other.uri)) { + return false; } - @Override - public CharSequence getCharContent(final boolean ignoreEncodingErrors) throws IOException { - final Path path = Paths.get(uri); - return new String(Files.readAllBytes(path), "UTF-8"); - } + return true; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (uri == null ? 0 : uri.hashCode()); - return result; - } + @Override + public CharSequence getCharContent(final boolean ignoreEncodingErrors) throws IOException { + final Path path = Paths.get(uri); + return new String(Files.readAllBytes(path), "UTF-8"); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (uri == null ? 0 : uri.hashCode()); + return result; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/GroupThreadFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/GroupThreadFactory.java index b635eb81..b44cc71b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/GroupThreadFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/GroupThreadFactory.java @@ -1,61 +1,57 @@ package javasabr.rlib.common.concurrent; import java.util.concurrent.ThreadFactory; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; -import org.jetbrains.annotations.NotNull; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; +import org.jspecify.annotations.NullMarked; /** - * The implementation of the {@link ThreadFactory} to create threads in the same thread - * group. + * The implementation of the {@link ThreadFactory} to create threads in the same thread group. * * @author JavaSaBr */ +@NullMarked public class GroupThreadFactory implements ThreadFactory { - public interface ThreadConstructor { - - @NotNull Thread create(@NotNull ThreadGroup group, @NotNull Runnable runnable, @NotNull String name); - } - - private final AtomicInteger ordinal; - private final String name; - private final ThreadGroup group; - private final ThreadConstructor constructor; - - private final int priority; - private final boolean daemon; - - public GroupThreadFactory(@NotNull String name) { - this(name, Thread::new, Thread.NORM_PRIORITY); - } - - public GroupThreadFactory(@NotNull String name, int priority) { - this(name, Thread::new, priority); - } - - public GroupThreadFactory(@NotNull String name, @NotNull ThreadConstructor constructor, int priority) { - this(name, constructor, priority, false); - } - - public GroupThreadFactory( - @NotNull String name, - @NotNull ThreadConstructor constructor, - int priority, - boolean daemon - ) { - this.constructor = constructor; - this.priority = priority; - this.name = name; - this.group = new ThreadGroup(name); - this.ordinal = new AtomicInteger(); - this.daemon = daemon; - } - - @Override - public @NotNull Thread newThread(@NotNull Runnable runnable) { - var thread = constructor.create(group, runnable, name + "-" + ordinal.incrementAndGet()); - thread.setPriority(priority); - thread.setDaemon(daemon); - return thread; - } + @NullMarked + public interface ThreadConstructor { + + Thread create(ThreadGroup group, Runnable runnable, String name); + } + + private final ReusableAtomicInteger ordinal; + private final String name; + private final ThreadGroup group; + private final ThreadConstructor constructor; + + private final int priority; + private final boolean daemon; + + public GroupThreadFactory(String name) { + this(name, Thread::new, Thread.NORM_PRIORITY); + } + + public GroupThreadFactory(String name, int priority) { + this(name, Thread::new, priority); + } + + public GroupThreadFactory(String name, ThreadConstructor constructor, int priority) { + this(name, constructor, priority, false); + } + + public GroupThreadFactory(String name, ThreadConstructor constructor, int priority, boolean daemon) { + this.constructor = constructor; + this.priority = priority; + this.name = name; + this.group = new ThreadGroup(name); + this.ordinal = new ReusableAtomicInteger(); + this.daemon = daemon; + } + + @Override + public Thread newThread(Runnable runnable) { + var thread = constructor.create(group, runnable, name + "-" + ordinal.incrementAndGet()); + thread.setPriority(priority); + thread.setDaemon(daemon); + return thread; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicInteger.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicInteger.java deleted file mode 100644 index 88e36e1d..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicInteger.java +++ /dev/null @@ -1,48 +0,0 @@ -package javasabr.rlib.common.concurrent.atomic; - -import javasabr.rlib.common.util.pools.Reusable; - -/** - * The atomic integer with additional methods. - * - * @author JavaSaBr - */ -public final class AtomicInteger extends java.util.concurrent.atomic.AtomicInteger implements Reusable { - - private static final long serialVersionUID = -624766818867950719L; - - /** - * Instantiates a new Atomic integer. - */ - public AtomicInteger() { - } - - /** - * Instantiates a new Atomic integer. - * - * @param initialValue the initial value - */ - public AtomicInteger(final int initialValue) { - super(initialValue); - } - - /** - * Atomically decrements by delta the current value. - * - * @param delta the delta. - * @return the result value. - */ - public final int subAndGet(final int delta) { - - int current; - int next; - - do { - current = get(); - next = current - delta; - } - while (!compareAndSet(current, next)); - - return next; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicReference.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicReference.java deleted file mode 100644 index 75da8677..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/AtomicReference.java +++ /dev/null @@ -1,29 +0,0 @@ -package javasabr.rlib.common.concurrent.atomic; - -import javasabr.rlib.common.util.pools.Reusable; - -/** - * The atomic reference with additional methods. - * - * @param the type parameter - * @author JavaSaBr - */ -public final class AtomicReference extends java.util.concurrent.atomic.AtomicReference implements Reusable { - - private static final long serialVersionUID = -4058945159519762615L; - - /** - * Instantiates a new Atomic reference. - */ - public AtomicReference() { - } - - /** - * Instantiates a new Atomic reference. - * - * @param initialValue the initial value - */ - public AtomicReference(final V initialValue) { - super(initialValue); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicInteger.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicInteger.java new file mode 100644 index 00000000..fa948929 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicInteger.java @@ -0,0 +1,41 @@ +package javasabr.rlib.common.concurrent.atomic; + +import java.io.Serial; +import java.util.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.util.pools.Reusable; + +/** + * The atomic integer with additional methods. + * + * @author JavaSaBr + */ +public final class ReusableAtomicInteger extends AtomicInteger implements Reusable { + + @Serial + private static final long serialVersionUID = -624766818867950719L; + + public ReusableAtomicInteger() {} + + public ReusableAtomicInteger(int initialValue) { + super(initialValue); + } + + /** + * Atomically decrements by delta the current value. + * + * @param delta the delta. + * @return the result value. + */ + public int subAndGet(int delta) { + + int current; + int next; + + do { + current = get(); + next = current - delta; + } while (!compareAndSet(current, next)); + + return next; + } +} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicReference.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicReference.java new file mode 100644 index 00000000..b3b84497 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/atomic/ReusableAtomicReference.java @@ -0,0 +1,26 @@ +package javasabr.rlib.common.concurrent.atomic; + +import java.io.Serial; +import java.util.concurrent.atomic.AtomicReference; +import javasabr.rlib.common.util.pools.Reusable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +/** + * The atomic reference with additional methods. + * + * @param the type parameter + * @author JavaSaBr + */ +@NullMarked +public final class ReusableAtomicReference extends AtomicReference implements Reusable { + + @Serial + private static final long serialVersionUID = -4058945159519762615L; + + public ReusableAtomicReference() {} + + public ReusableAtomicReference(@Nullable V initialValue) { + super(initialValue); + } +} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockDetector.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockDetector.java index b8773668..2538714a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockDetector.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockDetector.java @@ -12,114 +12,116 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of a deadlock detector. * * @author JavaSaBr */ +@NullMarked public class DeadLockDetector implements Runnable { - private static final Logger LOGGER = LoggerManager.getLogger(DeadLockDetector.class); + private static final Logger LOGGER = LoggerManager.getLogger(DeadLockDetector.class); - /** - * The list of listeners. - */ - private final @Getter @NotNull ConcurrentArray listeners; + /** + * The list of listeners. + */ + @Getter + private final ConcurrentArray listeners; - /** - * The bean with information about threads. - */ - private final @NotNull ThreadMXBean mxThread; + /** + * The bean with information about threads. + */ + private final ThreadMXBean mxThread; - /** - * The scheduler. - */ - private final @NotNull ScheduledExecutorService executorService; + /** + * The scheduler. + */ + private final ScheduledExecutorService executorService; - /** - * The reference to a task. - */ - private volatile @Getter @Nullable ScheduledFuture schedule; + /** + * The reference to a task. + */ + @Getter + private volatile @Nullable ScheduledFuture schedule; - /** - * The checking interval. - */ - private final int interval; + /** + * The checking interval. + */ + private final int interval; - public DeadLockDetector(int interval) { + public DeadLockDetector(int interval) { - if (interval < 1) { - throw new IllegalArgumentException("negative interval."); - } - - this.listeners = ArrayFactory.newConcurrentReentrantRWLockArray(DeadLockListener.class); - this.mxThread = ManagementFactory.getThreadMXBean(); - this.executorService = Executors.newSingleThreadScheduledExecutor(); - this.interval = interval; + if (interval < 1) { + throw new IllegalArgumentException("negative interval."); } - /** - * Add a new listener. - * - * @param listener the new listener. - */ - public void addListener(@NotNull DeadLockListener listener) { - listeners.runInWriteLock(listener, Array::add); - } + this.listeners = ArrayFactory.newConcurrentReentrantRWLockArray(DeadLockListener.class); + this.mxThread = ManagementFactory.getThreadMXBean(); + this.executorService = Executors.newSingleThreadScheduledExecutor(); + this.interval = interval; + } - @Override - public void run() { + /** + * Add a new listener. + * + * @param listener the new listener. + */ + public void addListener(DeadLockListener listener) { + listeners.runInWriteLock(listener, Array::add); + } - var threadIds = mxThread.findDeadlockedThreads(); + @Override + public void run() { - if (threadIds.length < 1) { - return; - } + var threadIds = mxThread.findDeadlockedThreads(); - var listeners = getListeners(); + if (threadIds.length < 1) { + return; + } - for (var id : threadIds) { + var listeners = getListeners(); - var info = mxThread.getThreadInfo(id); + for (var id : threadIds) { - if (listeners.isEmpty()) { - continue; - } + var info = mxThread.getThreadInfo(id); - listeners.runInReadLock(info, (list, inf) -> list.forEachR(inf, DeadLockListener::onDetected)); + if (listeners.isEmpty()) { + continue; + } - LOGGER.warning("DeadLock detected! : " + info); - } - } + listeners.runInReadLock(info, (list, inf) -> list.forEachR(inf, DeadLockListener::onDetected)); - /** - * Start. - */ - public synchronized void start() { + LOGGER.warning("DeadLock detected! : " + info); + } + } - if (schedule != null) { - return; - } + /** + * Start. + */ + public synchronized void start() { - schedule = executorService.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS); + if (schedule != null) { + return; } - /** - * Stop. - */ - public synchronized void stop() { + schedule = executorService.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS); + } - var schedule = getSchedule(); + /** + * Stop. + */ + public synchronized void stop() { - if (schedule == null) { - return; - } + var schedule = getSchedule(); + if (schedule == null) { + return; + } - schedule.cancel(false); + schedule.cancel(false); - this.schedule = null; - } + this.schedule = null; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockListener.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockListener.java index 2d86bd6c..e3910eed 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockListener.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/deadlock/DeadLockListener.java @@ -1,19 +1,20 @@ package javasabr.rlib.common.concurrent.deadlock; import java.lang.management.ThreadInfo; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a deadlock listener. * * @author JavaSaBr */ +@NullMarked public interface DeadLockListener { - /** - * Notify about deadlock detecting. - * - * @param info the information about thread. - */ - void onDetected(@NotNull ThreadInfo info); + /** + * Notify about deadlock detecting. + * + * @param info the information about thread. + */ + void onDetected(ThreadInfo info); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/PeriodicTaskExecutor.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/PeriodicTaskExecutor.java index e5ed860b..82e19bdd 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/PeriodicTaskExecutor.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/PeriodicTaskExecutor.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.concurrent.executor; import javasabr.rlib.common.concurrent.task.PeriodicTask; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a periodic task executor. @@ -10,19 +10,20 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface PeriodicTaskExecutor, L> { - /** - * Add a periodic task to execute. - * - * @param task the periodic task. - */ - void addTask(@NotNull T task); + /** + * Add a periodic task to execute. + * + * @param task the periodic task. + */ + void addTask(T task); - /** - * Remove a periodic task from executing. - * - * @param task the periodic task. - */ - void removeTask(@NotNull T task); + /** + * Remove a periodic task from executing. + * + * @param task the periodic task. + */ + void removeTask(T task); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java index cc0c95a2..b9a16a93 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java @@ -4,6 +4,7 @@ import javasabr.rlib.common.concurrent.task.CallableTask; import javasabr.rlib.common.concurrent.task.SimpleTask; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a task executor. @@ -11,22 +12,22 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface TaskExecutor { - /** - * Execute a simple task. - * - * @param task the simple task. - */ - void execute(@NotNull SimpleTask task); + /** + * Execute a simple task. + * + * @param task the simple task. + */ + void execute(SimpleTask task); - /** - * Submit a callable task. - * - * @param the type parameter - * @param task the callable task. - * @return the reference to the task. - */ - @NotNull - Future submit(@NotNull CallableTask task); + /** + * Submit a callable task. + * + * @param the type parameter + * @param task the callable task. + * @return the reference to the task. + */ + Future submit(CallableTask task); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java index 29a29cda..7351a587 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java @@ -19,266 +19,260 @@ import javasabr.rlib.logger.api.LoggerManager; import lombok.AccessLevel; import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of single thread periodic executor. * * @author JavaSaBr */ +@NullMarked @Getter(AccessLevel.PROTECTED) public class SingleThreadPeriodicTaskExecutor, L> implements PeriodicTaskExecutor, Runnable, Lockable { - protected static final Logger LOGGER = LoggerManager.getLogger(SingleThreadPeriodicTaskExecutor.class); - - /** - * The list of waiting tasks. - */ - private final @NotNull Array waitTasks; - - /** - * The list of executing tasks. - */ - private final @NotNull Array executeTasks; - - /** - * The list of finished tasks. - */ - private final @NotNull Array finishedTasks; - - /** - * The executor thread. - */ - private final @NotNull Thread thread; - - /** - * The thread local objects. - */ - private final @NotNull L localObjects; - - /** - * The finishing function. - */ - private final @NotNull Consumer finishFunction = task -> task.onFinish(getLocalObjects()); - - /** - * The waiting flag. - */ - private final @NotNull AtomicBoolean wait; - - /** - * The synchronizator. - */ - private final @NotNull Lock lock; - - /** - * The update interval. - */ - private final int interval; - - public SingleThreadPeriodicTaskExecutor( - @NotNull Class threadClass, - int priority, - int interval, - @NotNull String name, - @NotNull Class taskClass, - @Nullable L localObjects - ) { - this.waitTasks = ArrayFactory.newArray(taskClass); - this.executeTasks = ArrayFactory.newArray(taskClass); - this.finishedTasks = ArrayFactory.newArray(taskClass); - this.wait = new AtomicBoolean(); - this.lock = LockFactory.newAtomicLock(); - this.interval = interval; - - Constructor constructor = - ClassUtils.getConstructor(threadClass, Runnable.class, String.class); - - this.thread = ClassUtils.newInstance(constructor, this, name); - this.thread.setPriority(priority); - this.thread.setDaemon(true); - this.localObjects = check(localObjects, thread); - this.thread.start(); - } - - @Override - public void addTask(@NotNull T task) { - lock(); - try { - - waitTasks.add(task); - - if (wait.get()) { - synchronized (wait) { - if (wait.compareAndSet(true, false)) { - ConcurrentUtils.notifyAllInSynchronize(wait); - } - } - } - - } finally { - unlock(); + protected static final Logger LOGGER = LoggerManager.getLogger(SingleThreadPeriodicTaskExecutor.class); + + /** + * The list of waiting tasks. + */ + private final Array waitTasks; + + /** + * The list of executing tasks. + */ + private final Array executeTasks; + + /** + * The list of finished tasks. + */ + private final Array finishedTasks; + + /** + * The executor thread. + */ + private final Thread thread; + + /** + * The thread local objects. + */ + private final L localObjects; + + /** + * The finishing function. + */ + private final Consumer finishFunction = task -> task.onFinish(getLocalObjects()); + + /** + * The waiting flag. + */ + private final AtomicBoolean wait; + + /** + * The synchronizator. + */ + private final Lock lock; + + /** + * The update interval. + */ + private final int interval; + + public SingleThreadPeriodicTaskExecutor( + Class threadClass, + int priority, + int interval, + String name, + Class taskClass, + @Nullable L localObjects) { + this.waitTasks = ArrayFactory.newArray(taskClass); + this.executeTasks = ArrayFactory.newArray(taskClass); + this.finishedTasks = ArrayFactory.newArray(taskClass); + this.wait = new AtomicBoolean(); + this.lock = LockFactory.newAtomicLock(); + this.interval = interval; + + Constructor constructor = ClassUtils.getConstructor(threadClass, Runnable.class, String.class); + + this.thread = ClassUtils.newInstance(constructor, this, name); + this.thread.setPriority(priority); + this.thread.setDaemon(true); + this.localObjects = check(localObjects, thread); + this.thread.start(); + } + + @Override + public void addTask(T task) { + lock(); + try { + + waitTasks.add(task); + + if (wait.get()) { + synchronized (wait) { + if (wait.compareAndSet(true, false)) { + ConcurrentUtils.notifyAllInSynchronize(wait); + } } - } + } - protected @NotNull L check(@Nullable L localObjects, @NotNull Thread thread) { - return requireNonNull(localObjects); + } finally { + unlock(); } - - /** - * Execute tasks. - * - * @param executeTasks the execute tasks. - * @param finishedTasks the finished tasks. - * @param local the thread local objects. - * @param startExecuteTime the start time. - */ - protected void executeImpl( - @NotNull Array executeTasks, - @NotNull Array finishedTasks, - @NotNull L local, - long startExecuteTime - ) { - for (var task : executeTasks.array()) { - - if (task == null) { - break; - } - - if (task.call(local, startExecuteTime) == Boolean.TRUE) { - finishedTasks.add(task); - } - } + } + + protected L check(@Nullable L localObjects, Thread thread) { + return requireNonNull(localObjects); + } + + /** + * Execute tasks. + * + * @param executeTasks the execute tasks. + * @param finishedTasks the finished tasks. + * @param local the thread local objects. + * @param startExecuteTime the start time. + */ + protected void executeImpl(Array executeTasks, Array finishedTasks, L local, long startExecuteTime) { + for (var task : executeTasks.array()) { + + if (task == null) { + break; + } + + if (task.call(local, startExecuteTime) == Boolean.TRUE) { + finishedTasks.add(task); + } } - - /** - * @return the update interval. - */ - public int getInterval() { - return interval; + } + + /** + * @return the update interval. + */ + public int getInterval() { + return interval; + } + + @Override + public void lock() { + lock.lock(); + } + + /** + * Handle tasks after executing. + * + * @param executedTasks the list of executed tasks. + * @param local the thread local objects. + * @param startExecuteTime the start executing time. + */ + protected void postExecute(Array executedTasks, L local, long startExecuteTime) { + } + + /** + * Handle tasks before executing. + * + * @param executeTasks the list of execute tasks. + * @param local the thread local objects. + * @param startExecuteTime the start executing time. + */ + protected void preExecute(Array executeTasks, L local, long startExecuteTime) { + } + + @Override + public void removeTask(T task) { + lock(); + try { + waitTasks.fastRemove(task); + } finally { + unlock(); } + } - @Override - public void lock() { - lock.lock(); - } + @Override + public void run() { - /** - * Handle tasks after executing. - * - * @param executedTasks the list of executed tasks. - * @param local the thread local objects. - * @param startExecuteTime the start executing time. - */ - protected void postExecute(@NotNull Array executedTasks, @NotNull L local, long startExecuteTime) { - } + var waitTasks = getWaitTasks(); + var executeTasks = getExecuteTasks(); + var finishedTasks = getFinishedTasks(); - /** - * Handle tasks before executing. - * - * @param executeTasks the list of execute tasks. - * @param local the thread local objects. - * @param startExecuteTime the start executing time. - */ - protected void preExecute(@NotNull Array executeTasks, @NotNull L local, long startExecuteTime) { - } + var local = getLocalObjects(); + var interval = getInterval(); - @Override - public void removeTask(@NotNull final T task) { - lock(); - try { - waitTasks.fastRemove(task); - } finally { - unlock(); - } - } + while (true) { - @Override - public void run() { + executeTasks.clear(); + finishedTasks.clear(); - var waitTasks = getWaitTasks(); - var executeTasks = getExecuteTasks(); - var finishedTasks = getFinishedTasks(); + lock(); + try { - var local = getLocalObjects(); - var interval = getInterval(); - - while (true) { - - executeTasks.clear(); - finishedTasks.clear(); - - lock(); - try { - - if (waitTasks.isEmpty()) { - wait.getAndSet(true); - } else { - executeTasks.addAll(waitTasks); - } - - } finally { - unlock(); - } - - if (wait.get()) { - synchronized (wait) { - if (wait.get()) { - ConcurrentUtils.waitInSynchronize(wait); - } - } - } - - if (executeTasks.isEmpty()) { - continue; - } - - var startExecuteTime = System.currentTimeMillis(); - - preExecute(executeTasks, local, startExecuteTime); - try { - executeImpl(executeTasks, finishedTasks, local, startExecuteTime); - } catch (Exception exc) { - LOGGER.warning(exc); - } finally { - postExecute(executeTasks, local, startExecuteTime); - } + if (waitTasks.isEmpty()) { + wait.getAndSet(true); + } else { + executeTasks.addAll(waitTasks); + } - try { + } finally { + unlock(); + } - if (!finishedTasks.isEmpty()) { - lock(); - try { - waitTasks.removeAll(finishedTasks); - } finally { - unlock(); - } + if (wait.get()) { + synchronized (wait) { + if (wait.get()) { + ConcurrentUtils.waitInSynchronize(wait); + } + } + } + + if (executeTasks.isEmpty()) { + continue; + } + + var startExecuteTime = System.currentTimeMillis(); + + preExecute(executeTasks, local, startExecuteTime); + try { + executeImpl(executeTasks, finishedTasks, local, startExecuteTime); + } catch (Exception exc) { + LOGGER.warning(exc); + } finally { + postExecute(executeTasks, local, startExecuteTime); + } + + try { + + if (!finishedTasks.isEmpty()) { + lock(); + try { + waitTasks.removeAll(finishedTasks); + } finally { + unlock(); + } - finishedTasks.forEach(finishFunction); - } + finishedTasks.forEach(finishFunction); + } - } catch (Exception exc) { - LOGGER.warning(exc); - } + } catch (Exception exc) { + LOGGER.warning(exc); + } - if (interval < 1) { - continue; - } + if (interval < 1) { + continue; + } - var result = interval - (int) (System.currentTimeMillis() - startExecuteTime); + var result = interval - (int) (System.currentTimeMillis() - startExecuteTime); - if (result < 1) { - continue; - } + if (result < 1) { + continue; + } - ThreadUtils.sleep(result); - } + ThreadUtils.sleep(result); } + } - @Override - public void unlock() { - lock.unlock(); - } + @Override + public void unlock() { + lock.unlock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadTaskExecutor.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadTaskExecutor.java index 15927ad9..d52a7161 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadTaskExecutor.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/SingleThreadTaskExecutor.java @@ -17,8 +17,8 @@ import javasabr.rlib.common.util.array.ArrayFactory; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of single thread task executor. @@ -26,203 +26,194 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class SingleThreadTaskExecutor implements TaskExecutor, Runnable, Lockable { - protected static final Logger LOGGER = LoggerManager.getLogger(SingleThreadTaskExecutor.class); - - /** - * The list of waiting tasks. - */ - @NotNull - private final Array> waitTasks; - - /** - * The list of executing task. - */ - @NotNull - private final Array> executeTasks; - - /** - * The executor thread. - */ - @NotNull - private final Thread thread; - - /** - * The thread local objects. - */ - @NotNull - private final L localObjects; - - /** - * The waiting flag. - */ - @NotNull - private final AtomicBoolean wait; - - /** - * The synchronizer. - */ - @NotNull - private final Lock lock; - - public SingleThreadTaskExecutor( - @NotNull Class threadClass, - int priority, - @NotNull String name, - @Nullable L local - ) { - this.waitTasks = ArrayFactory.newArray(CallableTask.class); - this.executeTasks = ArrayFactory.newArray(CallableTask.class); - this.wait = new AtomicBoolean(); - this.lock = LockFactory.newAtomicLock(); - - Constructor constructor = - ClassUtils.tryGetConstructor(threadClass, Runnable.class, String.class); - - this.thread = ClassUtils.newInstance(requireNonNull(constructor), this, name); - this.thread.setPriority(priority); - this.thread.setDaemon(true); - this.localObjects = check(local, thread); - this.thread.start(); - } - - /** - * Check l. - * - * @param local the local - * @param thread the thread - * @return the l - */ - @NotNull - protected L check(@Nullable final L local, @NotNull final Thread thread) { - return requireNonNull(local); - } - - @Override - public void execute(@NotNull final SimpleTask task) { - lock(); - try { - - waitTasks.add(task); - - if (wait.get()) { - synchronized (wait) { - if (wait.compareAndSet(true, false)) { - ConcurrentUtils.notifyAllInSynchronize(wait); - } - } - } - - } finally { - unlock(); + protected static final Logger LOGGER = LoggerManager.getLogger(SingleThreadTaskExecutor.class); + + /** + * The list of waiting tasks. + */ + private final Array> waitTasks; + + /** + * The list of executing task. + */ + private final Array> executeTasks; + + /** + * The executor thread. + */ + private final Thread thread; + + /** + * The thread local objects. + */ + private final L localObjects; + + /** + * The waiting flag. + */ + private final AtomicBoolean wait; + + /** + * The synchronizer. + */ + private final Lock lock; + + public SingleThreadTaskExecutor( + Class threadClass, + int priority, + String name, + @Nullable L local) { + this.waitTasks = ArrayFactory.newArray(CallableTask.class); + this.executeTasks = ArrayFactory.newArray(CallableTask.class); + this.wait = new AtomicBoolean(); + this.lock = LockFactory.newAtomicLock(); + + Constructor constructor = ClassUtils.tryGetConstructor(threadClass, Runnable.class, String.class); + + this.thread = ClassUtils.newInstance(requireNonNull(constructor), this, name); + this.thread.setPriority(priority); + this.thread.setDaemon(true); + this.localObjects = check(local, thread); + this.thread.start(); + } + + /** + * Check l. + * + * @param local the local + * @param thread the thread + * @return the l + */ + protected L check(@Nullable L local, Thread thread) { + return requireNonNull(local); + } + + @Override + public void execute(final SimpleTask task) { + lock(); + try { + + waitTasks.add(task); + + if (wait.get()) { + synchronized (wait) { + if (wait.compareAndSet(true, false)) { + ConcurrentUtils.notifyAllInSynchronize(wait); + } } - } + } - /** - * Gets execute tasks. - * - * @return the list of executing task. - */ - @NotNull - protected Array> getExecuteTasks() { - return executeTasks; + } finally { + unlock(); } + } + + /** + * Gets execute tasks. + * + * @return the list of executing task. + */ + protected Array> getExecuteTasks() { + return executeTasks; + } + + /** + * Gets local objects. + * + * @return the thread local objects. + */ + protected L getLocalObjects() { + return localObjects; + } + + /** + * Gets wait. + * + * @return the waiting flag. + */ + public AtomicBoolean getWait() { + return wait; + } + + /** + * Gets wait tasks. + * + * @return the list of waiting tasks. + */ + protected Array> getWaitTasks() { + return waitTasks; + } + + @Override + public void lock() { + lock.lock(); + } + + @Override + public void run() { + + Array> waitTasks = getWaitTasks(); + Array> executeTasks = getExecuteTasks(); + + L local = getLocalObjects(); + + while (true) { + + executeTasks.clear(); + + lock(); + try { + + if (waitTasks.isEmpty()) { + wait.getAndSet(true); + } else { + executeTasks.addAll(waitTasks); + waitTasks.clear(); + } - /** - * Gets local objects. - * - * @return the thread local objects. - */ - @NotNull - protected L getLocalObjects() { - return localObjects; - } - - /** - * Gets wait. - * - * @return the waiting flag. - */ - @NotNull - public AtomicBoolean getWait() { - return wait; - } - - /** - * Gets wait tasks. - * - * @return the list of waiting tasks. - */ - @NotNull - protected Array> getWaitTasks() { - return waitTasks; - } - - @Override - public void lock() { - lock.lock(); - } - - @Override - public void run() { - - final Array> waitTasks = getWaitTasks(); - final Array> executeTasks = getExecuteTasks(); - - final L local = getLocalObjects(); - - while (true) { - - executeTasks.clear(); - - lock(); - try { - - if (waitTasks.isEmpty()) { - wait.getAndSet(true); - } else { - executeTasks.addAll(waitTasks); - waitTasks.clear(); - } - - } finally { - unlock(); - } - - if (wait.get()) { - synchronized (wait) { - if (wait.get()) { - ConcurrentUtils.waitInSynchronize(wait); - } - } - } + } finally { + unlock(); + } - if (executeTasks.isEmpty()) continue; + if (wait.get()) { + synchronized (wait) { + if (wait.get()) { + ConcurrentUtils.waitInSynchronize(wait); + } + } + } - try { + if (executeTasks.isEmpty()) { + continue; + } - final long currentTime = System.currentTimeMillis(); + try { - for (final CallableTask task : executeTasks.array()) { - if (task == null) break; - task.call(local, currentTime); - } + long currentTime = System.currentTimeMillis(); - } catch (final Exception e) { - LOGGER.warning(e); - } + for (CallableTask task : executeTasks.array()) { + if (task == null) { + break; + } + task.call(local, currentTime); } - } - @NotNull - @Override - public Future submit(@NotNull final CallableTask task) { - throw new RuntimeException("not implemented."); + } catch (final Exception e) { + LOGGER.warning(e); + } } + } - @Override - public void unlock() { - lock.unlock(); - } + @Override + public Future submit(CallableTask task) { + throw new RuntimeException("not implemented."); + } + + @Override + public void unlock() { + lock.unlock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/ThreadPoolTaskExecutor.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/ThreadPoolTaskExecutor.java index bad49bf7..bdc6555b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/ThreadPoolTaskExecutor.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/impl/ThreadPoolTaskExecutor.java @@ -17,7 +17,7 @@ import javasabr.rlib.common.util.linkedlist.LinkedListFactory; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * Реализация многопоточного пакетного исполнителя задач. Использовать только в случае необходимости выполнять большое @@ -28,193 +28,193 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class ThreadPoolTaskExecutor implements TaskExecutor, Runnable, Lockable { - /** - * The constant LOGGER. - */ - protected static final Logger LOGGER = LoggerManager.getLogger(ThreadPoolTaskExecutor.class); - - /** - * The list of waiting tasks. - */ - @NotNull - private final LinkedList> waitTasks; - - /** - * The list of working threads. - */ - @NotNull - private final Array threads; - - /** - * The waiting flag. - */ - @NotNull - private final AtomicBoolean wait; - - /** - * The synchronizer. - */ - @NotNull - private final Lock lock; - - /** - * The count of executing tasks per thread. - */ - private final int packetSize; - - /** - * Instantiates a new Thread pool task executor. - * - * @param threadFactory the thread factory - * @param poolSize the pool size - * @param packetSize the packet size - */ - public ThreadPoolTaskExecutor(@NotNull final GroupThreadFactory threadFactory, final int poolSize, final int packetSize) { - this.waitTasks = LinkedListFactory.newLinkedList(CallableTask.class); - this.wait = new AtomicBoolean(); - this.lock = LockFactory.newAtomicLock(); - this.threads = ArrayFactory.newArray(Thread.class); - this.packetSize = packetSize; - - for (int i = 0; i < poolSize; i++) { - - final Thread thread = threadFactory.newThread(this); - thread.setDaemon(true); - thread.start(); - - threads.add(thread); - } + /** + * The constant LOGGER. + */ + protected static final Logger LOGGER = LoggerManager.getLogger(ThreadPoolTaskExecutor.class); + + /** + * The list of waiting tasks. + */ + private final LinkedList> waitTasks; + + /** + * The list of working threads. + */ + private final Array threads; + + /** + * The waiting flag. + */ + private final AtomicBoolean wait; + + /** + * The synchronizer. + */ + private final Lock lock; + + /** + * The count of executing tasks per thread. + */ + private final int packetSize; + + /** + * Instantiates a new Thread pool task executor. + * + * @param threadFactory the thread factory + * @param poolSize the pool size + * @param packetSize the packet size + */ + public ThreadPoolTaskExecutor( + GroupThreadFactory threadFactory, + int poolSize, + int packetSize) { + this.waitTasks = LinkedListFactory.newLinkedList(CallableTask.class); + this.wait = new AtomicBoolean(); + this.lock = LockFactory.newAtomicLock(); + this.threads = ArrayFactory.newArray(Thread.class); + this.packetSize = packetSize; + + for (int i = 0; i < poolSize; i++) { + + final Thread thread = threadFactory.newThread(this); + thread.setDaemon(true); + thread.start(); + + threads.add(thread); } + } - @Override - public void execute(@NotNull final SimpleTask task) { - lock(); - try { - - waitTasks.add(task); + @Override + public void execute(SimpleTask task) { + lock(); + try { - if (wait.get()) { - synchronized (wait) { - if (wait.compareAndSet(true, false)) { - ConcurrentUtils.notifyAllInSynchronize(wait); - } - } - } + waitTasks.add(task); - } finally { - unlock(); + if (wait.get()) { + synchronized (wait) { + if (wait.compareAndSet(true, false)) { + ConcurrentUtils.notifyAllInSynchronize(wait); + } } - } - - /** - * Get a local object container. - * - * @param thread the thread. - * @return the local object container of the thread. - */ - @NotNull - protected L getLocalObjects(@NotNull final Thread thread) { - throw new UnsupportedOperationException(); - } - - /** - * Gets packet size. - * - * @return the count of executing tasks per thread. - */ - public int getPacketSize() { - return packetSize; - } + } - /** - * Gets wait. - * - * @return the waiting flag. - */ - @NotNull - protected AtomicBoolean getWait() { - return wait; + } finally { + unlock(); } + } + + /** + * Get a local object container. + * + * @param thread the thread. + * @return the local object container of the thread. + */ + protected L getLocalObjects(Thread thread) { + throw new UnsupportedOperationException(); + } + + /** + * Gets packet size. + * + * @return the count of executing tasks per thread. + */ + public int getPacketSize() { + return packetSize; + } + + /** + * Gets wait. + * + * @return the waiting flag. + */ + protected AtomicBoolean getWait() { + return wait; + } + + /** + * Gets wait tasks. + * + * @return the list of waiting tasks. + */ + protected LinkedList> getWaitTasks() { + return waitTasks; + } + + @Override + public void lock() { + lock.lock(); + } + + @Override + public void run() { + + Thread thread = Thread.currentThread(); + + LinkedList> waitTasks = getWaitTasks(); + Array> executeTasks = ArrayFactory.newArray(CallableTask.class); + + L local = getLocalObjects(thread); + int packetSize = getPacketSize(); + + while (true) { + + executeTasks.clear(); + + lock(); + try { + + if (waitTasks.isEmpty()) { + wait.getAndSet(true); + } else { + for (int i = 0; i < packetSize && !waitTasks.isEmpty(); i++) { + executeTasks.add(waitTasks.poll()); + } + } - /** - * Gets wait tasks. - * - * @return the list of waiting tasks. - */ - @NotNull - protected LinkedList> getWaitTasks() { - return waitTasks; - } - - @Override - public void lock() { - lock.lock(); - } - - @Override - public void run() { - - final Thread thread = Thread.currentThread(); - - final LinkedList> waitTasks = getWaitTasks(); - final Array> executeTasks = ArrayFactory.newArray(CallableTask.class); - - final L local = getLocalObjects(thread); - final int packetSize = getPacketSize(); - - while (true) { - - executeTasks.clear(); - - lock(); - try { - - if (waitTasks.isEmpty()) { - wait.getAndSet(true); - } else { - for (int i = 0; i < packetSize && !waitTasks.isEmpty(); i++) { - executeTasks.add(waitTasks.poll()); - } - } - - } finally { - unlock(); - } - - if (executeTasks.isEmpty() && wait.get()) { - synchronized (wait) { - if (wait.get()) { - ConcurrentUtils.waitInSynchronize(wait); - } - } - } + } finally { + unlock(); + } - if (executeTasks.isEmpty()) continue; - try { + if (executeTasks.isEmpty() && wait.get()) { + synchronized (wait) { + if (wait.get()) { + ConcurrentUtils.waitInSynchronize(wait); + } + } + } - final long currentTime = System.currentTimeMillis(); + if (executeTasks.isEmpty()) { + continue; + } + try { - for (final CallableTask task : executeTasks.array()) { - if (task == null) break; - task.call(local, currentTime); - } + long currentTime = System.currentTimeMillis(); - } catch (final Exception e) { - LOGGER.warning(e); - } + for (CallableTask task : executeTasks.array()) { + if (task == null) { + break; + } + task.call(local, currentTime); } - } - @NotNull - @Override - public Future submit(@NotNull final CallableTask task) { - throw new RuntimeException("not implemented."); + } catch (Exception e) { + LOGGER.warning(e); + } } + } - @Override - public void unlock() { - lock.unlock(); - } + @Override + public Future submit(CallableTask task) { + throw new RuntimeException("not implemented."); + } + + @Override + public void unlock() { + lock.unlock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/AsyncReadSyncWriteLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/AsyncReadSyncWriteLock.java index 84e86505..264f85d7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/AsyncReadSyncWriteLock.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/AsyncReadSyncWriteLock.java @@ -7,23 +7,23 @@ */ public interface AsyncReadSyncWriteLock { - /** - * Lock any writing for reading. - */ - void asyncLock(); + /** + * Lock any writing for reading. + */ + void asyncLock(); - /** - * Finish this reading and unlock any writing if it is last reading. - */ - void asyncUnlock(); + /** + * Finish this reading and unlock any writing if it is last reading. + */ + void asyncUnlock(); - /** - * Lock any reading for writing. - */ - void syncLock(); + /** + * Lock any reading for writing. + */ + void syncLock(); - /** - * Finish this writing and unlock any readings. - */ - void syncUnlock(); + /** + * Finish this writing and unlock any readings. + */ + void syncUnlock(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java index 1752a9c8..05e83f6d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java @@ -3,81 +3,77 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.StampedLock; -import javasabr.rlib.common.concurrent.lock.impl.FinalAtomicLock; -import javasabr.rlib.common.concurrent.lock.impl.FinalAtomicReadWriteLock; -import javasabr.rlib.common.concurrent.lock.impl.FinalReentrantAtomicLock; -import javasabr.rlib.common.concurrent.lock.impl.FinalReentrantLock; -import javasabr.rlib.common.concurrent.lock.impl.FinalReentrantReadWriteLock; -import javasabr.rlib.common.concurrent.lock.impl.FinalStampedLock; import javasabr.rlib.common.concurrent.lock.impl.ReentrantARSWLock; +import org.jspecify.annotations.NullMarked; /** * The factory for creating new locks. * * @author JavaSaBr */ +@NullMarked public class LockFactory { - /** - * Create a new {@link ReentrantARSWLock}. - * - * @return the new lock. - */ - public static AsyncReadSyncWriteLock newReentrantARSWLock() { - return new ReentrantARSWLock(); - } + /** + * Create a new {@link ReentrantARSWLock}. + * + * @return the new lock. + */ + public static AsyncReadSyncWriteLock newReentrantARSWLock() { + return new ReentrantARSWLock(); + } - /** - * Create a new {@link FinalStampedLock}. - * - * @return the new lock. - */ - public static StampedLock newStampedLock() { - return new FinalStampedLock(); - } + /** + * Create a new {@link FinalStampedLock}. + * + * @return the new lock. + */ + public static StampedLock newStampedLock() { + return new FinalStampedLock(); + } - /** - * Create a new {@link FinalReentrantLock}. - * - * @return the new lock. - */ - public static Lock newReentrantLock() { - return new FinalReentrantLock(); - } + /** + * Create a new {@link FinalReentrantLock}. + * + * @return the new lock. + */ + public static Lock newReentrantLock() { + return new FinalReentrantLock(); + } - /** - * Create a new {@link FinalAtomicReadWriteLock}. - * - * @return the new lock. - */ - public static AsyncReadSyncWriteLock newAtomicARSWLock() { - return new FinalAtomicReadWriteLock(); - } + /** + * Create a new {@link FinalAtomicReadWriteLock}. + * + * @return the new lock. + */ + public static AsyncReadSyncWriteLock newAtomicARSWLock() { + return new FinalAtomicReadWriteLock(); + } - /** - * Create a new {@link FinalAtomicLock}. - * - * @return the new lock. - */ - public static Lock newAtomicLock() { - return new FinalAtomicLock(); - } + /** + * Create a new {@link FinalAtomicLock}. + * + * @return the new lock. + */ + public static Lock newAtomicLock() { + return new FinalAtomicLock(); + } - /** - * Create a new {@link FinalReentrantReadWriteLock}. - * - * @return the new lock. - */ - public static ReadWriteLock newReentrantRWLock() { - return new FinalReentrantReadWriteLock(); - } + /** + * Create a new {@link FinalReentrantReadWriteLock}. + * + * @return the new lock. + */ + public static ReadWriteLock newReentrantRWLock() { + return new FinalReentrantReadWriteLock(); + } - /** - * Create a new {@link FinalReentrantAtomicLock}. - * - * @return the new lock. - */ - public static Lock newReentrantAtomicLock() { - return new FinalReentrantAtomicLock(); - } + /** + * Create a new {@link FinalReentrantAtomicLock}. + * + * @return the new lock. + */ + public static Lock newReentrantAtomicLock() { + return new FinalReentrantAtomicLock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockUtils.java index 0130d0ac..0ce473a2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockUtils.java @@ -7,215 +7,236 @@ import java.util.function.Function; import javasabr.rlib.common.function.FunctionInt; import javasabr.rlib.common.function.ObjectIntFunction; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class with utility methods to work with locks. * * @author JavaSaBr */ +@NullMarked public class LockUtils { - /** - * Execute a function in locked block. - * - * @param the type parameter - * @param lockable the lockable object. - * @param consumer the function. - */ - public static void runInLock(@Nullable final L lockable, @NotNull final Consumer consumer) { - if (lockable == null) return; - lockable.lock(); - try { - consumer.accept(lockable); - } finally { - lockable.unlock(); - } + /** + * Execute a function in locked block. + * + * @param the type parameter + * @param lockable the lockable object. + * @param consumer the function. + */ + public static void runInLock(@Nullable L lockable, Consumer consumer) { + if (lockable == null) { + return; } - - /** - * Execute a function in locked block. - * - * @param the type parameter - * @param the type parameter - * @param lockable the lockable object. - * @param argument the additional argument. - * @param consumer the function. - */ - public static void runInLock(@Nullable final L lockable, @Nullable final F argument, - @NotNull final BiConsumer consumer) { - if (lockable == null) return; - lockable.lock(); - try { - consumer.accept(lockable, argument); - } finally { - lockable.unlock(); - } + lockable.lock(); + try { + consumer.accept(lockable); + } finally { + lockable.unlock(); } - - /** - * Execute a function in locked block. - * - * @param the type parameter - * @param the type parameter - * @param lockable the lockable object. - * @param function the function. - * @return результат работы функции либо null. - */ - @Nullable - public static R getInLock(@Nullable final L lockable, @NotNull final Function function) { - if (lockable == null) return null; - lockable.lock(); - try { - return function.apply(lockable); - } finally { - lockable.unlock(); - } + } + + /** + * Execute a function in locked block. + * + * @param the type parameter + * @param the type parameter + * @param lockable the lockable object. + * @param argument the additional argument. + * @param consumer the function. + */ + public static void runInLock( + @Nullable L lockable, + @Nullable F argument, + BiConsumer<@Nullable L, @Nullable F> consumer) { + if (lockable == null) { + return; } - - /** - * Execute a function in locked block. - * - * @param the type parameter - * @param lockable the lockable object. - * @param function the function. - * @return результат работы функции либо -1. - */ - public static int getInLockInt(@Nullable final L lockable, @NotNull final FunctionInt function) { - if (lockable == null) return -1; - lockable.lock(); - try { - return function.apply(lockable); - } finally { - lockable.unlock(); - } + lockable.lock(); + try { + consumer.accept(lockable, argument); + } finally { + lockable.unlock(); } - - /** - * Execute a function in locked block. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param lockable the lockable object. - * @param argument the additional argument. - * @param function the function. - * @return результат работы функции либо null. - */ - @Nullable - public static R getInLock(@Nullable final L lockable, @Nullable final F argument, @NotNull final BiFunction function) { - if (lockable == null) return null; - lockable.lock(); - try { - return function.apply(lockable, argument); - } finally { - lockable.unlock(); - } + } + + /** + * Execute a function in locked block. + * + * @param the type parameter + * @param the type parameter + * @param lockable the lockable object. + * @param function the function. + * @return результат работы функции либо null. + */ + @Nullable + public static R getInLock( + @Nullable L lockable, + Function<@Nullable L, @Nullable R> function) { + if (lockable == null) { + return null; } - - /** - * Execute a function in locked block. - * - * @param the type parameter - * @param the type parameter - * @param lockable the lockable object. - * @param argument the additional argument. - * @param function the function. - * @return результат работы функции либо null. - */ - @Nullable - public static R getInLock(@Nullable final L lockable, final int argument, @NotNull final ObjectIntFunction function) { - if (lockable == null) return null; - lockable.lock(); - try { - return function.apply(lockable, argument); - } finally { - lockable.unlock(); - } + lockable.lock(); + try { + return function.apply(lockable); + } finally { + lockable.unlock(); } - - /** - * Lock two locks. - * - * @param first the first lock. - * @param second the second lock. - */ - public static void lock(@NotNull final Lockable first, @NotNull final Lock second) { - first.lock(); - second.lock(); + } + + /** + * Execute a function in locked block. + * + * @param the type parameter + * @param lockable the lockable object. + * @param function the function. + * @return результат работы функции либо -1. + */ + public static int getInLockInt( + @Nullable L lockable, + FunctionInt<@Nullable L> function) { + if (lockable == null) { + return -1; } - - /** - * Lock two lockable objects. - * - * @param first the first lockable object. - * @param second the second lockable object. - */ - public static void lock(@NotNull final Lockable first, @NotNull final Lockable second) { - first.lock(); - second.lock(); + lockable.lock(); + try { + return function.apply(lockable); + } finally { + lockable.unlock(); } - - /** - * Lock two comparable and lockable objects. - * - * @param the type parameter - * @param first the first lockable object. - * @param second the second lockable object. - */ - public static & Lockable> void lock(@NotNull final T first, @NotNull final T second) { - - final int result = first.compareTo(second); - - if (result == 0 || result == -1) { - first.lock(); - second.lock(); - } else { - second.lock(); - first.lock(); - } + } + + /** + * Execute a function in locked block. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param lockable the lockable object. + * @param argument the additional argument. + * @param function the function. + * @return результат работы функции либо null. + */ + @Nullable + public static R getInLock( + @Nullable L lockable, + @Nullable F argument, + BiFunction<@Nullable L, @Nullable F, R> function) { + if (lockable == null) { + return null; } - - /** - * Unlock two locks. - * - * @param first the first lock. - * @param second the second lock. - */ - public static void unlock(@NotNull final Lock first, @NotNull final Lock second) { - first.unlock(); - second.unlock(); + lockable.lock(); + try { + return function.apply(lockable, argument); + } finally { + lockable.unlock(); } - - /** - * Unlock two lockable objects. - * - * @param first the first lockable object. - * @param second the second lockable object. - */ - public static void unlock(@NotNull final Lockable first, @NotNull final Lockable second) { - first.unlock(); - second.unlock(); + } + + /** + * Execute a function in locked block. + * + * @param the type parameter + * @param the type parameter + * @param lockable the lockable object. + * @param argument the additional argument. + * @param function the function. + * @return результат работы функции либо null. + */ + @Nullable + public static R getInLock( + @Nullable final L lockable, + int argument, + ObjectIntFunction<@Nullable L, R> function) { + if (lockable == null) { + return null; } - - /** - * Unlock two comparable and lockable objects. - * - * @param the type parameter - * @param first the first lockable object. - * @param second the second lockable object. - */ - public static & Lockable> void unlock(@NotNull final T first, @NotNull final T second) { - - final int result = first.compareTo(second); - - if (result == 0 || result == -1) { - second.unlock(); - first.unlock(); - } else { - first.unlock(); - second.unlock(); - } + lockable.lock(); + try { + return function.apply(lockable, argument); + } finally { + lockable.unlock(); + } + } + + /** + * Lock two locks. + * + * @param first the first lock. + * @param second the second lock. + */ + public static void lock(Lockable first, Lock second) { + first.lock(); + second.lock(); + } + + /** + * Lock two lockable objects. + * + * @param first the first lockable object. + * @param second the second lockable object. + */ + public static void lock(Lockable first, Lockable second) { + first.lock(); + second.lock(); + } + + /** + * Lock two comparable and lockable objects. + * + * @param the type parameter + * @param first the first lockable object. + * @param second the second lockable object. + */ + public static & Lockable> void lock(T first, T second) { + int result = first.compareTo(second); + if (result == 0 || result < 0) { + first.lock(); + second.lock(); + } else { + second.lock(); + first.lock(); + } + } + + /** + * Unlock two locks. + * + * @param first the first lock. + * @param second the second lock. + */ + public static void unlock(Lock first, Lock second) { + first.unlock(); + second.unlock(); + } + + /** + * Unlock two lockable objects. + * + * @param first the first lockable object. + * @param second the second lockable object. + */ + public static void unlock(Lockable first, Lockable second) { + first.unlock(); + second.unlock(); + } + + /** + * Unlock two comparable and lockable objects. + * + * @param the type parameter + * @param first the first lockable object. + * @param second the second lockable object. + */ + public static & Lockable> void unlock(T first, T second) { + int result = first.compareTo(second); + if (result == 0 || result < 0) { + second.unlock(); + first.unlock(); + } else { + first.unlock(); + second.unlock(); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/Lockable.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/Lockable.java index 48b01a74..8d9a8c34 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/Lockable.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/Lockable.java @@ -7,13 +7,13 @@ */ public interface Lockable { - /** - * Lock this object. - */ - void lock(); + /** + * Lock this object. + */ + void lock(); - /** - * Unlock this object. - */ - void unlock(); + /** + * Unlock this object. + */ + void unlock(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicLock.java index ff721876..ed45c08c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicLock.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicLock.java @@ -3,93 +3,91 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; -import org.jetbrains.annotations.NotNull; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; +import org.jspecify.annotations.NullMarked; /** - * The implementation of the {@link Lock} based on using {@link AtomicInteger} without supporting - * reentrant calls. + * The implementation of the {@link Lock} based on using {@link ReusableAtomicInteger} without supporting reentrant calls. * * @author JavaSaBr */ +@NullMarked public class AtomicLock implements Lock { - private static final int STATUS_LOCKED = 1; - private static final int STATUS_UNLOCKED = 0; - - /** - * The status of lock. - */ - protected final AtomicInteger status; - - /** - * The field for consuming CPU. - */ - protected int sink; - - /** - * Instantiates a new Atomic lock. - */ - public AtomicLock() { - this.status = new AtomicInteger(); - this.sink = 1; - } - - @Override - public void lock() { - while (!tryLock()) consumeCPU(); - } - - /** - * Consume cpu. - */ - protected void consumeCPU() { - - final int value = sink; - int newValue = value * value; - newValue += value >>> 1; - newValue += value & newValue; - newValue += value ^ newValue; - newValue += newValue << value; - newValue += newValue | value; - newValue += value & newValue; - newValue += value ^ newValue; - newValue += newValue << value; - newValue += newValue | value; - - sink = newValue; - } - - @Override - public void lockInterruptibly() throws InterruptedException { - throw new UnsupportedOperationException(); - } - - @NotNull - @Override - public Condition newCondition() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean tryLock() { - return status.compareAndSet(STATUS_UNLOCKED, STATUS_LOCKED); - } - - @Override - public boolean tryLock(final long time, @NotNull final TimeUnit unit) throws InterruptedException { - throw new UnsupportedOperationException(); - } - - @Override - public void unlock() { - status.set(STATUS_UNLOCKED); - } - - @Override - public String toString() { - return "AtomicLock{" + - "status=" + status + - '}'; - } + private static final int STATUS_LOCKED = 1; + private static final int STATUS_UNLOCKED = 0; + + /** + * The status of lock. + */ + protected final ReusableAtomicInteger status; + + /** + * The field for consuming CPU. + */ + protected int sink; + + /** + * Instantiates a new Atomic lock. + */ + public AtomicLock() { + this.status = new ReusableAtomicInteger(); + this.sink = 1; + } + + @Override + public void lock() { + while (!tryLock()) + consumeCPU(); + } + + /** + * Consume cpu. + */ + protected void consumeCPU() { + + final int value = sink; + int newValue = value * value; + newValue += value >>> 1; + newValue += value & newValue; + newValue += value ^ newValue; + newValue += newValue << value; + newValue += newValue | value; + newValue += value & newValue; + newValue += value ^ newValue; + newValue += newValue << value; + newValue += newValue | value; + + sink = newValue; + } + + @Override + public void lockInterruptibly() { + throw new UnsupportedOperationException(); + } + + @Override + public Condition newCondition() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean tryLock() { + return status.compareAndSet(STATUS_UNLOCKED, STATUS_LOCKED); + } + + @Override + public boolean tryLock(long time, TimeUnit unit) { + throw new UnsupportedOperationException(); + } + + @Override + public void unlock() { + status.set(STATUS_UNLOCKED); + } + + @Override + public String toString() { + return "AtomicLock{" + "status=" + status + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicReadWriteLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicReadWriteLock.java index 8cf94eea..3ec5022e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicReadWriteLock.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/AtomicReadWriteLock.java @@ -3,162 +3,167 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.concurrent.lock.AsyncReadSyncWriteLock; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * The implementation of the {@link AsyncReadSyncWriteLock} using the several {@link AtomicInteger} without supporting + * The implementation of the {@link AsyncReadSyncWriteLock} using the several {@link ReusableAtomicInteger} without supporting * reentrant calls. * * @author JavaSaBr */ +@NullMarked public class AtomicReadWriteLock implements AsyncReadSyncWriteLock, Lock { - private static final int STATUS_WRITE_LOCKED = 1; - private static final int STATUS_WRITE_UNLOCKED = 0; - - private static final int STATUS_READ_UNLOCKED = 0; - private static final int STATUS_READ_LOCKED = -200000; - - /** - * The status of write lock. - */ - @NotNull - protected final AtomicInteger writeStatus; - - /** - * The count of writers. - */ - @NotNull - protected final AtomicInteger writeCount; - - /** - * The count of readers. - */ - @NotNull - protected final AtomicInteger readCount; - - /** - * The field for consuming CPU. - */ - protected int sink; - - /** - * Instantiates a new Atomic read write lock. - */ - public AtomicReadWriteLock() { - this.writeCount = new AtomicInteger(0); - this.writeStatus = new AtomicInteger(0); - this.readCount = new AtomicInteger(0); - this.sink = 1; - } - - @Override - public void asyncLock() { - while (!tryReadLock()) consumeCPU(); - } - - @Override - public void asyncUnlock() { - readCount.decrementAndGet(); - } - - /** - * Consume cpu. - */ - protected void consumeCPU() { - - final int value = sink; - int newValue = value * value; - newValue += value >>> 1; - newValue += value & newValue; - newValue += value >>> 1; - newValue += value & newValue; - newValue += value >>> 1; - newValue += value & newValue; - - sink = newValue; - } - - @Override - public void lock() { - syncLock(); - } - - @Override - public void lockInterruptibly() throws InterruptedException { - throw new UnsupportedOperationException(); - } - - @NotNull - @Override - public Condition newCondition() { - throw new UnsupportedOperationException(); - } - - @Override - public void syncLock() { - writeCount.incrementAndGet(); - while (tryToLockReading()) consumeCPU(); - while (tryToLockWriting()) consumeCPU(); - } - - /** - * Try to lock writing boolean. - * - * @return the boolean - */ - protected boolean tryToLockWriting() { - return writeStatus.get() != STATUS_WRITE_UNLOCKED || !writeStatus.compareAndSet(STATUS_WRITE_UNLOCKED, STATUS_WRITE_LOCKED); - } - - /** - * Try to lock reading boolean. - * - * @return the boolean - */ - protected boolean tryToLockReading() { - return readCount.get() != STATUS_READ_UNLOCKED || !readCount.compareAndSet(STATUS_READ_UNLOCKED, STATUS_READ_LOCKED); - } - - @Override - public void syncUnlock() { - writeStatus.set(STATUS_WRITE_UNLOCKED); - readCount.set(STATUS_READ_UNLOCKED); - writeCount.decrementAndGet(); - } - - @Override - public boolean tryLock() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean tryLock(final long time, @NotNull final TimeUnit unit) throws InterruptedException { - throw new UnsupportedOperationException(); - } - - /** - * Try to get read lock. - */ - private boolean tryReadLock() { - if (writeCount.get() != 0) return false; - final int value = readCount.get(); - return value != STATUS_READ_LOCKED && readCount.compareAndSet(value, value + 1); - } - - @Override - public void unlock() { - syncUnlock(); - } - - @Override - public String toString() { - return "AtomicReadWriteLock{" + - "readCount=" + readCount + - ", writeCount=" + writeCount + - ", writeStatus=" + writeStatus + - '}'; - } + private static final int STATUS_WRITE_LOCKED = 1; + private static final int STATUS_WRITE_UNLOCKED = 0; + + private static final int STATUS_READ_UNLOCKED = 0; + private static final int STATUS_READ_LOCKED = -200000; + + /** + * The status of write lock. + */ + protected final ReusableAtomicInteger writeStatus; + + /** + * The count of writers. + */ + protected final ReusableAtomicInteger writeCount; + + /** + * The count of readers. + */ + protected final ReusableAtomicInteger readCount; + + /** + * The field for consuming CPU. + */ + protected int sink; + + /** + * Instantiates a new Atomic read write lock. + */ + public AtomicReadWriteLock() { + this.writeCount = new ReusableAtomicInteger(0); + this.writeStatus = new ReusableAtomicInteger(0); + this.readCount = new ReusableAtomicInteger(0); + this.sink = 1; + } + + @Override + public void asyncLock() { + while (!tryReadLock()) + consumeCPU(); + } + + @Override + public void asyncUnlock() { + readCount.decrementAndGet(); + } + + /** + * Consume cpu. + */ + protected void consumeCPU() { + + final int value = sink; + int newValue = value * value; + newValue += value >>> 1; + newValue += value & newValue; + newValue += value >>> 1; + newValue += value & newValue; + newValue += value >>> 1; + newValue += value & newValue; + + sink = newValue; + } + + @Override + public void lock() { + syncLock(); + } + + @Override + public void lockInterruptibly() { + throw new UnsupportedOperationException(); + } + + @Override + public Condition newCondition() { + throw new UnsupportedOperationException(); + } + + @Override + public void syncLock() { + writeCount.incrementAndGet(); + while (tryToLockReading()) { + consumeCPU(); + } + while (tryToLockWriting()) { + consumeCPU(); + } + } + + /** + * Try to lock writing boolean. + * + * @return the boolean + */ + protected boolean tryToLockWriting() { + return writeStatus.get() != STATUS_WRITE_UNLOCKED || !writeStatus.compareAndSet( + STATUS_WRITE_UNLOCKED, + STATUS_WRITE_LOCKED); + } + + /** + * Try to lock reading boolean. + * + * @return the boolean + */ + protected boolean tryToLockReading() { + return readCount.get() != STATUS_READ_UNLOCKED || !readCount.compareAndSet( + STATUS_READ_UNLOCKED, + STATUS_READ_LOCKED); + } + + @Override + public void syncUnlock() { + writeStatus.set(STATUS_WRITE_UNLOCKED); + readCount.set(STATUS_READ_UNLOCKED); + writeCount.decrementAndGet(); + } + + @Override + public boolean tryLock() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean tryLock(long time, TimeUnit unit) { + throw new UnsupportedOperationException(); + } + + /** + * Try to get read lock. + */ + private boolean tryReadLock() { + if (writeCount.get() != 0) { + return false; + } + int value = readCount.get(); + return value != STATUS_READ_LOCKED && readCount.compareAndSet(value, value + 1); + } + + @Override + public void unlock() { + syncUnlock(); + } + + @Override + public String toString() { + return "AtomicReadWriteLock{" + "readCount=" + readCount + ", writeCount=" + writeCount + ", writeStatus=" + + writeStatus + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicLock.java deleted file mode 100644 index 318f98cf..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicLock.java +++ /dev/null @@ -1,16 +0,0 @@ -package javasabr.rlib.common.concurrent.lock.impl; - -/** - * The final implementation of the {@link AtomicLock}. - * - * @author JavaSaBr - */ -public final class FinalAtomicLock extends AtomicLock { - - /** - * Instantiates a new Final atomic lock. - */ - public FinalAtomicLock() { - super(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicReadWriteLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicReadWriteLock.java deleted file mode 100644 index ca647761..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalAtomicReadWriteLock.java +++ /dev/null @@ -1,16 +0,0 @@ -package javasabr.rlib.common.concurrent.lock.impl; - -/** - * The final implementation of the {@link AtomicReadWriteLock}. - * - * @author JavaSaBr - */ -public final class FinalAtomicReadWriteLock extends AtomicReadWriteLock { - - /** - * Instantiates a new Final atomic read write lock. - */ - public FinalAtomicReadWriteLock() { - super(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantAtomicLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantAtomicLock.java deleted file mode 100644 index 38c6f5ed..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantAtomicLock.java +++ /dev/null @@ -1,16 +0,0 @@ -package javasabr.rlib.common.concurrent.lock.impl; - -/** - * The final implementation of the {@link ReentrantAtomicLock}. - * - * @author JavaSaBr - */ -public final class FinalReentrantAtomicLock extends ReentrantAtomicLock { - - /** - * Instantiates a new Final reentrant atomic lock. - */ - public FinalReentrantAtomicLock() { - super(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantLock.java deleted file mode 100644 index 622585e2..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantLock.java +++ /dev/null @@ -1,13 +0,0 @@ -package javasabr.rlib.common.concurrent.lock.impl; - -import java.util.concurrent.locks.ReentrantLock; - -/** - * The type Final reentrant lock. - * - * @author JavaSaBr - */ -public final class FinalReentrantLock extends ReentrantLock { - - private static final long serialVersionUID = 411737919279934135L; -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantReadWriteLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantReadWriteLock.java deleted file mode 100644 index 9eb41ded..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalReentrantReadWriteLock.java +++ /dev/null @@ -1,13 +0,0 @@ -package javasabr.rlib.common.concurrent.lock.impl; - -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * The type Final reentrant read write lock. - * - * @author JavaSaBr - */ -public final class FinalReentrantReadWriteLock extends ReentrantReadWriteLock { - - private static final long serialVersionUID = 797324701725211617L; -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalStampedLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalStampedLock.java deleted file mode 100644 index 111e4b31..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/FinalStampedLock.java +++ /dev/null @@ -1,11 +0,0 @@ -package javasabr.rlib.common.concurrent.lock.impl; - -import java.util.concurrent.locks.StampedLock; - -/** - * The final implementation of the {@link StampedLock}. - * - * @author JavaSaBr. - */ -public final class FinalStampedLock extends StampedLock { -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java index e792e946..0ac18ab6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java @@ -6,53 +6,52 @@ import javasabr.rlib.common.concurrent.lock.AsyncReadSyncWriteLock; import javasabr.rlib.common.concurrent.lock.LockFactory; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * The wrapper of {@link ReentrantReadWriteLock} for implementing the interface {@link - * AsyncReadSyncWriteLock}*. + * The wrapper of {@link ReentrantReadWriteLock} for implementing the interface {@link AsyncReadSyncWriteLock}*. * * @author JavaSaBr */ +@NullMarked public final class ReentrantARSWLock implements AsyncReadSyncWriteLock { - /** - * The locker of writing. - */ - @NotNull - private final Lock readLock; - - /** - * The locker of reading. - */ - @NotNull - private final Lock writeLock; - - /** - * Instantiates a new Reentrant arsw lock. - */ - public ReentrantARSWLock() { - final ReadWriteLock readWriteLock = LockFactory.newReentrantRWLock(); - readLock = readWriteLock.readLock(); - writeLock = readWriteLock.writeLock(); - } - - @Override - public void asyncLock() { - readLock.lock(); - } - - @Override - public void asyncUnlock() { - readLock.unlock(); - } - - @Override - public void syncLock() { - writeLock.lock(); - } - - @Override - public void syncUnlock() { - writeLock.unlock(); - } + /** + * The locker of writing. + */ + private final Lock readLock; + + /** + * The locker of reading. + */ + private final Lock writeLock; + + /** + * Instantiates a new Reentrant arsw lock. + */ + public ReentrantARSWLock() { + ReadWriteLock readWriteLock = LockFactory.newReentrantRWLock(); + readLock = readWriteLock.readLock(); + writeLock = readWriteLock.writeLock(); + } + + @Override + public void asyncLock() { + readLock.lock(); + } + + @Override + public void asyncUnlock() { + readLock.unlock(); + } + + @Override + public void syncLock() { + writeLock.lock(); + } + + @Override + public void syncUnlock() { + writeLock.unlock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantAtomicLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantAtomicLock.java index 7599adc4..1c873c7b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantAtomicLock.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantAtomicLock.java @@ -3,115 +3,115 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.concurrent.atomic.AtomicReference; -import org.jetbrains.annotations.NotNull; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicReference; +import org.jspecify.annotations.NullMarked; /** - * The implementation of the {@link Lock} based on using {@link AtomicInteger} with supporting - * reentrant calls. + * The implementation of the {@link Lock} based on using {@link ReusableAtomicInteger} with supporting reentrant calls. * * @author JavaSaBr */ +@NullMarked public class ReentrantAtomicLock implements Lock { - /** - * The status of lock. - */ - @NotNull - private final AtomicReference status; - - /** - * The level of locking. - */ - @NotNull - private final AtomicInteger level; - - /** - * The field for consuming CPU. - */ - private int sink; - - /** - * Instantiates a new Reentrant atomic lock. - */ - public ReentrantAtomicLock() { - this.status = new AtomicReference<>(); - this.level = new AtomicInteger(); - this.sink = 1; + /** + * The status of lock. + */ + private final ReusableAtomicReference status; + + /** + * The level of locking. + */ + private final ReusableAtomicInteger level; + + /** + * The field for consuming CPU. + */ + private int sink; + + /** + * Instantiates a new Reentrant atomic lock. + */ + public ReentrantAtomicLock() { + this.status = new ReusableAtomicReference<>(); + this.level = new ReusableAtomicInteger(); + this.sink = 1; + } + + @Override + public void lock() { + Thread thread = Thread.currentThread(); + try { + if (status.get() == thread) { + return; + } + while (!status.compareAndSet(null, thread)) + consumeCPU(); + } finally { + level.incrementAndGet(); } - - @Override - public void lock() { - - final Thread thread = Thread.currentThread(); - - try { - if (status.get() == thread) return; - while (!status.compareAndSet(null, thread)) consumeCPU(); - } finally { - level.incrementAndGet(); - } - } - - /** - * Consume cpu. - */ - protected void consumeCPU() { - - final int value = sink; - int newValue = value * value; - newValue += value >>> 1; - newValue += value & newValue; - newValue += value ^ newValue; - newValue += newValue << value; - newValue += newValue | value; - - sink = newValue; + } + + /** + * Consume cpu. + */ + protected void consumeCPU() { + + final int value = sink; + int newValue = value * value; + newValue += value >>> 1; + newValue += value & newValue; + newValue += value ^ newValue; + newValue += newValue << value; + newValue += newValue | value; + + sink = newValue; + } + + @Override + public void lockInterruptibly() { + throw new UnsupportedOperationException(); + } + + @Override + public Condition newCondition() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean tryLock() { + + Thread currentThread = Thread.currentThread(); + + if (status.get() == currentThread) { + level.incrementAndGet(); + return true; } - @Override - public void lockInterruptibly() throws InterruptedException { - throw new UnsupportedOperationException(); + if (status.compareAndSet(null, currentThread)) { + level.incrementAndGet(); + return true; } - @NotNull - @Override - public Condition newCondition() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean tryLock() { + return false; + } - final Thread currentThread = Thread.currentThread(); + @Override + public boolean tryLock(long time, TimeUnit unit) { + throw new UnsupportedOperationException(); + } - if (status.get() == currentThread) { - level.incrementAndGet(); - return true; - } + @Override + public void unlock() { - if (status.compareAndSet(null, currentThread)) { - level.incrementAndGet(); - return true; - } - - return false; + final Thread thread = Thread.currentThread(); + if (status.get() != thread) { + return; } - @Override - public boolean tryLock(final long time, @NotNull final TimeUnit unit) throws InterruptedException { - throw new UnsupportedOperationException(); - } - - @Override - public void unlock() { - - final Thread thread = Thread.currentThread(); - if (status.get() != thread) return; - - if (level.decrementAndGet() == 0) { - status.set(null); - } + if (level.decrementAndGet() == 0) { + status.set(null); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/CallableTask.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/CallableTask.java index 386bf48e..795dac85 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/CallableTask.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/CallableTask.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.concurrent.task; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; /** * The interface to implement a callable tasks. @@ -13,13 +13,13 @@ @FunctionalInterface public interface CallableTask { - /** - * Execute this task. - * - * @param local the thread local container. - * @param currentTime the current time. - * @return the result. - */ - @Nullable - R call(@NotNull L local, long currentTime); + /** + * Execute this task. + * + * @param local the thread local container. + * @param currentTime the current time. + * @return the result. + */ + @Nullable + R call(@NonNull L local, long currentTime); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java index 4215a810..f866c5c2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java @@ -10,26 +10,28 @@ */ public interface PeriodicTask extends CallableTask { - @Override - default Boolean call(@NotNull final L local, final long currentTime) { - if (update(local, currentTime)) return Boolean.TRUE; - return Boolean.FALSE; + @Override + default Boolean call(@NotNull final L local, final long currentTime) { + if (update(local, currentTime)) { + return Boolean.TRUE; } + return Boolean.FALSE; + } - /** - * Notify about finishing this task. - * - * @param local the thread local container. - */ - default void onFinish(@NotNull final L local) { - } + /** + * Notify about finishing this task. + * + * @param local the thread local container. + */ + default void onFinish(@NotNull final L local) { + } - /** - * Execute and update this task. - * - * @param local the thread local container. - * @param currentTime the current time. - * @return true if this task is finished. - */ - boolean update(@NotNull L local, long currentTime); + /** + * Execute and update this task. + * + * @param local the thread local container. + * @param currentTime the current time. + * @return true if this task is finished. + */ + boolean update(@NotNull L local, long currentTime); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java index 7c40b103..6dbf3b63 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java @@ -10,17 +10,17 @@ */ public interface SimpleTask extends CallableTask { - @Override - default Void call(@NotNull final L local, final long currentTime) { - execute(local, currentTime); - return null; - } + @Override + default Void call(@NotNull final L local, final long currentTime) { + execute(local, currentTime); + return null; + } - /** - * Execute this task. - * - * @param local the thread local container. - * @param currentTime the current time. - */ - void execute(@NotNull L local, long currentTime); + /** + * Execute this task. + * + * @param local the thread local container. + * @param currentTime the current time. + */ + void execute(@NotNull L local, long currentTime); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ConcurrentUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ConcurrentUtils.java index 17ab330d..99558ff9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ConcurrentUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ConcurrentUtils.java @@ -6,168 +6,169 @@ import javasabr.rlib.common.function.ObjectLongFunction; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * THe utility class with methods to work in concurrent cases. * * @author JavaSaBr */ +@NullMarked public final class ConcurrentUtils { - private static final Logger LOGGER = LoggerManager.getLogger(ConcurrentUtils.class); + private static final Logger LOGGER = LoggerManager.getLogger(ConcurrentUtils.class); - /** - * Notify all threads. - * - * @param object the object - */ - public static void notifyAll(@NotNull final Object object) { - synchronized (object) { - object.notifyAll(); - } + /** + * Notify all threads. + * + * @param object the object + */ + public static void notifyAll(Object object) { + synchronized (object) { + object.notifyAll(); } + } - /** - * Notify all threads from a synchronized block. - * - * @param object the object - */ - public static void notifyAllInSynchronize(@NotNull final Object object) { - object.notifyAll(); - } + /** + * Notify all threads from a synchronized block. + * + * @param object the object + */ + public static void notifyAllInSynchronize(Object object) { + object.notifyAll(); + } - /** - * Notify all threads and wait. - * - * @param object the object - */ - public static void notifyAndWait(@NotNull final Object object) { - synchronized (object) { - notifyAllInSynchronize(object); - waitInSynchronize(object); - } + /** + * Notify all threads and wait. + * + * @param object the object + */ + public static void notifyAndWait(Object object) { + synchronized (object) { + notifyAllInSynchronize(object); + waitInSynchronize(object); } + } - /** - * Wait. - * - * @param object the object - */ - public static void wait(@NotNull final Object object) { - synchronized (object) { - try { - object.wait(); - } catch (final InterruptedException e) { - LOGGER.warning(e); - } - } + /** + * Wait. + * + * @param object the object + */ + public static void wait(Object object) { + synchronized (object) { + try { + object.wait(); + } catch (final InterruptedException e) { + LOGGER.warning(e); + } } + } - /** - * Wait. - * - * @param object the object. - * @param time the time in ms. - */ - public static void wait(@NotNull final Object object, final long time) { - synchronized (object) { - try { - object.wait(time); - } catch (final InterruptedException e) { - LOGGER.warning(e); - } - } + /** + * Wait. + * + * @param object the object. + * @param time the time in ms. + */ + public static void wait(Object object, long time) { + synchronized (object) { + try { + object.wait(time); + } catch (final InterruptedException e) { + LOGGER.warning(e); + } } + } - /** - * Wait from a synchronized block. - * - * @param object the object - */ - public static void waitInSynchronize(@NotNull final Object object) { - try { - object.wait(); - } catch (final InterruptedException e) { - LOGGER.warning(e); - } + /** + * Wait from a synchronized block. + * + * @param object the object + */ + public static void waitInSynchronize(Object object) { + try { + object.wait(); + } catch (final InterruptedException e) { + LOGGER.warning(e); } + } - /** - * Wait from a synchronized block. - * - * @param object the object. - * @param time the time in ms. - */ - public static void waitInSynchronize(@NotNull final Object object, long time) { - try { - object.wait(time); - } catch (final InterruptedException e) { - LOGGER.warning(e); - } + /** + * Wait from a synchronized block. + * + * @param object the object. + * @param time the time in ms. + */ + public static void waitInSynchronize(Object object, long time) { + try { + object.wait(time); + } catch (final InterruptedException e) { + LOGGER.warning(e); } + } - /** - * Apply a function in locked block. - * - * @param the type parameter - * @param the type parameter - * @param sync the synchronizer. - * @param function the function. - * @return the result from the function. - */ - @Nullable - public static R get(@NotNull final T sync, @NotNull final Function function) { - sync.lock(); - try { - return function.apply(sync); - } finally { - sync.unlock(); - } + /** + * Apply a function in locked block. + * + * @param the type parameter + * @param the type parameter + * @param sync the synchronizer. + * @param function the function. + * @return the result from the function. + */ + @Nullable + public static R get(T sync, Function function) { + sync.lock(); + try { + return function.apply(sync); + } finally { + sync.unlock(); } + } - /** - * Apply a function in locked block. - * - * @param the type parameter - * @param the type parameter - * @param sync the synchronizer. - * @param argument the argument. - * @param function the function. - * @return the result from the function. - */ - @Nullable - public static R get(@NotNull final T sync, final int argument, @NotNull final ObjectIntFunction function) { - sync.lock(); - try { - return function.apply(sync, argument); - } finally { - sync.unlock(); - } + /** + * Apply a function in locked block. + * + * @param the type parameter + * @param the type parameter + * @param sync the synchronizer. + * @param argument the argument. + * @param function the function. + * @return the result from the function. + */ + @Nullable + public static R get(T sync, int argument, ObjectIntFunction function) { + sync.lock(); + try { + return function.apply(sync, argument); + } finally { + sync.unlock(); } + } - /** - * Apply a function in locked block. - * - * @param the type parameter - * @param the type parameter - * @param sync the synchronizer. - * @param argument the argument. - * @param function the function. - * @return the result from the function. - */ - @Nullable - public static R getInL(@NotNull final T sync, final long argument, @NotNull final ObjectLongFunction function) { - sync.lock(); - try { - return function.apply(sync, argument); - } finally { - sync.unlock(); - } + /** + * Apply a function in locked block. + * + * @param the type parameter + * @param the type parameter + * @param sync the synchronizer. + * @param argument the argument. + * @param function the function. + * @return the result from the function. + */ + @Nullable + public static R getInL(T sync, long argument, ObjectLongFunction function) { + sync.lock(); + try { + return function.apply(sync, argument); + } finally { + sync.unlock(); } + } - private ConcurrentUtils() { - throw new RuntimeException(); - } + private ConcurrentUtils() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ThreadUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ThreadUtils.java index b57baaa0..76081022 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ThreadUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/util/ThreadUtils.java @@ -10,18 +10,18 @@ */ public class ThreadUtils { - private static final Logger LOGGER = LoggerManager.getLogger(ThreadUtils.class); + private static final Logger LOGGER = LoggerManager.getLogger(ThreadUtils.class); - /** - * Sleep the current thread. - * - * @param time the time in ms. - */ - public static void sleep(final long time) { - try { - Thread.sleep(time); - } catch (final InterruptedException e) { - LOGGER.warning(e); - } + /** + * Sleep the current thread. + * + * @param time the time in ms. + */ + public static void sleep(long time) { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + LOGGER.warning(e); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractFileDocument.java b/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractFileDocument.java index f5c77036..c7dffb9f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractFileDocument.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractFileDocument.java @@ -9,7 +9,7 @@ import java.io.UncheckedIOException; import java.nio.file.Path; import java.nio.file.StandardOpenOption; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The file implementation of the parser of xml documents. @@ -17,38 +17,40 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public abstract class AbstractFileDocument extends AbstractStreamDocument { - /** - * The file path. - */ - @NotNull - protected final String filePath; + /** + * The file path. + */ + protected final String filePath; - public AbstractFileDocument(@NotNull final File file) { - this.filePath = file.getAbsolutePath(); - try { - setStream(new FileInputStream(file)); - } catch (FileNotFoundException e) { - throw new UncheckedIOException(e); - } + public AbstractFileDocument(File file) { + this.filePath = file.getAbsolutePath(); + try { + setStream(new FileInputStream(file)); + } catch (FileNotFoundException e) { + throw new UncheckedIOException(e); } + } - public AbstractFileDocument(@NotNull final Path path) { - this.filePath = path.toAbsolutePath().toString(); - try { - setStream(newInputStream(path, StandardOpenOption.READ)); - } catch (final IOException e) { - throw new UncheckedIOException(e); - } + public AbstractFileDocument(Path path) { + this.filePath = path + .toAbsolutePath() + .toString(); + try { + setStream(newInputStream(path, StandardOpenOption.READ)); + } catch (final IOException e) { + throw new UncheckedIOException(e); } + } - /** - * Get the file path. - * - * @return the file path. - */ - protected @NotNull String getFilePath() { - return filePath; - } + /** + * Get the file path. + * + * @return the file path. + */ + protected String getFilePath() { + return filePath; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractStreamDocument.java b/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractStreamDocument.java index a3c1cf7f..00bedc9a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractStreamDocument.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/data/AbstractStreamDocument.java @@ -11,8 +11,8 @@ import javax.xml.parsers.ParserConfigurationException; import lombok.AccessLevel; import lombok.Setter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -23,114 +23,115 @@ * * @author JavaSaBr */ +@NullMarked public abstract class AbstractStreamDocument implements DocumentXML { - protected static final Logger LOGGER = LoggerManager.getLogger(DocumentXML.class); - - protected static final ThreadLocal LOCAL_FACTORY = withInitial(() -> { - var factory = DocumentBuilderFactory.newInstance(); - factory.setValidating(false); - factory.setIgnoringComments(true); - return factory; - }); - - /** - * The stream of xml document. - */ - @Setter(AccessLevel.PROTECTED) - protected @Nullable InputStream stream; - - /** - * the DOM model of this document. - */ - protected @Nullable Document document; - - /** - * The result of parsing. - */ - protected @Nullable C result; - - public AbstractStreamDocument() { - super(); + protected static final Logger LOGGER = LoggerManager.getLogger(DocumentXML.class); + + protected static final ThreadLocal LOCAL_FACTORY = withInitial(() -> { + var factory = DocumentBuilderFactory.newInstance(); + factory.setValidating(false); + factory.setIgnoringComments(true); + return factory; + }); + + /** + * The stream of xml document. + */ + @Setter(AccessLevel.PROTECTED) + protected @Nullable InputStream stream; + + /** + * the DOM model of this document. + */ + protected @Nullable Document document; + + /** + * The result of parsing. + */ + protected @Nullable C result; + + public AbstractStreamDocument() { + super(); + } + + public AbstractStreamDocument(InputStream stream) { + this.stream = stream; + } + + /** + * Create a container of the result. + * + * @return the container of the result. + */ + protected abstract C create(); + + @Override + public C parse() { + + var factory = LOCAL_FACTORY.get(); + try { + var builder = factory.newDocumentBuilder(); + document = builder.parse(stream); + } catch (SAXException | IOException | ParserConfigurationException exc) { + LOGGER.warning(exc); + throw new RuntimeException(exc); + } finally { + IOUtils.close(stream); } - public AbstractStreamDocument(@NotNull InputStream stream) { - this.stream = stream; + result = create(); + try { + parse(document); + } catch (Exception exc) { + LOGGER.warning(exc); + throw new RuntimeException(exc); } - /** - * Create a container of the result. - * - * @return the container of the result. - */ - protected abstract @NotNull C create(); - - @Override - public @NotNull C parse() { - - var factory = LOCAL_FACTORY.get(); - try { - var builder = factory.newDocumentBuilder(); - document = builder.parse(stream); - } catch (SAXException | IOException | ParserConfigurationException exc) { - LOGGER.warning(exc); - throw new RuntimeException(exc); - } finally { - IOUtils.close(stream); - } - - result = create(); - try { - parse(document); - } catch (Exception exc) { - LOGGER.warning(exc); - throw new RuntimeException(exc); - } - - return result; - } + return result; + } - /** - * The process of parsing this DOM model. - * - * @param document the DOM model of this document. - */ - protected void parse(@NotNull Document document) { - for (var node = document.getFirstChild(); node != null; node = node.getNextSibling()) { + /** + * The process of parsing this DOM model. + * + * @param document the DOM model of this document. + */ + protected void parse(Document document) { + for (var node = document.getFirstChild(); node != null; node = node.getNextSibling()) { - if (node.getNodeType() != Node.ELEMENT_NODE) { - continue; - } + if (node.getNodeType() != Node.ELEMENT_NODE) { + continue; + } - parse(null, (Element) node); - } + parse(null, (Element) node); } + } - /** - * The process of parsing this document. - * - * @param parent the parent element. - * @param element the current element. - */ - protected void parse(@Nullable Element parent, @NotNull Element element) { - handle(parent, element); - - for (var node = element.getFirstChild(); node != null; node = node.getNextSibling()) { + /** + * The process of parsing this document. + * + * @param parent the parent element. + * @param element the current element. + */ + protected void parse(@Nullable Element parent, Element element) { + handle(parent, element); - if (node.getNodeType() != Node.ELEMENT_NODE) { - continue; - } + for (var node = element.getFirstChild(); node != null; node = node.getNextSibling()) { - parse(element, (Element) node); - } - } + if (node.getNodeType() != Node.ELEMENT_NODE) { + continue; + } - /** - * The process of parsing this element. - * - * @param parent the parent element. - * @param element the current element. - */ - protected void handle(@Nullable Element parent, @NotNull Element element) { + parse(element, (Element) node); } + } + + /** + * The process of parsing this element. + * + * @param parent the parent element. + * @param element the current element. + */ + protected void handle(@Nullable Element parent, Element element) { + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/data/DocumentXML.java b/rlib-common/src/main/java/javasabr/rlib/common/data/DocumentXML.java index c2fb1fd7..1df10383 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/data/DocumentXML.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/data/DocumentXML.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.data; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a parser of xml documents. @@ -8,12 +8,13 @@ * @param the result type. * @author JavaSaBr */ +@NullMarked public interface DocumentXML { - /** - * Parse this document and get the result. - * - * @return the result. - */ - @NotNull C parse(); + /** + * Parse this document and get the result. + * + * @return the result. + */ + C parse(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/BiIntPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/BiIntPredicate.java index eee0a691..a2428be8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/BiIntPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/BiIntPredicate.java @@ -6,5 +6,5 @@ @FunctionalInterface public interface BiIntPredicate { - boolean test(int first, int second); + boolean test(int first, int second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java index 1ff2743a..7a544e83 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java @@ -12,12 +12,12 @@ @FunctionalInterface public interface BiObjectIntConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, @Nullable S second, int third); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + */ + void accept(@Nullable F first, @Nullable S second, int third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/BooleanFloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/BooleanFloatConsumer.java index b8e1a60a..7506b866 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/BooleanFloatConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/BooleanFloatConsumer.java @@ -8,11 +8,11 @@ @FunctionalInterface public interface BooleanFloatConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(boolean first, float second); + /** + * Accept. + * + * @param first the first + * @param second the second + */ + void accept(boolean first, float second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ByteFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ByteFunction.java index e94ca20d..f55dd45f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ByteFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ByteFunction.java @@ -6,5 +6,5 @@ @FunctionalInterface public interface ByteFunction { - R apply(byte value); + R apply(byte value); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/CharSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/CharSupplier.java index fe1aa82d..5a9d03bb 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/CharSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/CharSupplier.java @@ -3,8 +3,8 @@ import java.util.function.Supplier; /** - * Represents a supplier of {@code char}-valued results. This is the - * {@code char}-producing primitive specialization of {@link Supplier}. + * Represents a supplier of {@code char}-valued results. This is the {@code char}-producing primitive specialization of + * {@link Supplier}. * *

There is no requirement that a distinct result be returned each * time the supplier is invoked. @@ -12,17 +12,17 @@ *

This is a functional interface * whose functional method is {@link #getAsChar()}. * + * @author JavaSaBr * @see Supplier * @since 8.1.0 - * @author JavaSaBr */ @FunctionalInterface public interface CharSupplier { - /** - * Gets a result. - * - * @return a result - */ - char getAsChar(); + /** + * Gets a result. + * + * @return a result + */ + char getAsChar(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java index b72b354d..63ba38f3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface DoubleObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(double first, @Nullable T second); + /** + * Accept. + * + * @param first the first + * @param second the second + */ + void accept(double first, @Nullable T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java index 638d724d..369654ba 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java @@ -5,9 +5,9 @@ /** * The consumer with 5 arguments. * - * @param the type parameter - * @param the type parameter - * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param the type parameter * @param the type parameter * @param the type parameter * @author JavaSaBr @@ -15,14 +15,14 @@ @FunctionalInterface public interface FiveObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @param fourth the fourth - * @param five the five - */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FO fourth, @Nullable FI five); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + * @param fourth the fourth + * @param five the five + */ + void accept(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FO fourth, @Nullable FI five); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java index 4d4bd354..67aca096 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface FloatBiObjectConsumer { - void accept(float first, @Nullable S second, @Nullable T third); + void accept(float first, @Nullable S second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatConsumer.java index 717c1c42..91731171 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatConsumer.java @@ -8,10 +8,10 @@ @FunctionalInterface public interface FloatConsumer { - /** - * Consume the float value. - * - * @param value the value. - */ - void consume(float value); + /** + * Consume the float value. + * + * @param value the value. + */ + void consume(float value); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatFloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatFloatConsumer.java index 5f204f5b..ed44e770 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatFloatConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatFloatConsumer.java @@ -8,11 +8,11 @@ @FunctionalInterface public interface FloatFloatConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(float first, float second); + /** + * Accept. + * + * @param first the first + * @param second the second + */ + void accept(float first, float second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java index f4cd948f..27ea75e0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface FloatObjectConsumer { - /** - * Accept the two parameters. - * - * @param first the first. - * @param second the second. - */ - void accept(float first, @Nullable T second); + /** + * Accept the two parameters. + * + * @param first the first. + * @param second the second. + */ + void accept(float first, @Nullable T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java index 2ff59220..d2b2282c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java @@ -5,22 +5,22 @@ /** * The consumer with 4 arguments. * - * @param the type parameter - * @param the type parameter - * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param the type parameter * @param the type parameter * @author JavaSaBr */ @FunctionalInterface public interface FourObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @param fourth the fourth - */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FO fourth); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + * @param fourth the fourth + */ + void accept(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FO fourth); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java index 93406d50..a6a1be2d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface FunctionInt { - /** - * Apply int. - * - * @param first the first - * @return the int - */ - int apply(@Nullable T first); + /** + * Apply int. + * + * @param first the first + * @return the int + */ + int apply(@Nullable T first); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java b/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java index ff5f3362..04349775 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java @@ -6,64 +6,64 @@ public class Functions { - public static class Predicates { + public static class Predicates { - public static @NotNull Predicate isTrue() { + public static @NotNull Predicate isTrue() { - return bool -> bool; - } - - public static @NotNull Predicate ifTrue(@NotNull Runnable task) { + return bool -> bool; + } - return bool -> { + public static @NotNull Predicate ifTrue(@NotNull Runnable task) { - if (bool) { - task.run(); - } + return bool -> { - return true; - }; + if (bool) { + task.run(); } - public static @NotNull Predicate throwIfTrue(@NotNull Supplier factory) { + return true; + }; + } - return bool -> { + public static @NotNull Predicate throwIfTrue(@NotNull Supplier factory) { - if (bool) { - throw factory.get(); - } + return bool -> { - return true; - }; + if (bool) { + throw factory.get(); } - public static @NotNull Predicate isFalse() { + return true; + }; + } - return bool -> !bool; - } + public static @NotNull Predicate isFalse() { - public static @NotNull Predicate ifFalse(@NotNull Runnable task) { + return bool -> !bool; + } - return bool -> { + public static @NotNull Predicate ifFalse(@NotNull Runnable task) { - if (!bool) { - task.run(); - } + return bool -> { - return true; - }; + if (!bool) { + task.run(); } - public static @NotNull Predicate throwIfFalse(@NotNull Supplier factory) { + return true; + }; + } - return bool -> { + public static @NotNull Predicate throwIfFalse(@NotNull Supplier factory) { - if (!bool) { - throw factory.get(); - } + return bool -> { - return true; - }; + if (!bool) { + throw factory.get(); } + + return true; + }; } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java index 61c542c5..000e633a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java @@ -12,12 +12,12 @@ @FunctionalInterface public interface IntBiObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(int first, @Nullable S second, @Nullable T third); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + */ + void accept(int first, @Nullable S second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java index 56f63b53..3161ae2c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface IntObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(int first, @Nullable T second); + /** + * Accept. + * + * @param first the first + * @param second the second + */ + void accept(int first, @Nullable T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java index e196277f..d8467e12 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java @@ -11,12 +11,12 @@ @FunctionalInterface public interface IntObjectPredicate { - /** - * Test boolean. - * - * @param first the first - * @param second the second - * @return the boolean - */ - boolean test(int first, @Nullable T second); + /** + * Test boolean. + * + * @param first the first + * @param second the second + * @return the boolean + */ + boolean test(int first, @Nullable T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java index 7193af57..ee1428a6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java @@ -12,12 +12,12 @@ @FunctionalInterface public interface LongBiObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(long first, @Nullable S second, @Nullable T third); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + */ + void accept(long first, @Nullable S second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java index 9b8b3d30..b37ff04c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface LongObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(long first, @Nullable T second); + /** + * Accept. + * + * @param first the first + * @param second the second + */ + void accept(long first, @Nullable T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java index f18ab142..2b6626aa 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java @@ -11,12 +11,12 @@ @FunctionalInterface public interface LongObjectPredicate { - /** - * Test boolean. - * - * @param first the first - * @param second the second - * @return the boolean - */ - boolean test(long first, @Nullable T second); + /** + * Test boolean. + * + * @param first the first + * @param second the second + * @return the boolean + */ + boolean test(long first, @Nullable T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java index feeb93b6..6ba4801f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullBiConsumer extends BiConsumer { - @Override - void accept(@NotNull T first, @NotNull U second); + @Override + void accept(@NotNull T first, @NotNull U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java index 41e579b5..c5d27ca0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullBiFunction extends BiFunction { - @Override - @NotNull R apply(@NotNull T first, @NotNull U second); + @Override + @NotNull R apply(@NotNull T first, @NotNull U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java index 6e47c125..c84df536 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullBiPredicate extends BiPredicate { - @Override - boolean test(@NotNull T first, @NotNull U second); + @Override + boolean test(@NotNull T first, @NotNull U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java index 54810158..8e4ddf71 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullConsumer extends Consumer { - @Override - void accept(@NotNull T object); + @Override + void accept(@NotNull T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java index 820581d8..cd1a80e8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullFloatBiObjectConsumer extends FloatBiObjectConsumer { - @Override - void accept(float first, @NotNull S second, @NotNull T third); + @Override + void accept(float first, @NotNull S second, @NotNull T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java index a3c86aa8..832f09a6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullFunction extends Function { - @Override - @NotNull R apply(@NotNull T object); + @Override + @NotNull R apply(@NotNull T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java index 18ccb761..8b4e9aff 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java @@ -5,5 +5,5 @@ @FunctionalInterface public interface NotNullFunctionInt extends FunctionInt { - int apply(@NotNull T object); + int apply(@NotNull T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java index e13147d6..7558da83 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullIntBiObjectConsumer extends IntBiObjectConsumer { - @Override - void accept(int first, @NotNull S second, @NotNull T third); + @Override + void accept(int first, @NotNull S second, @NotNull T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java index 7a31dc65..624173da 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface NotNullIntObjectPredicate extends IntObjectPredicate { - boolean test(int first, @NotNull T second); + boolean test(int first, @NotNull T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java index 13710f63..4dd5a941 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullLongBiObjectConsumer extends LongBiObjectConsumer { - @Override - void accept(long first, @NotNull S second, @NotNull T third); + @Override + void accept(long first, @NotNull S second, @NotNull T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java index fb247f2f..8d82e019 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface NotNullLongObjectPredicate extends LongObjectPredicate { - boolean test(long first, @NotNull T second); + boolean test(long first, @NotNull T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java index 8cbd4046..5e5a4db2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java @@ -7,6 +7,6 @@ @FunctionalInterface public interface NotNullNullableBiFunction extends BiFunction { - @Override - @Nullable R apply(@NotNull T first, @NotNull U second); + @Override + @Nullable R apply(@NotNull T first, @NotNull U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java index 6c9aca2d..2de9055f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java @@ -7,6 +7,6 @@ @FunctionalInterface public interface NotNullNullableFunction extends Function { - @Override - @Nullable R apply(@NotNull T object); + @Override + @Nullable R apply(@NotNull T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java index 4ea80df9..17a66b66 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullNullableTripleFunction extends TripleFunction { - @Override - @Nullable R apply(@NotNull F first, @NotNull S second, @NotNull T third); + @Override + @Nullable R apply(@NotNull F first, @NotNull S second, @NotNull T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java index 5ba84d04..120eb47a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullObjectIntPredicate extends ObjectIntPredicate { - @Override - boolean test(@NotNull T first, int second); + @Override + boolean test(@NotNull T first, int second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java index 3b988b49..9c29c486 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java @@ -5,6 +5,6 @@ @FunctionalInterface public interface NotNullObjectLongPredicate extends ObjectLongPredicate { - @Override - boolean test(@NotNull T first, long second); + @Override + boolean test(@NotNull T first, long second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java index 19deca8f..bb3e23fd 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullPredicate extends Predicate { - @Override - boolean test(@NotNull T object); + @Override + boolean test(@NotNull T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java index 306e5178..8ea4a4fc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullSafeBiConsumer extends SafeBiConsumer { - @Override - void accept(@NotNull F first, @NotNull S second) throws Exception; + @Override + void accept(@NotNull F first, @NotNull S second) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java index 629dd26e..70c178f5 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java @@ -5,6 +5,6 @@ @FunctionalInterface public interface NotNullSafeBiFunction extends SafeBiFunction { - @Override - @NotNull R apply(@NotNull F first, @NotNull S second) throws Exception; + @Override + @NotNull R apply(@NotNull F first, @NotNull S second) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java index ac8550a2..89e8ca48 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullSafeConsumer extends SafeConsumer { - @Override - void accept(@NotNull T argument) throws Exception; + @Override + void accept(@NotNull T argument) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java index 46f352e9..b0dc9806 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullSafeFactory extends SafeFactory { - @Override - @NotNull R get() throws Exception; + @Override + @NotNull R get() throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java index b167ed4e..76098aba 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java @@ -5,6 +5,6 @@ @FunctionalInterface public interface NotNullSafeFunction extends SafeFunction { - @Override - @NotNull R apply(@NotNull F first) throws Exception; + @Override + @NotNull R apply(@NotNull F first) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java index 2e265ad2..779dc298 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullSafeSupplier extends SafeSupplier { - @Override - @NotNull T get() throws Exception; + @Override + @NotNull T get() throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java index c934b7a6..b5e78742 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java @@ -5,6 +5,6 @@ @FunctionalInterface public interface NotNullSafeTriFunction extends SafeTriFunction { - @Override - @NotNull R apply(@NotNull F first, @NotNull S second, @NotNull T third) throws Exception; + @Override + @NotNull R apply(@NotNull F first, @NotNull S second, @NotNull T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java index defee4f8..5bb6f8a7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NotNullSupplier extends Supplier { - @Override - @NotNull T get(); + @Override + @NotNull T get(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java index 6b85f458..dbd7aa95 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface NotNullTripleConsumer extends TripleConsumer { - @Override - void accept(@NotNull F first, @NotNull S second, @NotNull T third); + @Override + void accept(@NotNull F first, @NotNull S second, @NotNull T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java index 91a6c8e2..0e71330d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface NotNullTriplePredicate extends TriplePredicate { - boolean test(@NotNull F first, @NotNull S second, @NotNull T third); + boolean test(@NotNull F first, @NotNull S second, @NotNull T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java index 25bf8515..4c9d90d7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface NullableSupplier extends Supplier { - @Override - @Nullable T get(); + @Override + @Nullable T get(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java index 15646eff..7c8360cb 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface ObjectFloatConsumer { - /** - * Apply. - * - * @param first the first - * @param second the second - */ - void apply(@Nullable T first, float second); + /** + * Apply. + * + * @param first the first + * @param second the second + */ + void apply(@Nullable T first, float second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java index 03564de4..fd50016f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java @@ -12,13 +12,12 @@ @FunctionalInterface public interface ObjectFloatFunction { - /** - * Apply r. - * - * @param first the first - * @param second the second - * @return the r - */ - @Nullable - R apply(@Nullable T first, float second); + /** + * Apply r. + * + * @param first the first + * @param second the second + * @return the r + */ + @Nullable R apply(@Nullable T first, float second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java index e5352a46..482a7c0c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java @@ -12,12 +12,12 @@ @FunctionalInterface public interface ObjectFloatObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, float second, @Nullable T third); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + */ + void accept(@Nullable F first, float second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java index dcb6bc5b..40df9ffe 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface ObjectIntConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(@Nullable T first, int second); + /** + * Accept. + * + * @param first the first + * @param second the second + */ + void accept(@Nullable T first, int second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java index 37e488f1..31baace9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java @@ -12,13 +12,12 @@ @FunctionalInterface public interface ObjectIntFunction { - /** - * Apply r. - * - * @param first the first - * @param second the second - * @return the r - */ - @Nullable - R apply(@Nullable T first, int second); + /** + * Apply r. + * + * @param first the first + * @param second the second + * @return the r + */ + @Nullable R apply(@Nullable T first, int second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java index a5b83cda..7302bc9d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java @@ -12,12 +12,12 @@ @FunctionalInterface public interface ObjectIntObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, int second, @Nullable T third); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + */ + void accept(@Nullable F first, int second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java index dc57ac71..1d350bc0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java @@ -13,14 +13,13 @@ @FunctionalInterface public interface ObjectIntObjectFunction { - /** - * Apply r. - * - * @param first the first - * @param second the second - * @param third the third - * @return the r - */ - @Nullable - R apply(@Nullable F first, int second, @Nullable T third); + /** + * Apply r. + * + * @param first the first + * @param second the second + * @param third the third + * @return the r + */ + @Nullable R apply(@Nullable F first, int second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntPredicate.java index 7fe1ef96..a7dfdc1e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntPredicate.java @@ -6,5 +6,5 @@ @FunctionalInterface public interface ObjectIntPredicate { - boolean test(T first, int second); + boolean test(T first, int second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java index 49fa8e33..552cd2db 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java @@ -11,11 +11,11 @@ @FunctionalInterface public interface ObjectLongConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(@Nullable T first, long second); + /** + * Accept. + * + * @param first the first + * @param second the second + */ + void accept(@Nullable T first, long second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongFunction.java index 1e2df145..c2df2f99 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongFunction.java @@ -10,12 +10,12 @@ @FunctionalInterface public interface ObjectLongFunction { - /** - * Apply r. - * - * @param first the first - * @param second the second - * @return the r - */ - R apply(T first, long second); + /** + * Apply r. + * + * @param first the first + * @param second the second + * @return the r + */ + R apply(T first, long second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java index 05562471..8aede10c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java @@ -12,12 +12,12 @@ @FunctionalInterface public interface ObjectLongObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, long second, @Nullable T third); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + */ + void accept(@Nullable F first, long second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java index 356bd9ad..1d8e807a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java @@ -11,12 +11,12 @@ @FunctionalInterface public interface ObjectLongPredicate { - /** - * Test boolean. - * - * @param first the first - * @param second the second - * @return the boolean - */ - boolean test(@Nullable T first, long second); + /** + * Test boolean. + * + * @param first the first + * @param second the second + * @return the boolean + */ + boolean test(@Nullable T first, long second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java index 1fdff695..2c16bc94 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface SafeBiConsumer { - void accept(@Nullable F first, @Nullable S second) throws Exception; + void accept(@Nullable F first, @Nullable S second) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java index a363455e..4919d0b2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java @@ -5,5 +5,5 @@ @FunctionalInterface public interface SafeBiFunction { - @Nullable R apply(@Nullable F first, @Nullable S second) throws Exception; + @Nullable R apply(@Nullable F first, @Nullable S second) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java index 277a900f..cf2915c1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface SafeConsumer { - void accept(@Nullable T argument) throws Exception; + void accept(@Nullable T argument) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java index da4394a7..bda4b325 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface SafeFactory { - @Nullable R get() throws Exception; + @Nullable R get() throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java index b06bad5f..7639cf9f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java @@ -5,5 +5,5 @@ @FunctionalInterface public interface SafeFunction { - @Nullable R apply(@Nullable F first) throws Exception; + @Nullable R apply(@Nullable F first) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeRunnable.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeRunnable.java index fdad197c..20aafe97 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeRunnable.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeRunnable.java @@ -8,10 +8,10 @@ @FunctionalInterface public interface SafeRunnable { - /** - * Run. - * - * @throws Exception the exception - */ - void run() throws Exception; + /** + * Run. + * + * @throws Exception the exception + */ + void run() throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java index e7e20b0e..a0dcf98f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java @@ -8,5 +8,5 @@ @FunctionalInterface public interface SafeSupplier { - @Nullable T get() throws Exception; + @Nullable T get() throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java index 4f51e64b..7100bcf2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java @@ -5,5 +5,5 @@ @FunctionalInterface public interface SafeTriFunction { - @Nullable R apply(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; + @Nullable R apply(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java index aec05934..3e3e2d1d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java @@ -13,13 +13,13 @@ @FunctionalInterface public interface SafeTripleConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @throws Exception the exception - */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + * @throws Exception the exception + */ + void accept(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java index a6304cec..98b87998 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java @@ -14,15 +14,14 @@ @FunctionalInterface public interface SafeTripleFunction { - /** - * Apply r. - * - * @param first the first - * @param second the second - * @param third the third - * @return the r - * @throws Exception the exception - */ - @Nullable - R apply(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; + /** + * Apply r. + * + * @param first the first + * @param second the second + * @param third the third + * @return the r + * @throws Exception the exception + */ + @Nullable R apply(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java index 948c26e4..61a93b1c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java @@ -5,9 +5,9 @@ /** * The consumer with 5 arguments. * - * @param the type parameter - * @param the type parameter - * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param the type parameter * @param the type parameter * @param the type parameter * @param the type parameter @@ -16,16 +16,21 @@ @FunctionalInterface public interface SixObjectConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @param fourth the fourth - * @param five the five - * @param six the six - */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FO fourth, - @Nullable FI five, @Nullable SX six); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + * @param fourth the fourth + * @param five the five + * @param six the six + */ + void accept( + @Nullable F first, + @Nullable S second, + @Nullable T third, + @Nullable FO fourth, + @Nullable FI five, + @Nullable SX six); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java index b3bce91d..257012ba 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java @@ -13,12 +13,12 @@ @FunctionalInterface public interface TripleConsumer { - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third); + /** + * Accept. + * + * @param first the first + * @param second the second + * @param third the third + */ + void accept(@Nullable F first, @Nullable S second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java index bfe2ed6f..1d23b57f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java @@ -14,14 +14,13 @@ @FunctionalInterface public interface TripleFunction { - /** - * Apply r. - * - * @param first the first - * @param second the second - * @param third the third - * @return the r - */ - @Nullable - R apply(@Nullable F first, @Nullable S second, @Nullable T third); + /** + * Apply r. + * + * @param first the first + * @param second the second + * @param third the third + * @return the r + */ + @Nullable R apply(@Nullable F first, @Nullable S second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java index 43ff29b3..345bf7d9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java @@ -13,13 +13,13 @@ @FunctionalInterface public interface TriplePredicate { - /** - * Test boolean. - * - * @param first the first - * @param second the second - * @param third the third - * @return the boolean - */ - boolean test(@Nullable F first, @Nullable S second, @Nullable T third); + /** + * Test boolean. + * + * @param first the first + * @param second the second + * @param third the third + * @return the boolean + */ + boolean test(@Nullable F first, @Nullable S second, @Nullable T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/DirectionType.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/DirectionType.java index 9e6ed026..076be43d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/DirectionType.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/DirectionType.java @@ -6,28 +6,28 @@ * @author JavaSaBr */ public enum DirectionType { - /** - * Left direction type. - */ - LEFT, - /** - * Up direction type. - */ - UP, - /** - * Front direction type. - */ - FRONT, - /** - * Right direction type. - */ - RIGHT, - /** - * Down direction type. - */ - DOWN, - /** - * Behind direction type. - */ - BEHIND + /** + * Left direction type. + */ + LEFT, + /** + * Up direction type. + */ + UP, + /** + * Front direction type. + */ + FRONT, + /** + * Right direction type. + */ + RIGHT, + /** + * Down direction type. + */ + DOWN, + /** + * Behind direction type. + */ + BEHIND } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Matrix3f.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Matrix3f.java index 280a79ab..8a876261 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Matrix3f.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Matrix3f.java @@ -1,141 +1,148 @@ package javasabr.rlib.common.geom; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of float matrix 3x3. * * @author JavaSaBr */ +@NullMarked public final class Matrix3f implements Reusable { - public static final Matrix3f ZERO = new Matrix3f( - 0, 0, 0, - 0, 0, 0, - 0, 0, 0 - ); - - public static final Matrix3f IDENTITY = new Matrix3f(); - - /** - * Values. - */ - protected float val_0_0, val_0_1, val_0_2; - protected float val_1_0, val_1_1, val_1_2; - protected float val_2_0, val_2_1, val_2_2; - - public Matrix3f() { - val_0_1 = val_0_2 = val_1_0 = val_1_2 = val_2_0 = val_2_1 = 0; - val_0_0 = val_1_1 = val_2_2 = 1; - } - - public Matrix3f(@NotNull Matrix3f matrix) { - this(matrix.val_0_0, matrix.val_0_1, matrix.val_0_2, - matrix.val_1_0, matrix.val_1_1, matrix.val_1_2, - matrix.val_2_0, matrix.val_2_1, matrix.val_2_2); - } - - public Matrix3f( - float val_0_0, - float val_0_1, - float val_0_2, - float val_1_0, - float val_1_1, - float val_1_2, - float val_2_0, - float val_2_1, - float val_2_2 - ) { - this.val_0_0 = val_0_0; - this.val_0_1 = val_0_1; - this.val_0_2 = val_0_2; - this.val_1_0 = val_1_0; - this.val_1_1 = val_1_1; - this.val_1_2 = val_1_2; - this.val_2_0 = val_2_0; - this.val_2_1 = val_2_1; - this.val_2_2 = val_2_2; - } - - /** - * Change all values to absolute. - */ - public void absoluteLocal() { - val_0_0 = Math.abs(val_0_0); - val_0_1 = Math.abs(val_0_1); - val_0_2 = Math.abs(val_0_2); - val_1_0 = Math.abs(val_1_0); - val_1_1 = Math.abs(val_1_1); - val_1_2 = Math.abs(val_1_2); - val_2_0 = Math.abs(val_2_0); - val_2_1 = Math.abs(val_2_1); - val_2_2 = Math.abs(val_2_2); - } - - /** - * Multiply the vector by this matrix. - * - * @param vector the source vector. - * @param result the result vector. - * @return the result. - */ - public @NotNull Vector3f mult(@NotNull Vector3f vector, @NotNull Vector3f result) { - - float x = vector.x; - float y = vector.y; - float z = vector.z; - - result.x = val_0_0 * x + val_0_1 * y + val_0_2 * z; - result.y = val_1_0 * x + val_1_1 * y + val_1_2 * z; - result.z = val_2_0 * x + val_2_1 * y + val_2_2 * z; - - return result; - } - - /** - * Set the matrix values. - * - * @param val_0_0 the val 0 0 - * @param val_0_1 the val 0 1 - * @param val_0_2 the val 0 2 - * @param val_1_0 the val 1 0 - * @param val_1_1 the val 1 1 - * @param val_1_2 the val 1 2 - * @param val_2_0 the val 2 0 - * @param val_2_1 the val 2 1 - * @param val_2_2 the val 2 2 - */ - public void set( - float val_0_0, float val_0_1, float val_0_2, - float val_1_0, float val_1_1, float val_1_2, - float val_2_0, float val_2_1, float val_2_2 - ) { - this.val_0_0 = val_0_0; - this.val_0_1 = val_0_1; - this.val_0_2 = val_0_2; - this.val_1_0 = val_1_0; - this.val_1_1 = val_1_1; - this.val_1_2 = val_1_2; - this.val_2_0 = val_2_0; - this.val_2_1 = val_2_1; - this.val_2_2 = val_2_2; - } - - /** - * Set values from the rotation. - * - * @param rotation the rotation. - * @return this updated matrix. - */ - public @NotNull Matrix3f set(@NotNull Quaternion4f rotation) { - return rotation.toRotationMatrix(this); - } - - @Override - public String toString() { - return val_0_0 + ", " + val_0_1 + ", " + val_0_2 + "\n" + - val_1_0 + ", " + val_1_1 + ", " + val_1_2 + "\n" + - val_2_0 + ", " + val_2_1 + ", " + val_2_2 + "\n"; - } + public static final Matrix3f ZERO = new Matrix3f(0, 0, 0, 0, 0, 0, 0, 0, 0); + + public static final Matrix3f IDENTITY = new Matrix3f(); + + /** + * Values. + */ + protected float val_0_0, val_0_1, val_0_2; + protected float val_1_0, val_1_1, val_1_2; + protected float val_2_0, val_2_1, val_2_2; + + public Matrix3f() { + val_0_1 = val_0_2 = val_1_0 = val_1_2 = val_2_0 = val_2_1 = 0; + val_0_0 = val_1_1 = val_2_2 = 1; + } + + public Matrix3f(Matrix3f matrix) { + this( + matrix.val_0_0, + matrix.val_0_1, + matrix.val_0_2, + matrix.val_1_0, + matrix.val_1_1, + matrix.val_1_2, + matrix.val_2_0, + matrix.val_2_1, + matrix.val_2_2); + } + + public Matrix3f( + float val_0_0, + float val_0_1, + float val_0_2, + float val_1_0, + float val_1_1, + float val_1_2, + float val_2_0, + float val_2_1, + float val_2_2) { + this.val_0_0 = val_0_0; + this.val_0_1 = val_0_1; + this.val_0_2 = val_0_2; + this.val_1_0 = val_1_0; + this.val_1_1 = val_1_1; + this.val_1_2 = val_1_2; + this.val_2_0 = val_2_0; + this.val_2_1 = val_2_1; + this.val_2_2 = val_2_2; + } + + /** + * Change all values to absolute. + */ + public void absoluteLocal() { + val_0_0 = Math.abs(val_0_0); + val_0_1 = Math.abs(val_0_1); + val_0_2 = Math.abs(val_0_2); + val_1_0 = Math.abs(val_1_0); + val_1_1 = Math.abs(val_1_1); + val_1_2 = Math.abs(val_1_2); + val_2_0 = Math.abs(val_2_0); + val_2_1 = Math.abs(val_2_1); + val_2_2 = Math.abs(val_2_2); + } + + /** + * Multiply the vector by this matrix. + * + * @param vector the source vector. + * @param result the result vector. + * @return the result. + */ + public Vector3f mult(Vector3f vector, Vector3f result) { + + float x = vector.x; + float y = vector.y; + float z = vector.z; + + result.x = val_0_0 * x + val_0_1 * y + val_0_2 * z; + result.y = val_1_0 * x + val_1_1 * y + val_1_2 * z; + result.z = val_2_0 * x + val_2_1 * y + val_2_2 * z; + + return result; + } + + /** + * Set the matrix values. + * + * @param val_0_0 the val 0 0 + * @param val_0_1 the val 0 1 + * @param val_0_2 the val 0 2 + * @param val_1_0 the val 1 0 + * @param val_1_1 the val 1 1 + * @param val_1_2 the val 1 2 + * @param val_2_0 the val 2 0 + * @param val_2_1 the val 2 1 + * @param val_2_2 the val 2 2 + */ + public void set( + float val_0_0, + float val_0_1, + float val_0_2, + float val_1_0, + float val_1_1, + float val_1_2, + float val_2_0, + float val_2_1, + float val_2_2) { + this.val_0_0 = val_0_0; + this.val_0_1 = val_0_1; + this.val_0_2 = val_0_2; + this.val_1_0 = val_1_0; + this.val_1_1 = val_1_1; + this.val_1_2 = val_1_2; + this.val_2_0 = val_2_0; + this.val_2_1 = val_2_1; + this.val_2_2 = val_2_2; + } + + /** + * Set values from the rotation. + * + * @param rotation the rotation. + * @return this updated matrix. + */ + public Matrix3f set(Quaternion4f rotation) { + return rotation.toRotationMatrix(this); + } + + @Override + public String toString() { + return val_0_0 + ", " + val_0_1 + ", " + val_0_2 + "\n" + val_1_0 + ", " + val_1_1 + ", " + val_1_2 + "\n" + val_2_0 + + ", " + val_2_1 + ", " + val_2_2 + "\n"; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Plane.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Plane.java index a93ddb89..a2c695fc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Plane.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Plane.java @@ -3,514 +3,505 @@ import static javasabr.rlib.common.geom.Vector3f.substract; import javasabr.rlib.common.util.ExtMath; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * Geometry 3D plane.
- * Follow to the formula:

Ax + By + Cz + D = 0
+ * Geometry 3D plane.
Follow to the formula:
Ax + By + Cz + D = 0
* * @author zcxv */ +@NullMarked public class Plane { - /** - * The plane normal - */ - @NotNull - private final Vector3f normal; - - /** - * The D component, inverted by sign. - */ - private float d; - - public Plane(@NotNull Vector3f first, @NotNull Vector3f second, @NotNull Vector3f third) { - - var ba = substract(second, first); - var ca = substract(third, first); - - normal = ba.cross(ca).normalizeLocal(); - - this.d = first.dot(normal); - } - - public Plane(@NotNull Vector3f planePoint, @NotNull Vector3f normal) { - this.normal = normal.clone(); - this.d = planePoint.dot(normal); - } - - /** - * Return a plane normal. - * - * @return normal. - */ - public @NotNull Vector3f getNormal() { - return normal; - } - - /** - * Return a D component inverted by sign. - * - * @return the D component. - */ - public float getD() { - return d; - } - - /** - * Multiply plane by scalar. - * - * @param scalar scalar. - * @return this plane. - */ - public @NotNull Plane multLocal(float scalar) { - normal.multLocal(scalar); - d *= scalar; - return this; - } - - /** - * Divide plane by scalar. - * - * @param scalar scalar. - * @return this plane . - */ - public @NotNull Plane divideLocal(float scalar) { - normal.divideLocal(scalar); - d /= scalar; - return this; - } - - /** - * Add values to plane. - * - * @param x the X axis value. - * @param y the Y axis value. - * @param z the Z axis value. - * @param d the D component. - * @return this plane . - */ - public @NotNull Plane addLocal(float x, float y, float z, float d) { - normal.addLocal(x, y, z); - this.d += d; - return this; - } - - /** - * Subtract values to plane. - * - * @param x the X axis value. - * @param y the Y axis value. - * @param z the Z axis value. - * @param d the D component. - * @return this plane. - */ - public @NotNull Plane subtractLocal(float x, float y, float z, float d) { - normal.subtractLocal(x, y, z); - this.d -= d; - return this; - } - - /** - * Multiply plane by other plane. - * - * @param plane the other plane. - * @return this plane . - */ - public @NotNull Plane multLocal(@NotNull Plane plane) { - normal.multLocal(plane.normal); - d *= plane.d; - return this; - } - - /** - * Divide plane by other plane. - * - * @param plane the other plane. - * @return this plane . - */ - public @NotNull Plane divideLocal(@NotNull Plane plane) { - normal.divideLocal(plane.normal); - d /= plane.d; - return this; - } - - /** - * Add plane by other plane. - * - * @param plane the other plane. - * @return this plane - */ - public @NotNull Plane addLocal(@NotNull Plane plane) { - normal.addLocal(plane.normal); - d += plane.d; - return this; - } - - /** - * Subtract plane by other plane. - * - * @param plane the other plane - * @return this plane - */ - public @NotNull Plane subtractLocal(@NotNull Plane plane) { - normal.subtractLocal(plane.normal); - d -= plane.d; - return this; - } - - /** - * Multiply plane by vector.
- * Its operation is equals to multiply plane normal vector with vector. - * - * @param vector the vector. - * @return this plane. - */ - public @NotNull Plane multLocal(@NotNull Vector3f vector) { - normal.multLocal(vector); - return this; - } - - /** - * Divide plane by vector.
- * Its operation is equals to divide plane normal vector with vector. - * - * @param vector the vector. - * @return this plane . - */ - public @NotNull Plane divideLocal(@NotNull Vector3f vector) { - normal.divideLocal(vector); - return this; - } - - /** - * Add plane by vector.
- * Its operation is equals to: plane normal plus vector. - * - * @param vector the vector. - * @return this plane. - */ - public @NotNull Plane addLocal(@NotNull Vector3f vector) { - normal.addLocal(vector); - return this; - } - - /** - * Subtract plane by vector.
- * Its operation is equals to: plane normal minus vector. - * - * @param vector the vector. - * @return this plane. - */ - public @NotNull Plane subtractLocal(@NotNull Vector3f vector) { - normal.subtractLocal(vector); - return this; - } - - /** - * Dot product plane with vector. - * - * @param point vector - * @return dot product - */ - public float dot(@NotNull Vector3f point) { - return normal.dot(point) - d; - } - - /** - * Dot product plane with plane. - * - * @param plane plane - * @return dot product - */ - public float dot(@NotNull Plane plane) { - return normal.dot(plane.normal) - d * plane.d; - } - - /** - * Distance between the point and the plane. - * - * @param point the point. - * @param planePoint the plane point. - * @return the distance. - */ - public float distance(@NotNull Vector3f point, @NotNull Vector3f planePoint) { - return distance(point, planePoint, Vector3fBuffer.NO_REUSE); - } - - /** - * Distance between the point and the plane. - * - * @param point the point. - * @param planePoint the plane point. - * @param buffer the vector's buffer. - * @return the distance. - */ - public float distance(@NotNull Vector3f point, @NotNull Vector3f planePoint, @NotNull Vector3fBuffer buffer) { - return buffer.next(point) - .subtractLocal(planePoint) - .dot(normal); - } - - /** - * Distance between point and plane. - * - * @param point point - * @return distance - */ - public float distance(@NotNull Vector3f point) { - return -d + point.dot(normal); - } - - /** - * Angle between planes. - * - * @param plane plane - * @return angle in radians - */ - public float angle(@NotNull Plane plane) { - return ExtMath.cos(normal.dot(plane.normal) / - ExtMath.sqrt(normal.sqrLength() * plane.normal.sqrLength())); - } - - /** - * Return true if the planes are parallel. - * - * @param plane the plane. - * @param epsilon the epsilon. - * @return true if the planes are parallel. - */ - public boolean isParallel(@NotNull Plane plane, float epsilon) { - - // check plane normals to collinearity - var fA = plane.normal.getX() / normal.getX(); - var fB = plane.normal.getY() / normal.getY(); - var fC = plane.normal.getZ() / normal.getZ(); - - return Math.abs(fA - fB) < epsilon && Math.abs(fA - fC) < epsilon; - } - - /** - * Return true if the planes are perpendicular. - * - * @param plane the plane. - * @param epsilon the epsilon. - * @return true if the planes are perpendicular. - */ - public boolean isPerpendicular(@NotNull Plane plane, float epsilon) { - return Math.abs(normal.dot(plane.normal)) < epsilon; - } - - /** - * Ray-plane intersection. Return point where ray intersect plane.
- * This method doesn't check plane-vector collinearity! - * - * @param startPoint the start point. - * @param endPoint the end point. - * @return the intersection point. - */ - public @NotNull Vector3f rayIntersection(@NotNull Vector3f startPoint, @NotNull Vector3f endPoint) { - return rayIntersection(startPoint, endPoint, Vector3fBuffer.NO_REUSE); - } - - /** - * Ray-plane intersection. Return point where ray intersect plane.
- * This method doesn't check plane-vector collinearity! - * - * @param startPoint the start point. - * @param endPoint the end point. - * @param buffer the vector's buffer. - * @return the intersection point. - */ - public @NotNull Vector3f rayIntersection( - @NotNull Vector3f startPoint, - @NotNull Vector3f endPoint, - @NotNull Vector3fBuffer buffer - ) { - - var direction = buffer.next(endPoint); - direction.subtractLocal(startPoint); - - var denominator = direction.dot(normal); - var distance = (d - startPoint.dot(normal)) / denominator; - - direction.multLocal(distance); - - return new Vector3f(startPoint) - .addLocal(direction); - } - - /** - * Ray-plane intersection. Return point where ray intersect plane.
- * This method doesn't check plane-vector collinearity! - * - * @param startPoint the start point. - * @param endPoint the end point. - * @return the intersection point. - */ - public @NotNull Vector3f rayIntersection( - @NotNull Vector3f startPoint, - @NotNull Vector3f endPoint, - @NotNull Vector3f planePoint - ) { - return rayIntersection(startPoint, endPoint, planePoint, Vector3fBuffer.NO_REUSE); - } - - /** - * Ray-plane intersection. Return point where ray intersect plane.
- * This method doesn't check plane-vector collinearity! - * - * @param startPoint the start point. - * @param endPoint the end point. - * @param buffer the vector's buffer. - * @return the intersection point. - */ - public @NotNull Vector3f rayIntersection( - @NotNull Vector3f startPoint, - @NotNull Vector3f endPoint, - @NotNull Vector3f planePoint, - @NotNull Vector3fBuffer buffer - ) { - - var direction = buffer.next(endPoint) - .subtractLocal(startPoint); - - var denominator = direction.dot(normal); - var distance = buffer.next(planePoint) - .subtractLocal(startPoint) - .dot(normal) / denominator; - - direction.multLocal(distance); - - return new Vector3f(startPoint) - .addLocal(direction); - } - - /** - * Ray-plane intersection. Return point where ray intersect plane.
- * This method doesn't check plane-vector collinearity! - * - * @param ray the ray. - * @return the intersection point. - */ - public @NotNull Vector3f rayIntersection(@NotNull Ray3f ray) { - return rayIntersection(ray, Vector3fBuffer.NO_REUSE); - } - - /** - * Ray-plane intersection. Return point where ray intersect plane.
- * This method doesn't check plane-vector collinearity! - * - * @param ray the ray. - * @param buffer the vector's buffer. - * @return the intersection point. - */ - public @NotNull Vector3f rayIntersection(@NotNull Ray3f ray, @NotNull Vector3fBuffer buffer) { - - var direction = ray.getDirection(); - var start = ray.getStart(); - - var denominator = direction.dot(normal); - var distance = (d - start.dot(normal)) / denominator; - - var add = buffer.next(direction); - add.multLocal(distance); - - return new Vector3f(start) - .addLocal(add); - } - - /** - * Line-plane (segment-plane) intersection. Return point where line intersect plane.
- * If line and plane is parallel or lines doesn't intersect plane return {@link Vector3f#POSITIVE_INFINITY} const. - * - * @param startPoint the line start point. - * @param secondPoint the line end point. - * @return intersection point or {@link Vector3f#POSITIVE_INFINITY} - */ - public @NotNull Vector3f lineIntersection(@NotNull Vector3f startPoint, @NotNull Vector3f secondPoint) { - return lineIntersection(startPoint, secondPoint, Vector3fBuffer.NO_REUSE); - } - - /** - * Line-plane (segment-plane) intersection. Return point where line intersect plane.
- * If line and plane is parallel or lines doesn't intersect plane return {@link Vector3f#POSITIVE_INFINITY} const. - * - * @param startPoint the line start point. - * @param secondPoint the line end point. - * @param buffer the vector's buffer. - * @return intersection point or {@link Vector3f#POSITIVE_INFINITY} - */ - public @NotNull Vector3f lineIntersection( - @NotNull Vector3f startPoint, - @NotNull Vector3f secondPoint, - @NotNull Vector3fBuffer buffer - ) { - - var ab = buffer.next(secondPoint); - ab.subtractLocal(startPoint); - - var t = (d - normal.dot(startPoint)) / normal.dot(ab); - - if (t < 0 || t > 1.f) { - return Vector3f.POSITIVE_INFINITY; - } - - return new Vector3f(startPoint) - .addLocal(ab.multLocal(t)); - } - - /** - * Plane-plane intersection. Return point where planes intersects.
- * If planes is parallel return {@link Vector3f#POSITIVE_INFINITY} const. - * - * @param plane the plane. - * @param epsilon the epsilon. - * @return the intersection point or copy of {@link Vector3f#POSITIVE_INFINITY}. - */ - public @NotNull Vector3f planeIntersection(@NotNull Plane plane, float epsilon) { - return planeIntersection(plane, epsilon, Vector3fBuffer.NO_REUSE); - } - - /** - * Plane-plane intersection. Return point where planes intersects.
- * If planes is parallel return {@link Vector3f#POSITIVE_INFINITY} const. - * - * @param plane the plane. - * @param epsilon the epsilon. - * @param buffer the vector's buffer. - * @return the intersection point or {@link Vector3f#POSITIVE_INFINITY}. - */ - public @NotNull Vector3f planeIntersection(@NotNull Plane plane, float epsilon, @NotNull Vector3fBuffer buffer) { - - var direction = normal.cross(plane.normal, buffer.nextVector()); - var denominator = direction.dot(direction); - - if (denominator < epsilon) { - // these planes are parallel - return Vector3f.POSITIVE_INFINITY; - } - - return new Vector3f(plane.normal) - .multLocal(d) - .subtractLocal(buffer.next(normal).multLocal(plane.d)) - .crossLocal(direction) - .divideLocal(denominator); - } - - /** {@inheritDoc} */ - @Override - public int hashCode() { - int prime = 31; - int result = 1; - result = prime * result + normal.hashCode(); - result = prime * result + Float.floatToIntBits(d); - return result; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Plane{normal=" + normal + ", d=" + d + "}"; - } + /** + * The plane normal + */ + private final Vector3f normal; + + /** + * The D component, inverted by sign. + */ + private float d; + + public Plane(Vector3f first, Vector3f second, Vector3f third) { + + var ba = substract(second, first); + var ca = substract(third, first); + + normal = ba + .cross(ca) + .normalizeLocal(); + + this.d = first.dot(normal); + } + + public Plane(Vector3f planePoint, Vector3f normal) { + this.normal = normal.clone(); + this.d = planePoint.dot(normal); + } + + /** + * Return a plane normal. + * + * @return normal. + */ + public Vector3f getNormal() { + return normal; + } + + /** + * Return a D component inverted by sign. + * + * @return the D component. + */ + public float getD() { + return d; + } + + /** + * Multiply plane by scalar. + * + * @param scalar scalar. + * @return this plane. + */ + public Plane multLocal(float scalar) { + normal.multLocal(scalar); + d *= scalar; + return this; + } + + /** + * Divide plane by scalar. + * + * @param scalar scalar. + * @return this plane . + */ + public Plane divideLocal(float scalar) { + normal.divideLocal(scalar); + d /= scalar; + return this; + } + + /** + * Add values to plane. + * + * @param x the X axis value. + * @param y the Y axis value. + * @param z the Z axis value. + * @param d the D component. + * @return this plane . + */ + public Plane addLocal(float x, float y, float z, float d) { + normal.addLocal(x, y, z); + this.d += d; + return this; + } + + /** + * Subtract values to plane. + * + * @param x the X axis value. + * @param y the Y axis value. + * @param z the Z axis value. + * @param d the D component. + * @return this plane. + */ + public Plane subtractLocal(float x, float y, float z, float d) { + normal.subtractLocal(x, y, z); + this.d -= d; + return this; + } + + /** + * Multiply plane by other plane. + * + * @param plane the other plane. + * @return this plane . + */ + public Plane multLocal(Plane plane) { + normal.multLocal(plane.normal); + d *= plane.d; + return this; + } + + /** + * Divide plane by other plane. + * + * @param plane the other plane. + * @return this plane . + */ + public Plane divideLocal(Plane plane) { + normal.divideLocal(plane.normal); + d /= plane.d; + return this; + } + + /** + * Add plane by other plane. + * + * @param plane the other plane. + * @return this plane + */ + public Plane addLocal(Plane plane) { + normal.addLocal(plane.normal); + d += plane.d; + return this; + } + + /** + * Subtract plane by other plane. + * + * @param plane the other plane + * @return this plane + */ + public Plane subtractLocal(Plane plane) { + normal.subtractLocal(plane.normal); + d -= plane.d; + return this; + } + + /** + * Multiply plane by vector.
Its operation is equals to multiply plane normal vector with vector. + * + * @param vector the vector. + * @return this plane. + */ + public Plane multLocal(Vector3f vector) { + normal.multLocal(vector); + return this; + } + + /** + * Divide plane by vector.
Its operation is equals to divide plane normal vector with vector. + * + * @param vector the vector. + * @return this plane . + */ + public Plane divideLocal(Vector3f vector) { + normal.divideLocal(vector); + return this; + } + + /** + * Add plane by vector.
Its operation is equals to: plane normal plus vector. + * + * @param vector the vector. + * @return this plane. + */ + public Plane addLocal(Vector3f vector) { + normal.addLocal(vector); + return this; + } + + /** + * Subtract plane by vector.
Its operation is equals to: plane normal minus vector. + * + * @param vector the vector. + * @return this plane. + */ + public Plane subtractLocal(Vector3f vector) { + normal.subtractLocal(vector); + return this; + } + + /** + * Dot product plane with vector. + * + * @param point vector + * @return dot product + */ + public float dot(Vector3f point) { + return normal.dot(point) - d; + } + + /** + * Dot product plane with plane. + * + * @param plane plane + * @return dot product + */ + public float dot(Plane plane) { + return normal.dot(plane.normal) - d * plane.d; + } + + /** + * Distance between the point and the plane. + * + * @param point the point. + * @param planePoint the plane point. + * @return the distance. + */ + public float distance(Vector3f point, Vector3f planePoint) { + return distance(point, planePoint, Vector3fBuffer.NO_REUSE); + } + + /** + * Distance between the point and the plane. + * + * @param point the point. + * @param planePoint the plane point. + * @param buffer the vector's buffer. + * @return the distance. + */ + public float distance(Vector3f point, Vector3f planePoint, Vector3fBuffer buffer) { + return buffer + .next(point) + .subtractLocal(planePoint) + .dot(normal); + } + + /** + * Distance between point and plane. + * + * @param point point + * @return distance + */ + public float distance(Vector3f point) { + return -d + point.dot(normal); + } + + /** + * Angle between planes. + * + * @param plane plane + * @return angle in radians + */ + public float angle(Plane plane) { + return ExtMath.cos(normal.dot(plane.normal) / ExtMath.sqrt(normal.sqrLength() * plane.normal.sqrLength())); + } + + /** + * Return true if the planes are parallel. + * + * @param plane the plane. + * @param epsilon the epsilon. + * @return true if the planes are parallel. + */ + public boolean isParallel(Plane plane, float epsilon) { + + // check plane normals to collinearity + var fA = plane.normal.getX() / normal.getX(); + var fB = plane.normal.getY() / normal.getY(); + var fC = plane.normal.getZ() / normal.getZ(); + + return Math.abs(fA - fB) < epsilon && Math.abs(fA - fC) < epsilon; + } + + /** + * Return true if the planes are perpendicular. + * + * @param plane the plane. + * @param epsilon the epsilon. + * @return true if the planes are perpendicular. + */ + public boolean isPerpendicular(Plane plane, float epsilon) { + return Math.abs(normal.dot(plane.normal)) < epsilon; + } + + /** + * Ray-plane intersection. Return point where ray intersect plane.
+ * This method doesn't check plane-vector collinearity! + * + * @param startPoint the start point. + * @param endPoint the end point. + * @return the intersection point. + */ + public Vector3f rayIntersection(Vector3f startPoint, Vector3f endPoint) { + return rayIntersection(startPoint, endPoint, Vector3fBuffer.NO_REUSE); + } + + /** + * Ray-plane intersection. Return point where ray intersect plane.
+ * This method doesn't check plane-vector collinearity! + * + * @param startPoint the start point. + * @param endPoint the end point. + * @param buffer the vector's buffer. + * @return the intersection point. + */ + public Vector3f rayIntersection(Vector3f startPoint, Vector3f endPoint, Vector3fBuffer buffer) { + + var direction = buffer.next(endPoint); + direction.subtractLocal(startPoint); + + var denominator = direction.dot(normal); + var distance = (d - startPoint.dot(normal)) / denominator; + + direction.multLocal(distance); + + return new Vector3f(startPoint).addLocal(direction); + } + + /** + * Ray-plane intersection. Return point where ray intersect plane.
+ * This method doesn't check plane-vector collinearity! + * + * @param startPoint the start point. + * @param endPoint the end point. + * @return the intersection point. + */ + public Vector3f rayIntersection(Vector3f startPoint, Vector3f endPoint, Vector3f planePoint) { + return rayIntersection(startPoint, endPoint, planePoint, Vector3fBuffer.NO_REUSE); + } + + /** + * Ray-plane intersection. Return point where ray intersect plane.
+ * This method doesn't check plane-vector collinearity! + * + * @param startPoint the start point. + * @param endPoint the end point. + * @param buffer the vector's buffer. + * @return the intersection point. + */ + public Vector3f rayIntersection( + Vector3f startPoint, + Vector3f endPoint, + Vector3f planePoint, + Vector3fBuffer buffer) { + + var direction = buffer + .next(endPoint) + .subtractLocal(startPoint); + + var denominator = direction.dot(normal); + var distance = buffer + .next(planePoint) + .subtractLocal(startPoint) + .dot(normal) / denominator; + + direction.multLocal(distance); + + return new Vector3f(startPoint).addLocal(direction); + } + + /** + * Ray-plane intersection. Return point where ray intersect plane.
+ * This method doesn't check plane-vector collinearity! + * + * @param ray the ray. + * @return the intersection point. + */ + public Vector3f rayIntersection(Ray3f ray) { + return rayIntersection(ray, Vector3fBuffer.NO_REUSE); + } + + /** + * Ray-plane intersection. Return point where ray intersect plane.
+ * This method doesn't check plane-vector collinearity! + * + * @param ray the ray. + * @param buffer the vector's buffer. + * @return the intersection point. + */ + public Vector3f rayIntersection(Ray3f ray, Vector3fBuffer buffer) { + + var direction = ray.getDirection(); + var start = ray.getStart(); + + var denominator = direction.dot(normal); + var distance = (d - start.dot(normal)) / denominator; + + var add = buffer.next(direction); + add.multLocal(distance); + + return new Vector3f(start).addLocal(add); + } + + /** + * Line-plane (segment-plane) intersection. Return point where line intersect plane.
If line and plane is parallel + * or lines doesn't intersect plane return {@link Vector3f#POSITIVE_INFINITY} const. + * + * @param startPoint the line start point. + * @param secondPoint the line end point. + * @return intersection point or {@link Vector3f#POSITIVE_INFINITY} + */ + public Vector3f lineIntersection(Vector3f startPoint, Vector3f secondPoint) { + return lineIntersection(startPoint, secondPoint, Vector3fBuffer.NO_REUSE); + } + + /** + * Line-plane (segment-plane) intersection. Return point where line intersect plane.
If line and plane is parallel + * or lines doesn't intersect plane return {@link Vector3f#POSITIVE_INFINITY} const. + * + * @param startPoint the line start point. + * @param secondPoint the line end point. + * @param buffer the vector's buffer. + * @return intersection point or {@link Vector3f#POSITIVE_INFINITY} + */ + public Vector3f lineIntersection( + Vector3f startPoint, + Vector3f secondPoint, + Vector3fBuffer buffer) { + + var ab = buffer.next(secondPoint); + ab.subtractLocal(startPoint); + + var t = (d - normal.dot(startPoint)) / normal.dot(ab); + + if (t < 0 || t > 1.f) { + return Vector3f.POSITIVE_INFINITY; + } + + return new Vector3f(startPoint).addLocal(ab.multLocal(t)); + } + + /** + * Plane-plane intersection. Return point where planes intersects.
If planes is parallel return + * {@link Vector3f#POSITIVE_INFINITY} const. + * + * @param plane the plane. + * @param epsilon the epsilon. + * @return the intersection point or copy of {@link Vector3f#POSITIVE_INFINITY}. + */ + public Vector3f planeIntersection(Plane plane, float epsilon) { + return planeIntersection(plane, epsilon, Vector3fBuffer.NO_REUSE); + } + + /** + * Plane-plane intersection. Return point where planes intersects.
If planes is parallel return + * {@link Vector3f#POSITIVE_INFINITY} const. + * + * @param plane the plane. + * @param epsilon the epsilon. + * @param buffer the vector's buffer. + * @return the intersection point or {@link Vector3f#POSITIVE_INFINITY}. + */ + public Vector3f planeIntersection(Plane plane, float epsilon, Vector3fBuffer buffer) { + + var direction = normal.cross(plane.normal, buffer.nextVector()); + var denominator = direction.dot(direction); + + if (denominator < epsilon) { + // these planes are parallel + return Vector3f.POSITIVE_INFINITY; + } + + return new Vector3f(plane.normal) + .multLocal(d) + .subtractLocal(buffer + .next(normal) + .multLocal(plane.d)) + .crossLocal(direction) + .divideLocal(denominator); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int prime = 31; + int result = 1; + result = prime * result + normal.hashCode(); + result = prime * result + Float.floatToIntBits(d); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Plane{normal=" + normal + ", d=" + d + "}"; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Polygon.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Polygon.java index dce3a68b..214b60a0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Polygon.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Polygon.java @@ -3,386 +3,389 @@ import static javasabr.rlib.common.util.array.ArrayFactory.toArray; import java.util.Arrays; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * Geometry 3D polygon. - * + * * @author zcxv */ +@NullMarked public class Polygon { - private final static float EPSILON_ON_PLANE = 0.1f; - private final static float EPSILON_CWW = 0.01f; - - /** - * The polygon vertices. - */ - private final @NotNull Vector3f[] vertices; - - /** - * The polygon plane. - */ - private final @NotNull Plane plane; - - /** - * Custom flags. - */ - private int flags; - - /** - * Construct polygon from the vertices. - * - * @param vertices the vertices. - * @throws IllegalArgumentException throw if vertices is less than 3 - * @see Polygon#Polygon(Vector3f, Vector3f, Vector3f) - */ - public Polygon(@NotNull Vector3f[] vertices) throws IllegalArgumentException { - this(vertices, Vector3fBuffer.NO_REUSE); + private final static float EPSILON_ON_PLANE = 0.1f; + private final static float EPSILON_CWW = 0.01f; + + /** + * The polygon vertices. + */ + private final Vector3f[] vertices; + + /** + * The polygon plane. + */ + private final Plane plane; + + /** + * Custom flags. + */ + private int flags; + + /** + * Construct polygon from the vertices. + * + * @param vertices the vertices. + * @throws IllegalArgumentException throw if vertices is less than 3 + * @see Polygon#Polygon(Vector3f, Vector3f, Vector3f) + */ + public Polygon(Vector3f[] vertices) throws IllegalArgumentException { + this(vertices, Vector3fBuffer.NO_REUSE); + } + + /** + * Construct polygon from the vertices. + * + * @param vertices the vertices. + * @param buffer the vector's buffer. + * @throws IllegalArgumentException throw if vertices is less than 3 + * @see Polygon#Polygon(Vector3f, Vector3f, Vector3f, Vector3fBuffer) + */ + public Polygon(Vector3f[] vertices, Vector3fBuffer buffer) throws IllegalArgumentException { + + if (vertices.length < 3) { + throw new IllegalArgumentException("polygon cannot have less than 3 vertices."); } - /** - * Construct polygon from the vertices. - * - * @param vertices the vertices. - * @param buffer the vector's buffer. - * @throws IllegalArgumentException throw if vertices is less than 3 - * @see Polygon#Polygon(Vector3f, Vector3f, Vector3f, Vector3fBuffer) - */ - public Polygon(@NotNull Vector3f[] vertices, @NotNull Vector3fBuffer buffer) throws IllegalArgumentException { + this.vertices = vertices; - if (vertices.length < 3) { - throw new IllegalArgumentException("polygon cannot have less than 3 vertices."); - } + var normal = buffer.nextVector(); - this.vertices = vertices; - - var normal = buffer.nextVector(); - - for (int i = 2; i < vertices.length; i++) { - var ab = buffer.next(vertices[i - 1]).subtractLocal(vertices[0]); - var ac = buffer.next(vertices[i]).subtractLocal(vertices[0]); - normal.addLocal(ab.crossLocal(ac)); - } - - this.plane = new Plane(getPlanePoint(), normal.normalizeLocal()); + for (int i = 2; i < vertices.length; i++) { + var ab = buffer + .next(vertices[i - 1]) + .subtractLocal(vertices[0]); + var ac = buffer + .next(vertices[i]) + .subtractLocal(vertices[0]); + normal.addLocal(ab.crossLocal(ac)); } - /** - * Construct polygon from the 3 vertices. - * - * @param first the first vertex. - * @param second the second vertex. - * @param third the third vertex. - * @param buffer the vector's buffer. - * @see Polygon#Polygon(Vector3f[], Vector3fBuffer) - */ - public Polygon( - @NotNull Vector3f first, - @NotNull Vector3f second, - @NotNull Vector3f third, - @NotNull Vector3fBuffer buffer - ) { - this(toArray(first, second, third), buffer); + this.plane = new Plane(getPlanePoint(), normal.normalizeLocal()); + } + + /** + * Construct polygon from the 3 vertices. + * + * @param first the first vertex. + * @param second the second vertex. + * @param third the third vertex. + * @param buffer the vector's buffer. + * @see Polygon#Polygon(Vector3f[], Vector3fBuffer) + */ + public Polygon( + Vector3f first, + Vector3f second, + Vector3f third, + Vector3fBuffer buffer) { + this(toArray(first, second, third), buffer); + } + + /** + * Construct polygon from the 3 vertices. + * + * @param first the first vertex. + * @param second the second vertex. + * @param third the third vertex. + * @see Polygon#Polygon(Vector3f[]) + */ + public Polygon(Vector3f first, Vector3f second, Vector3f third) { + this(toArray(first, second, third), Vector3fBuffer.NO_REUSE); + } + + /** + * Return plane point.
It's a first polygon vertex. + * + * @return the plane point. + */ + public Vector3f getPlanePoint() { + return vertices[0]; + } + + /** + * Return polygon vertices. + * + * @return vertices + */ + public Vector3f[] getVertices() { + return vertices; + } + + /** + * Return polygon plane. + * + * @return plane + */ + public Plane getPlane() { + return plane; + } + + /** + * Return polygon custom flags.
By default it is zero. + * + * @return flags + */ + public int getFlags() { + return flags; + } + + /** + * Set polygon custom flags. + * + * @param flags flags + */ + public void setFlags(int flags) { + this.flags = flags; + } + + /** + * Toggle flag bit. + * + * @param flag flag + * @return flag status + */ + public boolean toggleFlag(int flag) { + flags ^= flag; + return isFlagSet(flag); + } + + /** + * Return flag status. + * + * @param flag + * @return true if flag is set + */ + public boolean isFlagSet(int flag) { + return (flags & flag) != 0; + } + + /** + * Set flag bit. + * + * @param flag + */ + public void setFlag(int flag) { + flags |= flag; + } + + /** + * Unset flag bit. + * + * @param flag flag + */ + public void unsetFlag(int flag) { + flags &= ~flag; + } + + /** + * Return mid-point of this polygon. + * + * @return mid-point + */ + public Vector3f getMidPoint() { + return getMidPoint(Vector3fBuffer.NO_REUSE); + } + + /** + * Return mid-point of this polygon. + * + * @param buffer vector's buffer + * @return mid-point + */ + public Vector3f getMidPoint(Vector3fBuffer buffer) { + + var point = buffer.nextVector(); + + for (var vertice : vertices) { + point.addLocal(vertice); } - /** - * Construct polygon from the 3 vertices. - * - * @param first the first vertex. - * @param second the second vertex. - * @param third the third vertex. - * @see Polygon#Polygon(Vector3f[]) - */ - public Polygon(@NotNull Vector3f first, @NotNull Vector3f second, @NotNull Vector3f third) { - this(toArray(first, second, third), Vector3fBuffer.NO_REUSE); - } - - /** - * Return plane point.
- * It's a first polygon vertex. - * - * @return the plane point. - */ - public @NotNull Vector3f getPlanePoint() { - return vertices[0]; - } - - /** - * Return polygon vertices. - * - * @return vertices - */ - public @NotNull Vector3f[] getVertices() { - return vertices; - } - - /** - * Return polygon plane. - * - * @return plane - */ - public @NotNull Plane getPlane() { - return plane; - } - - /** - * Return polygon custom flags.
- * By default it is zero. - * - * @return flags - */ - public int getFlags() { - return flags; - } - - /** - * Set polygon custom flags. - * - * @param flags flags - */ - public void setFlags(int flags) { - this.flags = flags; + return point.divideLocal(vertices.length); + } + + /** + * Check polygon vertices to coplanar. + * + * @return true if polygon vertices is coplanar + */ + public boolean isCoplanar() { + return isCoplanar(Vector3fBuffer.NO_REUSE); + } + + /** + * Check polygon vertices to coplanar. + * + * @param buffer vector's buffer + * @return true if polygon vertices is coplanar + */ + public boolean isCoplanar(Vector3fBuffer buffer) { + + for (var vertice : vertices) { + if (!isOnPlane(vertice, buffer)) { + return false; + } } - - /** - * Toggle flag bit. - * - * @param flag flag - * @return flag status - */ - public boolean toggleFlag(int flag) { - flags ^= flag; - return isFlagSet(flag); - } - - /** - * Return flag status. - * - * @param flag - * @return true if flag is set - */ - public boolean isFlagSet(int flag) { - return (flags & flag) != 0; - } - - /** - * Set flag bit. - * - * @param flag - */ - public void setFlag(int flag) { - flags |= flag; - } - - /** - * Unset flag bit. - * - * @param flag flag - */ - public void unsetFlag(int flag) { - flags &= ~flag; - } - - /** - * Return mid-point of this polygon. - * - * @return mid-point - */ - public @NotNull Vector3f getMidPoint() { - return getMidPoint(Vector3fBuffer.NO_REUSE); - } - - /** - * Return mid-point of this polygon. - * - * @param buffer vector's buffer - * @return mid-point - */ - public @NotNull Vector3f getMidPoint(@NotNull Vector3fBuffer buffer) { - - var point = buffer.nextVector(); - - for (var vertice : vertices) { - point.addLocal(vertice); - } - return point.divideLocal(vertices.length); - } - - /** - * Check polygon vertices to coplanar. - * - * @return true if polygon vertices is coplanar - */ - public boolean isCoplanar() { - return isCoplanar(Vector3fBuffer.NO_REUSE); + return true; + } + + /** + * Determines if point on polygon plane. + * + * @param point point + * @return true if point on plane + */ + public boolean isOnPlane(Vector3f point) { + return isOnPlane(point, Vector3fBuffer.NO_REUSE); + } + + /** + * Determines if point on polygon plane. + * + * @param point point + * @param buffer vector's buffer + * @return true if point on plane + */ + public boolean isOnPlane(Vector3f point, Vector3fBuffer buffer) { + var distance = plane.distance(point); + return distance > -EPSILON_ON_PLANE && distance < EPSILON_ON_PLANE; + } + + /** + * Determines if line AB intersect polygon.
If point isn't null and line intersect polygon then point coordinates + * is set to intersection. + * + * @param startLine start line point + * @param endLine end line point + * @param point [out] point with intersection coordinates, can be null + * @return true if line AB intersect polygon + */ + public boolean intersect(Vector3f startLine, Vector3f endLine, Vector3f point) { + return intersect(startLine, endLine, point, Vector3fBuffer.NO_REUSE); + } + + /** + * Determines if line AB intersect polygon.
If point isn't null and line intersect polygon then point coordinates + * is set to intersection. + * + * @param startLine start line point + * @param endLine end line point + * @param point [out] point with intersection coordinates, can be null + * @param vectorBuffer vector's buffer + * @return true if line AB intersect polygon + */ + public boolean intersect( + Vector3f startLine, + Vector3f endLine, + @Nullable Vector3f point, + Vector3fBuffer vectorBuffer) { + + var aDistance = plane.distance(startLine, vertices[0], vectorBuffer); + var bDistance = plane.distance(endLine, vertices[0], vectorBuffer); + + if ((aDistance < 0 && bDistance < 0) || (aDistance > 0 && bDistance > 0)) { + return false; } - /** - * Check polygon vertices to coplanar. - * - * @param buffer vector's buffer - * @return true if polygon vertices is coplanar - */ - public boolean isCoplanar(@NotNull Vector3fBuffer buffer) { - - for (var vertice : vertices) { - if (!isOnPlane(vertice, buffer)) { - return false; - } - } - - return true; - } - - /** - * Determines if point on polygon plane. - * - * @param point point - * @return true if point on plane - */ - public boolean isOnPlane(@NotNull Vector3f point) { - return isOnPlane(point, Vector3fBuffer.NO_REUSE); - } + var intersection = plane.rayIntersection(startLine, endLine, vertices[0], vectorBuffer); - /** - * Determines if point on polygon plane. - * - * @param point point - * @param buffer vector's buffer - * @return true if point on plane - */ - public boolean isOnPlane(@NotNull Vector3f point, @NotNull Vector3fBuffer buffer) { - var distance = plane.distance(point); - return distance > -EPSILON_ON_PLANE && distance < EPSILON_ON_PLANE; + if (intersection.equals(startLine, 0.1f) || intersection.equals(endLine, 0.1f)) { + return false; } - /** - * Determines if line AB intersect polygon.
- * If point isn't null and line intersect polygon then point coordinates is set to intersection. - * - * @param startLine start line point - * @param endLine end line point - * @param point [out] point with intersection coordinates, can be null - * @return true if line AB intersect polygon - */ - public boolean intersect(@NotNull Vector3f startLine, @NotNull Vector3f endLine, @Nullable Vector3f point) { - return intersect(startLine, endLine, point, Vector3fBuffer.NO_REUSE); - } - - /** - * Determines if line AB intersect polygon.
- * If point isn't null and line intersect polygon then point coordinates is set to intersection. - * - * @param startLine start line point - * @param endLine end line point - * @param point [out] point with intersection coordinates, can be null - * @param vectorBuffer vector's buffer - * @return true if line AB intersect polygon - */ - public boolean intersect( - @NotNull Vector3f startLine, - @NotNull Vector3f endLine, - @Nullable Vector3f point, - @NotNull Vector3fBuffer vectorBuffer - ) { - - var aDistance = plane.distance(startLine, vertices[0], vectorBuffer); - var bDistance = plane.distance(endLine, vertices[0], vectorBuffer); - - if ((aDistance < 0 && bDistance < 0) || (aDistance > 0 && bDistance > 0)) { - return false; - } - - var intersection = plane.rayIntersection(startLine, endLine, vertices[0], vectorBuffer); - - if (intersection.equals(startLine, 0.1f) || intersection.equals(endLine, 0.1f)) { - return false; - } - - if (point != null) { - point.set(intersection); - } - - return contains(intersection, vectorBuffer); + if (point != null) { + point.set(intersection); } - /** - * Determines if point inside of polygon. - * - * @param point point - * @return true if point inside - */ - public boolean contains(@NotNull Vector3f point) { - return contains(point, Vector3fBuffer.NO_REUSE); + return contains(intersection, vectorBuffer); + } + + /** + * Determines if point inside of polygon. + * + * @param point point + * @return true if point inside + */ + public boolean contains(Vector3f point) { + return contains(point, Vector3fBuffer.NO_REUSE); + } + + /** + * Determines if point inside of polygon. + * + * @param point point + * @param buffer vector's buffer + * @return true if point inside + */ + public boolean contains(Vector3f point, Vector3fBuffer buffer) { + + int low = 0; + int high = vertices.length; + + do { + + int mid = (low + high) / 2; + + if (isTriangleCCW(vertices[0], vertices[mid], point, buffer)) { + low = mid; + } else { + high = mid; + } + + } while (low + 1 < high); + + if (low == 0 || high == vertices.length) { + return false; } - /** - * Determines if point inside of polygon. - * - * @param point point - * @param buffer vector's buffer - * @return true if point inside - */ - public boolean contains(@NotNull Vector3f point, @NotNull Vector3fBuffer buffer) { - - int low = 0; - int high = vertices.length; - - do { - - int mid = (low + high) / 2; - - if (isTriangleCCW(vertices[0], vertices[mid], point, buffer)) { - low = mid; - } else { - high = mid; - } - - } while (low + 1 < high); - - if (low == 0 || high == vertices.length) { - return false; - } - - return isTriangleCCW(vertices[low], vertices[high], point, buffer); - } - - /** - * Determines if triangle specified by 3 points is defined counterclockwise. - * - * @param first first vertex. - * @param second second vertex. - * @param third third vertex. - * @param buffer vector's buffer. - * @return true if defined. - */ - private boolean isTriangleCCW( - @NotNull Vector3f first, - @NotNull Vector3f second, - @NotNull Vector3f third, - @NotNull Vector3fBuffer buffer - ) { - - var ab = buffer.next(first) - .subtractLocal(second); - - var ac = buffer.next(first) - .subtractLocal(third); - - ab.crossLocal(ac); - - return plane.getNormal() - .dot(ab) > EPSILON_CWW; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return "Polygon{vertices=" + Arrays.toString(vertices) + - ", plane=" + plane + - ", flags=" + flags + "}"; - } + return isTriangleCCW(vertices[low], vertices[high], point, buffer); + } + + /** + * Determines if triangle specified by 3 points is defined counterclockwise. + * + * @param first first vertex. + * @param second second vertex. + * @param third third vertex. + * @param buffer vector's buffer. + * @return true if defined. + */ + private boolean isTriangleCCW( + Vector3f first, + Vector3f second, + Vector3f third, + Vector3fBuffer buffer) { + + var ab = buffer + .next(first) + .subtractLocal(second); + + var ac = buffer + .next(first) + .subtractLocal(third); + + ab.crossLocal(ac); + + return plane + .getNormal() + .dot(ab) > EPSILON_CWW; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Polygon{vertices=" + Arrays.toString(vertices) + ", plane=" + plane + ", flags=" + flags + "}"; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Quaternion4f.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Quaternion4f.java index d32123ec..578826ac 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Quaternion4f.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Quaternion4f.java @@ -4,867 +4,880 @@ import javasabr.rlib.common.util.ExtMath; import javasabr.rlib.common.util.random.Random; import javasabr.rlib.common.util.random.RandomFactory; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of rotation in 3D world based on Quaternion. * * @author JavaSaBr */ +@NullMarked public class Quaternion4f { - public static final Quaternion4f IDENTITY = new Quaternion4f(0, 0, 0, 1); - - private static final ThreadLocal RANDOM_LOCAL = - ThreadLocal.withInitial(RandomFactory::newFastRandom); - - private static final ThreadLocal ROTATION_LOCAL = - ThreadLocal.withInitial(Quaternion4f::new); - - /** - * Get the thread local instance. - * - * @return the thread local instance. - */ - public static Quaternion4f get() { - return ROTATION_LOCAL.get(); - } - - /** - * The X component. - */ - private float x; - - /** - * The Y component. - */ - private float y; - - /** - * The Z component. - */ - private float z; - - /** - * The W component. - */ - private float w; - - public Quaternion4f() { - w = 1; - } - - public Quaternion4f(float[] vals) { - this(vals[0], vals[1], vals[2], vals[3]); - } - - public Quaternion4f(float angleX, float angleY, float angleZ) { - fromAngles(angleX, angleY, angleZ); - } - - public Quaternion4f(float x, float y, float z, float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - /** - * Add local quaternion 4 f. - * - * @param rotation the rotation - * @return the quaternion 4 f - */ - @NotNull - public Quaternion4f addLocal(@NotNull final Quaternion4f rotation) { - this.x += rotation.x; - this.y += rotation.y; - this.z += rotation.z; - this.w += rotation.w; - return this; - } - - /** - * Рассчет косинуса угла между текущим и указанным разворотом. - * - * @param rotation сверяемый разворот. - * @return косинус угла между 2мя разворотами. - */ - public float dot(@NotNull final Quaternion4f rotation) { - return w * rotation.w + x * rotation.x + y * rotation.y + z * rotation.z; - } - - @Override - public final boolean equals(final Object obj) { - - if (this == obj) { - return true; - } else if (obj == null) { - return false; - } else if (getClass() != obj.getClass()) { - return false; - } - - final Quaternion4f other = (Quaternion4f) obj; - - if (Float.floatToIntBits(w) != Float.floatToIntBits(other.w)) { - return false; - } else if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) { - return false; - } else if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) { - return false; - } else if (Float.floatToIntBits(z) != Float.floatToIntBits(other.z)) { - return false; - } - - return true; - } - - /** - * Расчет разворота по углам в 3х осях. - * - * @param angleX угол по оси X. - * @param yAngle угол по оси Y. - * @param zAngle угол по оси Z. - * @return the quaternion 4 f - */ - - public final @NotNull Quaternion4f fromAngles(float angleX, float yAngle, float zAngle) { - - float angle = zAngle * 0.5f; - - float sinZ = ExtMath.sin(angle); - float cosZ = ExtMath.cos(angle); - - angle = yAngle * 0.5f; - - float sinY = ExtMath.sin(angle); - float cosY = ExtMath.cos(angle); - - angle = angleX * 0.5f; - - float sinX = ExtMath.sin(angle); - float cosX = ExtMath.cos(angle); - - float cosYXcosZ = cosY * cosZ; - float sinYXsinZ = sinY * sinZ; - float cosYXsinZ = cosY * sinZ; - float sinYXcosZ = sinY * cosZ; - - w = cosYXcosZ * cosX - sinYXsinZ * sinX; - x = cosYXcosZ * sinX + sinYXsinZ * cosX; - y = sinYXcosZ * cosX + cosYXsinZ * sinX; - z = cosYXsinZ * cosX - sinYXcosZ * sinX; - - return normalizeLocal(); - } - - /** - * Calculate a rotation from angles. - * - * @param angles the angles. - * @return the quaternion 4 f - */ - @NotNull - public final Quaternion4f fromAngles(final float[] angles) { - return fromAngles(angles[0], angles[1], angles[2]); - } - - /** - * fromAxes creates a Quaternion that represents the coordinate system defined by three - * axes. These axes are assumed to be orthogonal and no error checking is applied. Thus, the user must insure that - * the three axes being provided indeed represents a proper right handed coordinate system. - * - * @param axisX vector representing the x-axis of the coordinate system. - * @param axisY vector representing the y-axis of the coordinate system. - * @param axisZ vector representing the z-axis of the coordinate system. - * @return the quaternion 4 f - */ - @NotNull - public Quaternion4f fromAxes(@NotNull final Vector3f axisX, @NotNull final Vector3f axisY, @NotNull final Vector3f axisZ) { - return fromRotationMatrix(axisX.getX(), axisY.getX(), axisZ.getX(), axisX.getY(), axisY.getY(), - axisZ.getY(), axisX.getZ(), axisY.getZ(), axisZ.getZ()); - } - - /** - * From rotation matrix quaternion 4 f. - * - * @param val_0_0 the val 0 0 - * @param val_0_1 the val 0 1 - * @param val_0_2 the val 0 2 - * @param val_1_0 the val 1 0 - * @param val_1_1 the val 1 1 - * @param val_1_2 the val 1 2 - * @param val_2_0 the val 2 0 - * @param val_2_1 the val 2 1 - * @param val_2_2 the val 2 2 - * @return the quaternion 4 f - */ - @NotNull - public Quaternion4f fromRotationMatrix(final float val_0_0, final float val_0_1, final float val_0_2, - final float val_1_0, final float val_1_1, final float val_1_2, - final float val_2_0, final float val_2_1, final float val_2_2) { - - final float t = val_0_0 + val_1_1 + val_2_2; - - // we protect the division by s by ensuring that s>=1 - if (t >= 0) { // |w| >= .5 - float s = ExtMath.sqrt(t + 1); // |s|>=1 ... - w = 0.5f * s; - s = 0.5f / s; // so this division isn't bad - x = (val_2_1 - val_1_2) * s; - y = (val_0_2 - val_2_0) * s; - z = (val_1_0 - val_0_1) * s; - } else if (val_0_0 > val_1_1 && val_0_0 > val_2_2) { - float s = ExtMath.sqrt(1.0f + val_0_0 - val_1_1 - val_2_2); // |s|>=1 - x = s * 0.5f; // |x| >= .5 - s = 0.5f / s; - y = (val_1_0 + val_0_1) * s; - z = (val_0_2 + val_2_0) * s; - w = (val_2_1 - val_1_2) * s; - } else if (val_1_1 > val_2_2) { - float s = ExtMath.sqrt(1.0f + val_1_1 - val_0_0 - val_2_2); // |s|>=1 - y = s * 0.5f; // |y| >= .5 - s = 0.5f / s; - x = (val_1_0 + val_0_1) * s; - z = (val_2_1 + val_1_2) * s; - w = (val_0_2 - val_2_0) * s; - } else { - float s = ExtMath.sqrt(1.0f + val_2_2 - val_0_0 - val_1_1); // |s|>=1 - z = s * 0.5f; // |z| >= .5 - s = 0.5f / s; - x = (val_0_2 + val_2_0) * s; - y = (val_2_1 + val_1_2) * s; - w = (val_1_0 - val_0_1) * s; - } - - return this; - } - - /** - * Calculate a vector for the direction type. - * - * @param type the direction type. - * @return the calculated vector. - */ - public @NotNull Vector3f getDirection(@NotNull DirectionType type) { - return getDirection(type, null); - } - - /** - * Calculate a vector for the direction type. - * - * @param type the direction type. - * @param store the vector to store result. - * @return the calculated vector. - */ - public @NotNull Vector3f getDirection(@NotNull DirectionType type, @Nullable Vector3f store) { - - if (store == null) { - store = new Vector3f(); - } - - float norm = norm(); - - if (norm != 1.0f) { - norm = ExtMath.invSqrt(norm); - } - - float xx = x * x * norm; - float xy = x * y * norm; - float xz = x * z * norm; - float xw = x * w * norm; - float yy = y * y * norm; - float yz = y * z * norm; - float yw = y * w * norm; - float zz = z * z * norm; - float zw = z * w * norm; - - switch (type) { - case RIGHT: { - store.setX(1 - 2 * (yy + zz)); - store.setY(2 * (xy + zw)); - store.setZ(2 * (xz - yw)); - break; - } - case LEFT: { - store.setX(1 - 2 * (yy + zz)); - store.setY(2 * (xy + zw)); - store.setZ(2 * (xz - yw)); - store.negateLocal(); - break; - } - case UP: { - store.setX(2 * (xy - zw)); - store.setY(1 - 2 * (xx + zz)); - store.setZ(2 * (yz + xw)); - break; - } - case DOWN: { - store.setX(2 * (xy - zw)); - store.setY(1 - 2 * (xx + zz)); - store.setZ(2 * (yz + xw)); - store.negateLocal(); - break; - } - case FRONT: { - store.setX(2 * (xz + yw)); - store.setY(2 * (yz - xw)); - store.setZ(1 - 2 * (xx + yy)); - break; - } - case BEHIND: { - store.setX(2 * (xz + yw)); - store.setY(2 * (yz - xw)); - store.setZ(1 - 2 * (xx + yy)); - store.negateLocal(); - break; - } - } - - return store; - } - - /** - * Gets w. - * - * @return степень разворота по оси w. - */ - public final float getW() { - return w; - } - - /** - * Sets w. - * - * @param w степень разворота по оси w. - */ - public final void setW(final float w) { - this.w = w; - } - - /** - * Gets x. - * - * @return степень разворота по оси х. - */ - public final float getX() { - return x; - } - - /** - * Sets x. - * - * @param x степень разворота по оси х. - */ - public final void setX(final float x) { - this.x = x; - } - - /** - * Gets y. - * - * @return степень разворота по оси y. - */ - public final float getY() { - return y; - } - - /** - * Sets y. - * - * @param y степень разворота по оси y. - */ - public final void setY(final float y) { - this.y = y; - } - - /** - * Gets z. - * - * @return степень разворота по оси z. - */ - public final float getZ() { - return z; - } - - /** - * Sets z. - * - * @param z степень разворота по оси z. - */ - public final void setZ(final float z) { - this.z = z; - } - - @Override - public final int hashCode() { - - final int prime = 31; - int result = 1; - - result = prime * result + Float.floatToIntBits(w); - result = prime * result + Float.floatToIntBits(x); - result = prime * result + Float.floatToIntBits(y); - result = prime * result + Float.floatToIntBits(z); - - return result; - } - - /** - * Calculate the value of the quaternion, which will look in the specified direction. - * - * @param direction the direction. - * @param up the vector of orientation where is top. - */ - public void lookAt(@NotNull Vector3f direction, @NotNull Vector3f up) { - lookAt(direction, up, Vector3fBuffer.NO_REUSE); - } - - /** - * Calculate the value of the quaternion, which will look in the specified direction. - * - * @param direction the direction. - * @param up the vector of orientation where is top. - * @param buffer the vector's buffer. - */ - public void lookAt(@NotNull Vector3f direction, @NotNull Vector3f up, @NotNull Vector3fBuffer buffer) { - - var axisZ = buffer.next(direction) - .normalizeLocal(); - - var axisX = buffer.next(up) - .crossLocal(direction) - .normalizeLocal(); - - var axisY = buffer.next(direction) - .crossLocal(axisX) - .normalizeLocal(); - - fromAxes(axisX, axisY, axisZ); - - normalizeLocal(); - } - - /** - * Приминение разворота на вектор. - * - * @param vector вектор, который надо развернуть. - * @return полученный вектор. - */ - @NotNull - public final Vector3f multLocal(@NotNull final Vector3f vector) { - - final float vectorX = vector.getX(); - final float vectorY = vector.getY(); - final float vectorZ = vector.getZ(); - - final float x = getX(); - final float y = getY(); - final float z = getZ(); - final float w = getW(); - - vector.setX(w * w * vectorX + 2 * y * w * vectorZ - 2 * z * w * vectorY + x * x * vectorX + 2 * y * x * vectorY + 2 * z * x * vectorZ - z * z * vectorX - y * y * vectorX); - vector.setY(2 * x * y * vectorX + y * y * vectorY + 2 * z * y * vectorZ + 2 * w * z * vectorX - z * z * vectorY + w * w * vectorY - 2 * x * w * vectorZ - x * x * vectorY); - vector.setZ(2 * x * z * vectorX + 2 * y * z * vectorY + z * z * vectorZ - 2 * w * y * vectorX - y * y * vectorZ + 2 * w * x * vectorY - x * x * vectorZ + w * w * vectorZ); - - return vector; - } - - /** - * Negate local quaternion 4 f. - * - * @return перевернуть значения. - */ - public final Quaternion4f negateLocal() { - x = -x; - y = -y; - z = -z; - w = -w; - return this; - } - - /** - * Norm float. - * - * @return норма этого разворота. - */ - public float norm() { - return w * w + x * x + y * y + z * z; - } - - /** - * Normalizing of the current quaternion - * - * @return this quaternion. - */ - public final @NotNull Quaternion4f normalizeLocal() { - - var norm = ExtMath.invSqrt(norm()); - - x *= norm; - y *= norm; - z *= norm; - w *= norm; - - return this; - } - - /** - * Создание случайного разворота. - */ - public void random() { - random(RANDOM_LOCAL.get()); - } - - /** - * Создание случайного разворота. - * - * @param random the random - */ - public void random(@NotNull final Random random) { - - final float x = AngleUtils.degreeToRadians(random.nextInt(0, 360)); - final float y = AngleUtils.degreeToRadians(random.nextInt(0, 360)); - final float z = AngleUtils.degreeToRadians(random.nextInt(0, 360)); - - fromAngles(x, y, z); - } - - /** - * Set quaternion 4 f. - * - * @param rotation the rotation - * @return the quaternion 4 f - */ - @NotNull - public Quaternion4f set(@NotNull final Quaternion4f rotation) { - this.x = rotation.x; - this.y = rotation.y; - this.z = rotation.z; - this.w = rotation.w; - return this; - } - - /** - * Sets xyzw. - * - * @param x the x - * @param y the y - * @param z the z - * @param w the w - */ - public void setXYZW(final float x, final float y, final float z, final float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - /** - * Рассчитывает промежуточный разворот между текуим и указанным в зависимости от указанного %. - * - * @param end конечный разворот. - * @param percent % разворота от текущего к конечному. - */ - public void slerp(@NotNull final Quaternion4f end, final float percent) { - if (equals(end)) return; - - float result = x * end.x + y * end.y + z * end.z + w * end.w; - - if (result < 0.0f) { - end.x = -end.x; - end.y = -end.y; - end.z = -end.z; - end.w = -end.w; - result = -result; - } - - float scale0 = 1 - percent; - float scale1 = percent; - - if (1 - result > 0.1f) { - - final float theta = ExtMath.acos(result); - final float invSinTheta = 1f / ExtMath.sin(theta); - - scale0 = ExtMath.sin((1 - percent) * theta) * invSinTheta; - scale1 = ExtMath.sin(percent * theta) * invSinTheta; - } - - x = scale0 * x + scale1 * end.x; - y = scale0 * y + scale1 * end.y; - z = scale0 * z + scale1 * end.z; - w = scale0 * w + scale1 * end.w; - } - - /** - * Рассчитывает промежуточный разворот от указанного стартового, до указанного конечного в зависимости от указанного - * %. - * - * @param start стартовый разворот. - * @param end конечный разворот. - * @param percent % разворота от стартового до конечного. - * @return the quaternion 4 f - */ - @NotNull - public Quaternion4f slerp(@NotNull final Quaternion4f start, @NotNull final Quaternion4f end, final float percent) { - return slerp(start, end, percent, false); - } - - /** - * Рассчитывает промежуточный разворот от указанного стартового, до указанного конечного в зависимости от указанного - * %. - * - * @param start стартовый разворот. - * @param end конечный разворот. - * @param percent % разворота от стартового до конечного. - * @param forceLinear принудительное использование линейной интерполяции. - * @return the quaternion 4 f - */ - @NotNull - public final Quaternion4f slerp(@NotNull final Quaternion4f start, @NotNull final Quaternion4f end, - final float percent, final boolean forceLinear) { - - if (start.equals(end)) { - set(start); - return this; - } - - float result = start.dot(end); - - if (result < 0.0f) { - end.negateLocal(); - result = -result; - } - - float startScale = 1 - percent; - float endScale = percent; - - if (!forceLinear && 1 - result > 0.1f) { - - final float theta = ExtMath.acos(result); - final float invSinTheta = 1f / ExtMath.sin(theta); - - startScale = ExtMath.sin((1 - percent) * theta) * invSinTheta; - endScale = ExtMath.sin(percent * theta) * invSinTheta; - } - - this.x = startScale * start.getX() + endScale * end.getX(); - this.y = startScale * start.getY() + endScale * end.getY(); - this.z = startScale * start.getZ() + endScale * end.getZ(); - this.w = startScale * start.getW() + endScale * end.getW(); - - return this; - } - - /** - * Рассчитывает промежуточный разворот от указанного стартового, до указанного конечного в зависимости от указанного - * %. - * - * @param targetRotation конечный разворот. - * @param percent % разворота от стартового до конечного. - */ - public void nlerp(@NotNull final Quaternion4f targetRotation, float percent) { - - float dot = dot(targetRotation); - float blendI = 1.0F - percent; - - if (dot < 0.0F) { - x = blendI * x - percent * targetRotation.x; - y = blendI * y - percent * targetRotation.y; - z = blendI * z - percent * targetRotation.z; - w = blendI * w - percent * targetRotation.w; - } else { - x = blendI * x + percent * targetRotation.x; - y = blendI * y + percent * targetRotation.y; - z = blendI * z + percent * targetRotation.z; - w = blendI * w + percent * targetRotation.w; - } - - normalizeLocal(); - } - - /** - * Subtract local quaternion 4 f. - * - * @param rotation the rotation - * @return the quaternion 4 f - */ - public Quaternion4f subtractLocal(@NotNull final Quaternion4f rotation) { - this.x -= rotation.x; - this.y -= rotation.y; - this.z -= rotation.z; - this.w -= rotation.w; - return this; - } - - /** - * To angle axis float. - * - * @param axisStore the axis store - * @return the float - */ - public final float toAngleAxis(@Nullable final Vector3f axisStore) { - - final float sqrLength = x * x + y * y + z * z; - float angle; - - if (sqrLength == 0.0f) { - - angle = 0.0f; - - if (axisStore != null) { - axisStore.setX(1.0F); - axisStore.setY(0.0F); - axisStore.setZ(0.0F); - } - - } else { - - angle = 2.0f * ExtMath.acos(w); - - if (axisStore != null) { - - final float invLength = 1.0f / ExtMath.sqrt(sqrLength); - - axisStore.setX(x * invLength); - axisStore.setY(y * invLength); - axisStore.setZ(z * invLength); - } - } - - return angle; - } - - /** - * toAngles returns this quaternion converted to Euler rotation angles (yaw,roll,pitch). Note that - * the result is not always 100% accurate due to the implications of euler angles. - * - * @param angles the float[] in which the angles should be stored, or null if you want a new float[] to be created - * @return the float[] in which the angles are stored. - * @see http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm - */ - @NotNull - public float[] toAngles(@Nullable float[] angles) { - - if (angles == null) { - angles = new float[3]; - } else if (angles.length != 3) { - throw new IllegalArgumentException("Angles array must have three elements"); - } - - float sqw = w * w; - float sqx = x * x; - float sqy = y * y; - float sqz = z * z; - float unit = sqx + sqy + sqz + sqw; // if normalized is one, otherwise - - // is correction factor - float test = x * y + z * w; - if (test > 0.499 * unit) { // singularity at north pole - angles[1] = 2 * ExtMath.atan2(x, w); - angles[2] = ExtMath.HALF_PI; - angles[0] = 0; - } else if (test < -0.499 * unit) { // singularity at south pole - angles[1] = -2 * ExtMath.atan2(x, w); - angles[2] = -ExtMath.HALF_PI; - angles[0] = 0; - } else { - angles[1] = ExtMath.atan2(2 * y * w - 2 * x * z, sqx - sqy - sqz + sqw); // roll - // or - // heading - angles[2] = ExtMath.asin(2 * test / unit); // pitch or attitude - angles[0] = ExtMath.atan2(2 * x * w - 2 * y * z, -sqx + sqy - sqz + sqw); // yaw - // or - // bank - } - return angles; - } - - /** - * Конвектирование квантерниона в матрицу 3х3 - * - * @param result матрица, в которую занести нужно результат. - * @return результат в виде матрицы. - */ - @NotNull - public final Matrix3f toRotationMatrix(@NotNull final Matrix3f result) { - - final float norm = norm(); - - final float s = norm == 1f ? 2f : norm > 0f ? 2f / norm : 0; - - final float x = getX(); - final float y = getY(); - final float z = getZ(); - final float w = getW(); - - final float xs = x * s; - final float ys = y * s; - final float zs = z * s; - final float xx = x * xs; - final float xy = x * ys; - final float xz = x * zs; - final float xw = w * xs; - final float yy = y * ys; - final float yz = y * zs; - final float yw = w * ys; - final float zz = z * zs; - final float zw = w * zs; - - result.set( - 1 - (yy + zz), xy - zw, xz + yw, - xy + zw, 1 - (xx + zz), yz - xw, - xz - yw, yz + xw, 1 - (xx + yy) - ); - - return result; - } - - /** - * Rotate the vector by this quaternion. - * - * @param vector the vector to rotate. - * @return the same vector which was rotated. - */ - public @NotNull Vector3f rotate(@NotNull Vector3f vector) { - - float px = vector.x; - float py = vector.y; - float pz = vector.z; - - float norm = norm(); - float s = norm == 1f ? 2f : norm > 0f ? 2f / norm : 0; - - float x = getX() * s; - float y = getY() * s; - float z = getZ() * s; - float xx = getX() * x; - float xy = getX() * y; - float xz = getX() * z; - float xw = getW() * x; - float yy = getY() * y; - float yz = getY() * z; - float yw = getW() * y; - float zz = getZ() * z; - float zw = getW() * z; - - vector.setX((1f - (yy + zz)) * px + (xy - zw) * py + (xz + yw) * pz); - vector.setY((xy + zw) * px + (1f - (xx + zz)) * py + (yz - xw) * pz); - vector.setZ((xz - yw) * px + (yz - xw) * py + (1f - (xx + yy)) * pz); - - return vector; - } - - @Override - public String toString() { - return "Quaternion4f{" + - "x=" + x + - ", y=" + y + - ", z=" + z + - ", w=" + w + - '}'; - } + public static final Quaternion4f IDENTITY = new Quaternion4f(0, 0, 0, 1); + + private static final ThreadLocal RANDOM_LOCAL = ThreadLocal.withInitial(RandomFactory::newFastRandom); + + private static final ThreadLocal ROTATION_LOCAL = ThreadLocal.withInitial(Quaternion4f::new); + + /** + * Get the thread local instance. + * + * @return the thread local instance. + */ + public static Quaternion4f get() { + return ROTATION_LOCAL.get(); + } + + /** + * The X component. + */ + private float x; + + /** + * The Y component. + */ + private float y; + + /** + * The Z component. + */ + private float z; + + /** + * The W component. + */ + private float w; + + public Quaternion4f() { + w = 1; + } + + public Quaternion4f(float[] vals) { + this(vals[0], vals[1], vals[2], vals[3]); + } + + public Quaternion4f(float angleX, float angleY, float angleZ) { + fromAngles(angleX, angleY, angleZ); + } + + public Quaternion4f(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + /** + * Add local quaternion 4 f. + * + * @param rotation the rotation + * @return the quaternion 4 f + */ + public Quaternion4f addLocal(Quaternion4f rotation) { + this.x += rotation.x; + this.y += rotation.y; + this.z += rotation.z; + this.w += rotation.w; + return this; + } + + /** + * Рассчет косинуса угла между текущим и указанным разворотом. + * + * @param rotation сверяемый разворот. + * @return косинус угла между 2мя разворотами. + */ + public float dot(Quaternion4f rotation) { + return w * rotation.w + x * rotation.x + y * rotation.y + z * rotation.z; + } + + @Override + public final boolean equals(Object obj) { + + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } + + Quaternion4f other = (Quaternion4f) obj; + + if (Float.floatToIntBits(w) != Float.floatToIntBits(other.w)) { + return false; + } else if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) { + return false; + } else if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) { + return false; + } else if (Float.floatToIntBits(z) != Float.floatToIntBits(other.z)) { + return false; + } + + return true; + } + + /** + * Расчет разворота по углам в 3х осях. + * + * @param angleX угол по оси X. + * @param yAngle угол по оси Y. + * @param zAngle угол по оси Z. + * @return the quaternion 4 f + */ + + public final Quaternion4f fromAngles(float angleX, float yAngle, float zAngle) { + + float angle = zAngle * 0.5f; + + float sinZ = ExtMath.sin(angle); + float cosZ = ExtMath.cos(angle); + + angle = yAngle * 0.5f; + + float sinY = ExtMath.sin(angle); + float cosY = ExtMath.cos(angle); + + angle = angleX * 0.5f; + + float sinX = ExtMath.sin(angle); + float cosX = ExtMath.cos(angle); + + float cosYXcosZ = cosY * cosZ; + float sinYXsinZ = sinY * sinZ; + float cosYXsinZ = cosY * sinZ; + float sinYXcosZ = sinY * cosZ; + + w = cosYXcosZ * cosX - sinYXsinZ * sinX; + x = cosYXcosZ * sinX + sinYXsinZ * cosX; + y = sinYXcosZ * cosX + cosYXsinZ * sinX; + z = cosYXsinZ * cosX - sinYXcosZ * sinX; + + return normalizeLocal(); + } + + /** + * Calculate a rotation from angles. + * + * @param angles the angles. + * @return the quaternion 4 f + */ + public final Quaternion4f fromAngles(float[] angles) { + return fromAngles(angles[0], angles[1], angles[2]); + } + + /** + * fromAxes creates a Quaternion that represents the coordinate system defined by three + * axes. These axes are assumed to be orthogonal and no error checking is applied. Thus, the user must insure that the + * three axes being provided indeed represents a proper right handed coordinate system. + * + * @param axisX vector representing the x-axis of the coordinate system. + * @param axisY vector representing the y-axis of the coordinate system. + * @param axisZ vector representing the z-axis of the coordinate system. + * @return the quaternion 4 f + */ + public Quaternion4f fromAxes(Vector3f axisX, Vector3f axisY, Vector3f axisZ) { + return fromRotationMatrix( + axisX.getX(), + axisY.getX(), + axisZ.getX(), + axisX.getY(), + axisY.getY(), + axisZ.getY(), + axisX.getZ(), + axisY.getZ(), + axisZ.getZ()); + } + + /** + * From rotation matrix quaternion 4 f. + * + * @param val_0_0 the val 0 0 + * @param val_0_1 the val 0 1 + * @param val_0_2 the val 0 2 + * @param val_1_0 the val 1 0 + * @param val_1_1 the val 1 1 + * @param val_1_2 the val 1 2 + * @param val_2_0 the val 2 0 + * @param val_2_1 the val 2 1 + * @param val_2_2 the val 2 2 + * @return the quaternion 4 f + */ + public Quaternion4f fromRotationMatrix( + float val_0_0, + float val_0_1, + float val_0_2, + float val_1_0, + float val_1_1, + float val_1_2, + float val_2_0, + float val_2_1, + float val_2_2) { + + float t = val_0_0 + val_1_1 + val_2_2; + + // we protect the division by s by ensuring that s>=1 + if (t >= 0) { // |w| >= .5 + float s = ExtMath.sqrt(t + 1); // |s|>=1 ... + w = 0.5f * s; + s = 0.5f / s; // so this division isn't bad + x = (val_2_1 - val_1_2) * s; + y = (val_0_2 - val_2_0) * s; + z = (val_1_0 - val_0_1) * s; + } else if (val_0_0 > val_1_1 && val_0_0 > val_2_2) { + float s = ExtMath.sqrt(1.0f + val_0_0 - val_1_1 - val_2_2); // |s|>=1 + x = s * 0.5f; // |x| >= .5 + s = 0.5f / s; + y = (val_1_0 + val_0_1) * s; + z = (val_0_2 + val_2_0) * s; + w = (val_2_1 - val_1_2) * s; + } else if (val_1_1 > val_2_2) { + float s = ExtMath.sqrt(1.0f + val_1_1 - val_0_0 - val_2_2); // |s|>=1 + y = s * 0.5f; // |y| >= .5 + s = 0.5f / s; + x = (val_1_0 + val_0_1) * s; + z = (val_2_1 + val_1_2) * s; + w = (val_0_2 - val_2_0) * s; + } else { + float s = ExtMath.sqrt(1.0f + val_2_2 - val_0_0 - val_1_1); // |s|>=1 + z = s * 0.5f; // |z| >= .5 + s = 0.5f / s; + x = (val_0_2 + val_2_0) * s; + y = (val_2_1 + val_1_2) * s; + w = (val_1_0 - val_0_1) * s; + } + + return this; + } + + /** + * Calculate a vector for the direction type. + * + * @param type the direction type. + * @return the calculated vector. + */ + public Vector3f getDirection(DirectionType type) { + return getDirection(type, null); + } + + /** + * Calculate a vector for the direction type. + * + * @param type the direction type. + * @param store the vector to store result. + * @return the calculated vector. + */ + public Vector3f getDirection(DirectionType type, @Nullable Vector3f store) { + + if (store == null) { + store = new Vector3f(); + } + + float norm = norm(); + + if (norm != 1.0f) { + norm = ExtMath.invSqrt(norm); + } + + float xx = x * x * norm; + float xy = x * y * norm; + float xz = x * z * norm; + float xw = x * w * norm; + float yy = y * y * norm; + float yz = y * z * norm; + float yw = y * w * norm; + float zz = z * z * norm; + float zw = z * w * norm; + + switch (type) { + case RIGHT: { + store.setX(1 - 2 * (yy + zz)); + store.setY(2 * (xy + zw)); + store.setZ(2 * (xz - yw)); + break; + } + case LEFT: { + store.setX(1 - 2 * (yy + zz)); + store.setY(2 * (xy + zw)); + store.setZ(2 * (xz - yw)); + store.negateLocal(); + break; + } + case UP: { + store.setX(2 * (xy - zw)); + store.setY(1 - 2 * (xx + zz)); + store.setZ(2 * (yz + xw)); + break; + } + case DOWN: { + store.setX(2 * (xy - zw)); + store.setY(1 - 2 * (xx + zz)); + store.setZ(2 * (yz + xw)); + store.negateLocal(); + break; + } + case FRONT: { + store.setX(2 * (xz + yw)); + store.setY(2 * (yz - xw)); + store.setZ(1 - 2 * (xx + yy)); + break; + } + case BEHIND: { + store.setX(2 * (xz + yw)); + store.setY(2 * (yz - xw)); + store.setZ(1 - 2 * (xx + yy)); + store.negateLocal(); + break; + } + } + + return store; + } + + /** + * Gets w. + * + * @return степень разворота по оси w. + */ + public final float getW() { + return w; + } + + /** + * Sets w. + * + * @param w степень разворота по оси w. + */ + public final void setW(float w) { + this.w = w; + } + + /** + * Gets x. + * + * @return степень разворота по оси х. + */ + public final float getX() { + return x; + } + + /** + * Sets x. + * + * @param x степень разворота по оси х. + */ + public final void setX(float x) { + this.x = x; + } + + /** + * Gets y. + * + * @return степень разворота по оси y. + */ + public final float getY() { + return y; + } + + /** + * Sets y. + * + * @param y степень разворота по оси y. + */ + public final void setY(float y) { + this.y = y; + } + + /** + * Gets z. + * + * @return степень разворота по оси z. + */ + public final float getZ() { + return z; + } + + /** + * Sets z. + * + * @param z степень разворота по оси z. + */ + public final void setZ(float z) { + this.z = z; + } + + @Override + public final int hashCode() { + + final int prime = 31; + int result = 1; + + result = prime * result + Float.floatToIntBits(w); + result = prime * result + Float.floatToIntBits(x); + result = prime * result + Float.floatToIntBits(y); + result = prime * result + Float.floatToIntBits(z); + + return result; + } + + /** + * Calculate the value of the quaternion, which will look in the specified direction. + * + * @param direction the direction. + * @param up the vector of orientation where is top. + */ + public void lookAt(Vector3f direction, Vector3f up) { + lookAt(direction, up, Vector3fBuffer.NO_REUSE); + } + + /** + * Calculate the value of the quaternion, which will look in the specified direction. + * + * @param direction the direction. + * @param up the vector of orientation where is top. + * @param buffer the vector's buffer. + */ + public void lookAt(Vector3f direction, Vector3f up, Vector3fBuffer buffer) { + + var axisZ = buffer + .next(direction) + .normalizeLocal(); + + var axisX = buffer + .next(up) + .crossLocal(direction) + .normalizeLocal(); + + var axisY = buffer + .next(direction) + .crossLocal(axisX) + .normalizeLocal(); + + fromAxes(axisX, axisY, axisZ); + + normalizeLocal(); + } + + /** + * Приминение разворота на вектор. + * + * @param vector вектор, который надо развернуть. + * @return полученный вектор. + */ + public final Vector3f multLocal(Vector3f vector) { + + final float vectorX = vector.getX(); + final float vectorY = vector.getY(); + final float vectorZ = vector.getZ(); + + final float x = getX(); + final float y = getY(); + final float z = getZ(); + final float w = getW(); + + vector.setX(w * w * vectorX + 2 * y * w * vectorZ - 2 * z * w * vectorY + x * x * vectorX + 2 * y * x * vectorY + + 2 * z * x * vectorZ - z * z * vectorX - y * y * vectorX); + vector.setY(2 * x * y * vectorX + y * y * vectorY + 2 * z * y * vectorZ + 2 * w * z * vectorX - z * z * vectorY + + w * w * vectorY - 2 * x * w * vectorZ - x * x * vectorY); + vector.setZ(2 * x * z * vectorX + 2 * y * z * vectorY + z * z * vectorZ - 2 * w * y * vectorX - y * y * vectorZ + + 2 * w * x * vectorY - x * x * vectorZ + w * w * vectorZ); + + return vector; + } + + /** + * Negate local quaternion 4 f. + * + * @return перевернуть значения. + */ + public final Quaternion4f negateLocal() { + x = -x; + y = -y; + z = -z; + w = -w; + return this; + } + + /** + * Norm float. + * + * @return норма этого разворота. + */ + public float norm() { + return w * w + x * x + y * y + z * z; + } + + /** + * Normalizing of the current quaternion + * + * @return this quaternion. + */ + public final Quaternion4f normalizeLocal() { + + var norm = ExtMath.invSqrt(norm()); + + x *= norm; + y *= norm; + z *= norm; + w *= norm; + + return this; + } + + /** + * Создание случайного разворота. + */ + public void random() { + random(RANDOM_LOCAL.get()); + } + + /** + * Создание случайного разворота. + * + * @param random the random + */ + public void random(Random random) { + + float x = AngleUtils.degreeToRadians(random.nextInt(0, 360)); + float y = AngleUtils.degreeToRadians(random.nextInt(0, 360)); + float z = AngleUtils.degreeToRadians(random.nextInt(0, 360)); + + fromAngles(x, y, z); + } + + /** + * Set quaternion 4 f. + * + * @param rotation the rotation + * @return the quaternion 4 f + */ + public Quaternion4f set(Quaternion4f rotation) { + this.x = rotation.x; + this.y = rotation.y; + this.z = rotation.z; + this.w = rotation.w; + return this; + } + + /** + * Sets xyzw. + * + * @param x the x + * @param y the y + * @param z the z + * @param w the w + */ + public void setXYZW(final float x, final float y, final float z, final float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + /** + * Рассчитывает промежуточный разворот между текуим и указанным в зависимости от указанного %. + * + * @param end конечный разворот. + * @param percent % разворота от текущего к конечному. + */ + public void slerp(Quaternion4f end, float percent) { + if (equals(end)) { + return; + } + + float result = x * end.x + y * end.y + z * end.z + w * end.w; + + if (result < 0.0f) { + end.x = -end.x; + end.y = -end.y; + end.z = -end.z; + end.w = -end.w; + result = -result; + } + + float scale0 = 1 - percent; + float scale1 = percent; + + if (1 - result > 0.1f) { + + final float theta = ExtMath.acos(result); + final float invSinTheta = 1f / ExtMath.sin(theta); + + scale0 = ExtMath.sin((1 - percent) * theta) * invSinTheta; + scale1 = ExtMath.sin(percent * theta) * invSinTheta; + } + + x = scale0 * x + scale1 * end.x; + y = scale0 * y + scale1 * end.y; + z = scale0 * z + scale1 * end.z; + w = scale0 * w + scale1 * end.w; + } + + /** + * Рассчитывает промежуточный разворот от указанного стартового, до указанного конечного в зависимости от указанного + * %. + * + * @param start стартовый разворот. + * @param end конечный разворот. + * @param percent % разворота от стартового до конечного. + * @return the quaternion 4 f + */ + public Quaternion4f slerp(Quaternion4f start, Quaternion4f end, float percent) { + return slerp(start, end, percent, false); + } + + /** + * Рассчитывает промежуточный разворот от указанного стартового, до указанного конечного в зависимости от указанного + * %. + * + * @param start стартовый разворот. + * @param end конечный разворот. + * @param percent % разворота от стартового до конечного. + * @param forceLinear принудительное использование линейной интерполяции. + * @return the quaternion 4 f + */ + public final Quaternion4f slerp(Quaternion4f start, Quaternion4f end, float percent, boolean forceLinear) { + + if (start.equals(end)) { + set(start); + return this; + } + + float result = start.dot(end); + + if (result < 0.0f) { + end.negateLocal(); + result = -result; + } + + float startScale = 1 - percent; + float endScale = percent; + + if (!forceLinear && 1 - result > 0.1f) { + + final float theta = ExtMath.acos(result); + final float invSinTheta = 1f / ExtMath.sin(theta); + + startScale = ExtMath.sin((1 - percent) * theta) * invSinTheta; + endScale = ExtMath.sin(percent * theta) * invSinTheta; + } + + this.x = startScale * start.getX() + endScale * end.getX(); + this.y = startScale * start.getY() + endScale * end.getY(); + this.z = startScale * start.getZ() + endScale * end.getZ(); + this.w = startScale * start.getW() + endScale * end.getW(); + + return this; + } + + /** + * Рассчитывает промежуточный разворот от указанного стартового, до указанного конечного в зависимости от указанного + * %. + * + * @param targetRotation конечный разворот. + * @param percent % разворота от стартового до конечного. + */ + public void nlerp(Quaternion4f targetRotation, float percent) { + + float dot = dot(targetRotation); + float blendI = 1.0F - percent; + + if (dot < 0.0F) { + x = blendI * x - percent * targetRotation.x; + y = blendI * y - percent * targetRotation.y; + z = blendI * z - percent * targetRotation.z; + w = blendI * w - percent * targetRotation.w; + } else { + x = blendI * x + percent * targetRotation.x; + y = blendI * y + percent * targetRotation.y; + z = blendI * z + percent * targetRotation.z; + w = blendI * w + percent * targetRotation.w; + } + + normalizeLocal(); + } + + /** + * Subtract local quaternion 4 f. + * + * @param rotation the rotation + * @return the quaternion 4 f + */ + public Quaternion4f subtractLocal(Quaternion4f rotation) { + this.x -= rotation.x; + this.y -= rotation.y; + this.z -= rotation.z; + this.w -= rotation.w; + return this; + } + + /** + * To angle axis float. + * + * @param axisStore the axis store + * @return the float + */ + public final float toAngleAxis(@Nullable Vector3f axisStore) { + + float sqrLength = x * x + y * y + z * z; + float angle; + + if (sqrLength == 0.0f) { + + angle = 0.0f; + + if (axisStore != null) { + axisStore.setX(1.0F); + axisStore.setY(0.0F); + axisStore.setZ(0.0F); + } + + } else { + + angle = 2.0f * ExtMath.acos(w); + + if (axisStore != null) { + + float invLength = 1.0f / ExtMath.sqrt(sqrLength); + + axisStore.setX(x * invLength); + axisStore.setY(y * invLength); + axisStore.setZ(z * invLength); + } + } + + return angle; + } + + /** + * toAngles returns this quaternion converted to Euler rotation angles (yaw,roll,pitch). Note that + * the result is not always 100% accurate due to the implications of euler angles. + * + * @param angles the float[] in which the angles should be stored, or null if you want a new float[] to be created + * @return the float[] in which the angles are stored. + * @see http://www + * .euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm + */ + public float[] toAngles(float @Nullable [] angles) { + + if (angles == null) { + angles = new float[3]; + } else if (angles.length != 3) { + throw new IllegalArgumentException("Angles array must have three elements"); + } + + float sqw = w * w; + float sqx = x * x; + float sqy = y * y; + float sqz = z * z; + float unit = sqx + sqy + sqz + sqw; // if normalized is one, otherwise + + // is correction factor + float test = x * y + z * w; + if (test > 0.499 * unit) { // singularity at north pole + angles[1] = 2 * ExtMath.atan2(x, w); + angles[2] = ExtMath.HALF_PI; + angles[0] = 0; + } else if (test < -0.499 * unit) { // singularity at south pole + angles[1] = -2 * ExtMath.atan2(x, w); + angles[2] = -ExtMath.HALF_PI; + angles[0] = 0; + } else { + angles[1] = ExtMath.atan2(2 * y * w - 2 * x * z, sqx - sqy - sqz + sqw); // roll + // or + // heading + angles[2] = ExtMath.asin(2 * test / unit); // pitch or attitude + angles[0] = ExtMath.atan2(2 * x * w - 2 * y * z, -sqx + sqy - sqz + sqw); // yaw + // or + // bank + } + return angles; + } + + /** + * Конвектирование квантерниона в матрицу 3х3 + * + * @param result матрица, в которую занести нужно результат. + * @return результат в виде матрицы. + */ + public final Matrix3f toRotationMatrix(Matrix3f result) { + + final float norm = norm(); + + final float s = norm == 1f ? 2f : norm > 0f ? 2f / norm : 0; + + final float x = getX(); + final float y = getY(); + final float z = getZ(); + final float w = getW(); + + final float xs = x * s; + final float ys = y * s; + final float zs = z * s; + final float xx = x * xs; + final float xy = x * ys; + final float xz = x * zs; + final float xw = w * xs; + final float yy = y * ys; + final float yz = y * zs; + final float yw = w * ys; + final float zz = z * zs; + final float zw = w * zs; + + result.set( + 1 - (yy + zz), + xy - zw, + xz + yw, + xy + zw, + 1 - (xx + zz), + yz - xw, + xz - yw, + yz + xw, + 1 - (xx + yy)); + + return result; + } + + /** + * Rotate the vector by this quaternion. + * + * @param vector the vector to rotate. + * @return the same vector which was rotated. + */ + public Vector3f rotate(Vector3f vector) { + + float px = vector.x; + float py = vector.y; + float pz = vector.z; + + float norm = norm(); + float s = norm == 1f ? 2f : norm > 0f ? 2f / norm : 0; + + float x = getX() * s; + float y = getY() * s; + float z = getZ() * s; + float xx = getX() * x; + float xy = getX() * y; + float xz = getX() * z; + float xw = getW() * x; + float yy = getY() * y; + float yz = getY() * z; + float yw = getW() * y; + float zz = getZ() * z; + float zw = getW() * z; + + vector.setX((1f - (yy + zz)) * px + (xy - zw) * py + (xz + yw) * pz); + vector.setY((xy + zw) * px + (1f - (xx + zz)) * py + (yz - xw) * pz); + vector.setZ((xz - yw) * px + (yz - xw) * py + (1f - (xx + yy)) * pz); + + return vector; + } + + @Override + public String toString() { + return "Quaternion4f{" + "x=" + x + ", y=" + y + ", z=" + z + ", w=" + w + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Ray3f.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Ray3f.java index 79d5ab5a..aad31a67 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Ray3f.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Ray3f.java @@ -1,83 +1,82 @@ package javasabr.rlib.common.geom; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of a ray. * * @author JavaSaBr */ +@NullMarked public class Ray3f implements Reusable { - /** - * The start point of this ray. - */ - @NotNull - private final Vector3f start; + /** + * The start point of this ray. + */ + private final Vector3f start; - /** - * The direction of this ray. - */ - @NotNull - private final Vector3f direction; - - /** - * Construct new ray in start point and specified direction. - * - * @param origin start point - * @param direction direction - */ - public Ray3f(@NotNull Vector3f origin, @NotNull Vector3f direction) { - this.start = origin; - this.direction = direction; - } - - /** - * Construct empty ray in zero point and zero direction. - */ - public Ray3f() { - this(new Vector3f(), new Vector3f()); - } + /** + * The direction of this ray. + */ + private final Vector3f direction; - /** - * Get the direction. - * - * @return the direction. - */ - public final @NotNull Vector3f getDirection() { - return direction; - } + /** + * Construct new ray in start point and specified direction. + * + * @param origin start point + * @param direction direction + */ + public Ray3f(Vector3f origin, Vector3f direction) { + this.start = origin; + this.direction = direction; + } - /** - * Set the direction. - * - * @param direction the direction. - */ - public final void setDirection(@NotNull Vector3f direction) { - this.direction.set(direction); - } + /** + * Construct empty ray in zero point and zero direction. + */ + public Ray3f() { + this(new Vector3f(), new Vector3f()); + } - /** - * Get the start point. - * - * @return the start point. - */ - public final @NotNull Vector3f getStart() { - return start; - } + /** + * Get the direction. + * + * @return the direction. + */ + public final Vector3f getDirection() { + return direction; + } - /** - * Set the start point. - * - * @param start the start point. - */ - public final void setStart(@NotNull Vector3f start) { - this.start.set(start); - } + /** + * Set the direction. + * + * @param direction the direction. + */ + public final void setDirection(Vector3f direction) { + this.direction.set(direction); + } - @Override - public String toString() { - return "Ray3f{" + "start=" + start + ", direction=" + direction + '}'; - } + /** + * Get the start point. + * + * @return the start point. + */ + public final Vector3f getStart() { + return start; + } + + /** + * Set the start point. + * + * @param start the start point. + */ + public final void setStart(Vector3f start) { + this.start.set(start); + } + + @Override + public String toString() { + return "Ray3f{" + "start=" + start + ", direction=" + direction + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector2f.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector2f.java index 994d7d1d..6e7f9ecf 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector2f.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector2f.java @@ -4,473 +4,471 @@ import static java.lang.Float.isFinite; import javasabr.rlib.common.util.ExtMath; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * Implementation of float vector in 2D space (two coordinates) - * + * * @author zcxv */ +@NullMarked public class Vector2f implements Cloneable { - public final static Vector2f ZERO = new Vector2f(0, 0); - public final static Vector2f NAN = new Vector2f(Float.NaN, Float.NaN); - - public final static Vector2f UNIT_X = new Vector2f(1, 0); - public final static Vector2f UNIT_Y = new Vector2f(0, 1); - public final static Vector2f UNIT_XYZ = new Vector2f(1, 1); - - public final static Vector2f UNIT_X_NEGATIVE = new Vector2f(-1, 0); - public final static Vector2f UNIT_Y_NEGATIVE = new Vector2f(0, -1); - public final static Vector2f UNIT_XYZ_NEGATIVE = new Vector2f(-1, -1); - - public final static Vector2f POSITIVE_INFINITY = - new Vector2f(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY); - - public final static Vector2f NEGATIVE_INFINITY = - new Vector2f(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); - - /** - * Return true if the vector is not null and valid. - * - * @param vector the vector. - * @return true if the vector is not null and valid. - */ - public static boolean isValid(@Nullable Vector2f vector) { - return vector != null && isFinite(vector.getX()) && isFinite(vector.getY()); - } - - /** - * The X component. - */ - private float x; - - /** - * The Y component. - */ - private float y; - - public Vector2f() { - } - - public Vector2f(float value) { - this.x = value; - this.y = value; - } - - public Vector2f(float x, float y) { - this.x = x; - this.y = y; - } - - public Vector2f(@NotNull float[] components) { - this(components[0], components[1]); - } - - public Vector2f(@NotNull Vector2f another) { - this(another.getX(), another.getY()); - } - - /** - * Add coordinates to this vector. - * - * @param addX x axis value. - * @param addY y axis value. - * @return this vector - */ - public @NotNull Vector2f addLocal(float addX, float addY) { - x += addX; - y += addY; - return this; - } - - /** - * Add the vector to this vector. - * - * @param vector the vector. - * @return this vector. - */ - public @NotNull Vector2f addLocal(@NotNull Vector2f vector) { - return addLocal(vector.x, vector.y); - } - - /** - * Calculate distance to the vector. - * - * @param vector the vector. - * @return the distance. - */ - public float distance(@NotNull Vector2f vector) { - return ExtMath.sqrt(distanceSquared(vector)); - } - - /** - * Calculate squared distance to the coordinates. - * - * @param targetX the target x. - * @param targetY the target y. - * @return the squared distance. - */ - public float distanceSquared(float targetX, float targetY) { - - var dx = x - targetX; - var dy = y - targetY; - - return dx * dx + dy * dy; - } - - /** - * Calculate squared distance to the vector. - * - * @param vector the vector. - * @return the squared distance. - */ - public float distanceSquared(@NotNull Vector2f vector) { - return distanceSquared(vector.x, vector.y); - } - - /** - * Calculate dot to the vector. - * - * @param vector the vector. - * @return the dot product. - */ - public float dot(@NotNull Vector2f vector) { - return x * vector.x + y * vector.y; - } - - /** - * Get the X component. - * - * @return the X component. - */ - public float getX() { - return x; - } - - /** - * Set the X component. - * - * @param x the X component. - * @return this vector. - */ - public @NotNull Vector2f setX(float x) { - this.x = x; - return this; - } - - /** - * Get the Y component. - * - * @return the Y component. - */ - public float getY() { - return y; - } - - /** - * Set the Y component, - * - * @param y the Y component. - * @return this vector. - */ - public @NotNull Vector2f setY(float y) { - this.y = y; - return this; - } - - @Override - public int hashCode() { - var prime = 31; - var result = 1; - result = prime * result + Float.floatToIntBits(x); - result = prime * result + Float.floatToIntBits(y); - return result; - } - - /** - * Return true if all components are zero. - * - * @return true if all components are zero. - */ - public boolean isZero() { - return ExtMath.isZero(x) && ExtMath.isZero(y); - } - - /** - * Multiply this vector by the scalar. - * - * @param scalar the scalar. - * @return this vector. - */ - public @NotNull Vector2f multLocal(float scalar) { - return multLocal(scalar, scalar); - } - - /** - * Multiply this vector by the scalar values. - * - * @param x the x scalar. - * @param y the y scalar. - * @return this vector. - */ - public @NotNull Vector2f multLocal(float x, float y) { - this.x *= x; - this.y *= y; - return this; - } - - /** - * Multiply this vector by the vector. - * - * @param vector the vector. - * @return this vector. - */ - public @NotNull Vector2f multLocal(@NotNull Vector2f vector) { - return multLocal(vector.getX(), vector.getY()); - } - - /** - * Create a new vector as negative version of this vector. - * - * @return the new negative vector. - */ - public @NotNull Vector2f negate() { - return new Vector2f(-getX(), -getY()); - } - - /** - * Invert this vector to get a negative vector. - * - * @return this vector. - */ - public @NotNull Vector2f negateLocal() { - x = -x; - y = -y; - return this; - } - - /** - * Create a normalized vector from this vector. - * - * @return the new normalized vector. - */ - public @NotNull Vector2f normalize() { - - float length = x * x + y * y; + public final static Vector2f ZERO = new Vector2f(0, 0); + public final static Vector2f NAN = new Vector2f(Float.NaN, Float.NaN); + + public final static Vector2f UNIT_X = new Vector2f(1, 0); + public final static Vector2f UNIT_Y = new Vector2f(0, 1); + public final static Vector2f UNIT_XYZ = new Vector2f(1, 1); + + public final static Vector2f UNIT_X_NEGATIVE = new Vector2f(-1, 0); + public final static Vector2f UNIT_Y_NEGATIVE = new Vector2f(0, -1); + public final static Vector2f UNIT_XYZ_NEGATIVE = new Vector2f(-1, -1); + + public final static Vector2f POSITIVE_INFINITY = new Vector2f(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY); + + public final static Vector2f NEGATIVE_INFINITY = new Vector2f(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); + + /** + * Return true if the vector is not null and valid. + * + * @param vector the vector. + * @return true if the vector is not null and valid. + */ + public static boolean isValid(@Nullable Vector2f vector) { + return vector != null && isFinite(vector.getX()) && isFinite(vector.getY()); + } + + /** + * The X component. + */ + private float x; + + /** + * The Y component. + */ + private float y; + + public Vector2f() { + } + + public Vector2f(float value) { + this.x = value; + this.y = value; + } + + public Vector2f(float x, float y) { + this.x = x; + this.y = y; + } + + public Vector2f(float[] components) { + this(components[0], components[1]); + } + + public Vector2f(Vector2f another) { + this(another.getX(), another.getY()); + } + + /** + * Add coordinates to this vector. + * + * @param addX x axis value. + * @param addY y axis value. + * @return this vector + */ + public Vector2f addLocal(float addX, float addY) { + x += addX; + y += addY; + return this; + } + + /** + * Add the vector to this vector. + * + * @param vector the vector. + * @return this vector. + */ + public Vector2f addLocal(Vector2f vector) { + return addLocal(vector.x, vector.y); + } + + /** + * Calculate distance to the vector. + * + * @param vector the vector. + * @return the distance. + */ + public float distance(Vector2f vector) { + return ExtMath.sqrt(distanceSquared(vector)); + } + + /** + * Calculate squared distance to the coordinates. + * + * @param targetX the target x. + * @param targetY the target y. + * @return the squared distance. + */ + public float distanceSquared(float targetX, float targetY) { + + var dx = x - targetX; + var dy = y - targetY; + + return dx * dx + dy * dy; + } + + /** + * Calculate squared distance to the vector. + * + * @param vector the vector. + * @return the squared distance. + */ + public float distanceSquared(Vector2f vector) { + return distanceSquared(vector.x, vector.y); + } + + /** + * Calculate dot to the vector. + * + * @param vector the vector. + * @return the dot product. + */ + public float dot(Vector2f vector) { + return x * vector.x + y * vector.y; + } + + /** + * Get the X component. + * + * @return the X component. + */ + public float getX() { + return x; + } + + /** + * Set the X component. + * + * @param x the X component. + * @return this vector. + */ + public Vector2f setX(float x) { + this.x = x; + return this; + } + + /** + * Get the Y component. + * + * @return the Y component. + */ + public float getY() { + return y; + } + + /** + * Set the Y component, + * + * @param y the Y component. + * @return this vector. + */ + public Vector2f setY(float y) { + this.y = y; + return this; + } + + @Override + public int hashCode() { + var prime = 31; + var result = 1; + result = prime * result + Float.floatToIntBits(x); + result = prime * result + Float.floatToIntBits(y); + return result; + } + + /** + * Return true if all components are zero. + * + * @return true if all components are zero. + */ + public boolean isZero() { + return ExtMath.isZero(x) && ExtMath.isZero(y); + } + + /** + * Multiply this vector by the scalar. + * + * @param scalar the scalar. + * @return this vector. + */ + public Vector2f multLocal(float scalar) { + return multLocal(scalar, scalar); + } + + /** + * Multiply this vector by the scalar values. + * + * @param x the x scalar. + * @param y the y scalar. + * @return this vector. + */ + public Vector2f multLocal(float x, float y) { + this.x *= x; + this.y *= y; + return this; + } + + /** + * Multiply this vector by the vector. + * + * @param vector the vector. + * @return this vector. + */ + public Vector2f multLocal(Vector2f vector) { + return multLocal(vector.getX(), vector.getY()); + } + + /** + * Create a new vector as negative version of this vector. + * + * @return the new negative vector. + */ + public Vector2f negate() { + return new Vector2f(-getX(), -getY()); + } + + /** + * Invert this vector to get a negative vector. + * + * @return this vector. + */ + public Vector2f negateLocal() { + x = -x; + y = -y; + return this; + } + + /** + * Create a normalized vector from this vector. + * + * @return the new normalized vector. + */ + public Vector2f normalize() { + + float length = x * x + y * y; + + if (length != 1F && length != 0F) { + length = 1.0F / ExtMath.sqrt(length); + return new Vector2f(x * length, y * length); + } + + return new Vector2f(x, y); + } + + /** + * Normalize this vector. + * + * @return this vector. + */ + public Vector2f normalizeLocal() { + + float length = x * x + y * y; + + if (length != 1f && length != 0f) { + length = 1.0f / ExtMath.sqrt(length); + x *= length; + y *= length; + } + + return this; + } + + /** + * Set components from the vector to this vector. + * + * @param vector the vector. + * @return this vector. + */ + public Vector2f set(Vector2f vector) { + return set(vector.x, vector.y); + } + + /** + * Set the components to this vector. + * + * @param x x component. + * @param y y component. + * @return this vector. + */ + public Vector2f set(float x, float y) { + this.x = x; + this.y = y; + return this; + } + + /** + * Subtract this vector by the vector and store it to the result vector. + * + * @param vector the vector. + * @param result the result. + * @return the result vector. + */ + public Vector2f subtract(Vector2f vector, Vector2f result) { + result.x = x - vector.x; + result.y = y - vector.y; + return result; + } + + /** + * Subtract the components from this vector. + * + * @param subX the sub x. + * @param subY the sub y. + * @return this changed vector. + */ + public Vector2f subtractLocal(float subX, float subY) { + x -= subX; + y -= subY; + return this; + } + + /** + * Subtract the vector from this vector. + * + * @param vector the vector. + * @return this changed vector. + */ + public Vector2f subtractLocal(Vector2f vector) { + return subtractLocal(vector.x, vector.y); + } + + /** + * Return vector's length (magnitude). + * + * @return the vector's length. + */ + public float length() { + return ExtMath.sqrt(x * x + y * y); + } + + /** + * Return vector's squared length (magnitude). + * + * @return the vector's squared length. + */ + public float sqrLength() { + return x * x + y * y; + } + + /** + * Divide this vector by the components. + * + * @param x the divider x. + * @param y the divider y. + * @return this changed vector. + */ + public Vector2f divideLocal(float x, float y) { + this.x /= x; + this.y /= y; + return this; + } + + /** + * Divide this vector by the vector. + * + * @param vector the divider vector. + * @return this changed vector. + */ + public Vector2f divideLocal(Vector2f vector) { + return divideLocal(vector.x, vector.y); + } + + /** + * Divide this vector by the scalar. + * + * @param scalar the divider scalar. + * @return this changed vector. + */ + public Vector2f divideLocal(float scalar) { + return divideLocal(scalar, scalar); + } + + /** + * Linear time-based interpolation stored to this vector. + * + * @param min the minimal vector + * @param max the maximal vector + * @param t the time + * @return this vector. + */ + public Vector2f lerp(Vector2f min, Vector2f max, float t) { + + t = ExtMath.clamp(t); + + this.x = min.x + (max.x - min.x) * t; + this.y = min.y + (max.y - min.y) * t; + + return this; + } + + @Override + protected Vector2f clone() { + try { + return (Vector2f) super.clone(); + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); + } + } + + /** + * Check vectors to equals with epsilon. + * + * @param vector vector + * @param epsilon epsilon + * @return true if vectors equals + */ + public boolean equals(Vector3f vector, float epsilon) { + return Math.abs(x - vector.getX()) < epsilon && Math.abs(y - vector.getY()) < epsilon; + } + + @Override + public boolean equals(@Nullable Object obj) { + + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } + + var other = (Vector2f) obj; + + if (floatToIntBits(x) != floatToIntBits(other.x)) { + return false; + } else if (floatToIntBits(y) != floatToIntBits(other.y)) { + return false; + } + + return true; + } + + /** + * Return true if these vectors are equal with the epsilon. + * + * @param vector the vector. + * @param epsilon the epsilon. + * @return true if these vectors are equal with the epsilon. + */ + public boolean equals(Vector2f vector, float epsilon) { + return Math.abs(x - vector.getX()) < epsilon && Math.abs(y - vector.getY()) < epsilon; + } + + @Override + public String toString() { + return "Vector2f(" + x + ", " + y + ')'; + } - if (length != 1F && length != 0F) { - length = 1.0F / ExtMath.sqrt(length); - return new Vector2f(x * length, y * length); - } - - return new Vector2f(x, y); - } - - /** - * Normalize this vector. - * - * @return this vector. - */ - public @NotNull Vector2f normalizeLocal() { - - float length = x * x + y * y; - - if (length != 1f && length != 0f) { - length = 1.0f / ExtMath.sqrt(length); - x *= length; - y *= length; - } - - return this; - } - - /** - * Set components from the vector to this vector. - * - * @param vector the vector. - * @return this vector. - */ - public @NotNull Vector2f set(@NotNull Vector2f vector) { - return set(vector.x, vector.y); - } - - /** - * Set the components to this vector. - * - * @param x x component. - * @param y y component. - * @return this vector. - */ - public @NotNull Vector2f set(float x, float y) { - this.x = x; - this.y = y; - return this; - } - - /** - * Subtract this vector by the vector and store it to the result vector. - * - * @param vector the vector. - * @param result the result. - * @return the result vector. - */ - public @NotNull Vector2f subtract(@NotNull Vector2f vector, @NotNull Vector2f result) { - result.x = x - vector.x; - result.y = y - vector.y; - return result; - } - - /** - * Subtract the components from this vector. - * - * @param subX the sub x. - * @param subY the sub y. - * @return this changed vector. - */ - public Vector2f subtractLocal(float subX, float subY) { - x -= subX; - y -= subY; - return this; - } - - /** - * Subtract the vector from this vector. - * - * @param vector the vector. - * @return this changed vector. - */ - public Vector2f subtractLocal(Vector2f vector) { - return subtractLocal(vector.x, vector.y); - } - - /** - * Return vector's length (magnitude). - * - * @return the vector's length. - */ - public float length() { - return ExtMath.sqrt(x * x + y * y); - } - - /** - * Return vector's squared length (magnitude). - * - * @return the vector's squared length. - */ - public float sqrLength() { - return x * x + y * y; - } - - /** - * Divide this vector by the components. - * - * @param x the divider x. - * @param y the divider y. - * @return this changed vector. - */ - public @NotNull Vector2f divideLocal(float x, float y) { - this.x /= x; - this.y /= y; - return this; - } - - /** - * Divide this vector by the vector. - * - * @param vector the divider vector. - * @return this changed vector. - */ - public @NotNull Vector2f divideLocal(Vector2f vector) { - return divideLocal(vector.x, vector.y); - } - - /** - * Divide this vector by the scalar. - * - * @param scalar the divider scalar. - * @return this changed vector. - */ - public @NotNull Vector2f divideLocal(float scalar) { - return divideLocal(scalar, scalar); - } - - /** - * Linear time-based interpolation stored to this vector. - * - * @param min the minimal vector - * @param max the maximal vector - * @param t the time - * @return this vector. - */ - public @NotNull Vector2f lerp(@NotNull Vector2f min, @NotNull Vector2f max, float t) { - - t = ExtMath.clamp(t); - - this.x = min.x + (max.x - min.x) * t; - this.y = min.y + (max.y - min.y) * t; - - return this; - } - - @Override - protected @NotNull Vector2f clone() { - try { - return (Vector2f) super.clone(); - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - } - - /** - * Check vectors to equals with epsilon. - * - * @param vector vector - * @param epsilon epsilon - * @return true if vectors equals - */ - public boolean equals(@NotNull Vector3f vector, float epsilon) { - return Math.abs(x - vector.getX()) < epsilon && Math.abs(y - vector.getY()) < epsilon; - } - - @Override - public boolean equals(@Nullable Object obj) { - - if (this == obj) { - return true; - } else if (obj == null) { - return false; - } else if (getClass() != obj.getClass()) { - return false; - } - - var other = (Vector2f) obj; - - if (floatToIntBits(x) != floatToIntBits(other.x)) { - return false; - } else if (floatToIntBits(y) != floatToIntBits(other.y)) { - return false; - } - - return true; - } - - /** - * Return true if these vectors are equal with the epsilon. - * - * @param vector the vector. - * @param epsilon the epsilon. - * @return true if these vectors are equal with the epsilon. - */ - public boolean equals(@NotNull Vector2f vector, float epsilon) { - return Math.abs(x - vector.getX()) < epsilon && - Math.abs(y - vector.getY()) < epsilon; - } - - @Override - public String toString() { - return "Vector2f(" + x + ", " + y + ')'; - } - } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3f.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3f.java index 2da2b0a4..a1538631 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3f.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3f.java @@ -4,651 +4,637 @@ import static java.lang.Float.isFinite; import javasabr.rlib.common.util.ExtMath; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of vector with 3 float values. * * @author JavaSaBr */ +@NullMarked public final class Vector3f implements Cloneable { - public final static Vector3f ZERO = new Vector3f(0, 0, 0); - public final static Vector3f NAN = new Vector3f(Float.NaN, Float.NaN, Float.NaN); - - public final static Vector3f UNIT_X = new Vector3f(1, 0, 0); - public final static Vector3f UNIT_Y = new Vector3f(0, 1, 0); - public final static Vector3f UNIT_Z = new Vector3f(0, 0, 1); - public final static Vector3f UNIT_XYZ = new Vector3f(1, 1, 1); - - public final static Vector3f UNIT_X_NEGATIVE = new Vector3f(-1, 0, 0); - public final static Vector3f UNIT_Y_NEGATIVE = new Vector3f(0, -1, 0); - public final static Vector3f UNIT_Z_NEGATIVE = new Vector3f(0, 0, -1); - public final static Vector3f UNIT_XYZ_NEGATIVE = new Vector3f(-1, -1, -1); - - public final static Vector3f POSITIVE_INFINITY = new Vector3f(Float.POSITIVE_INFINITY, - Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY); - - public final static Vector3f NEGATIVE_INFINITY = new Vector3f(Float.NEGATIVE_INFINITY, - Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); - - /** - * Return true if the vector is not null and valid. - * - * @param vector the vector. - * @return true if the vector is not null and valid. - */ - public static boolean isValid(@Nullable Vector3f vector) { - return vector != null && - isFinite(vector.getX()) && - isFinite(vector.getY()) && - isFinite(vector.getZ()); - } - - /** - * Get a subtraction result between the two vectors. - * - * @param first the first vector. - * @param second the second vector. - * @return the subtraction result. - */ - public static @NotNull Vector3f substract(@NotNull Vector3f first, @NotNull Vector3f second) { - return first.clone().subtractLocal(second); - } - - /** - * The X component. - */ - protected float x; - - /** - * The Y component. - */ - protected float y; - - /** - * The Z component. - */ - protected float z; - - public Vector3f() { - super(); - } - - public Vector3f(float value) { - this.x = value; - this.y = value; - this.z = value; - } - - public Vector3f(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } - - public Vector3f(@NotNull float[] components) { - this(components[0], components[1], components[2]); - } - - public Vector3f(@NotNull Vector3f another) { - this(another.getX(), another.getY(), another.getZ()); - } - - /** - * Add the values to this vector. - * - * @param addX x axis value. - * @param addY y axis value. - * @param addZ z axis value. - * @return this vector. - */ - public @NotNull Vector3f addLocal(float addX, float addY, float addZ) { - x += addX; - y += addY; - z += addZ; - return this; - } - - /** - * Add the vector to this vector. - * - * @param vector the vector. - * @return this vector. - */ - public @NotNull Vector3f addLocal(@NotNull Vector3f vector) { - return addLocal(vector.x, vector.y, vector.z); - } - - /** - * Calculate a cross vector between this vector and the coordinates. - * - * @param otherX the other x - * @param otherY the other y - * @param otherZ the other z - * @param result the result vector. - * @return the result vector. - */ - public @NotNull Vector3f cross( - float otherX, - float otherY, - float otherZ, - @NotNull Vector3f result - ) { - - var resX = y * otherZ - z * otherY; - var resY = z * otherX - x * otherZ; - var resZ = x * otherY - y * otherX; - - result.set(resX, resY, resZ); - - return result; - } - - /** - * Calculate a cross vector between this vector and the vector. - * - * @param vector the vector. - * @return the result vector. - */ - public @NotNull Vector3f cross(@NotNull Vector3f vector) { - return cross(vector, new Vector3f()); - } - - /** - * Calculate a cross vector between this vector and the vector. - * - * @param vector the vector. - * @param result the result vector to store result. - * @return the result vector. - */ - public @NotNull Vector3f cross(@NotNull Vector3f vector, @NotNull Vector3f result) { - return cross(vector.x, vector.y, vector.z, result); - } - - /** - * Calculate a cross vector between this vector and the coordinates and store the result to this vector. - * - * @param otherX the other x. - * @param otherY the other y. - * @param otherZ the other z. - * @return this changed vector. - */ - public @NotNull Vector3f crossLocal(float otherX, float otherY, float otherZ) { - - var tempx = y * otherZ - z * otherY; - var tempy = z * otherX - x * otherZ; - - z = x * otherY - y * otherX; - x = tempx; - y = tempy; - - return this; - } - - /** - * Calculate a cross vector between this vector and the coordinates and store the result to this vector. - * - * @param vector the vector. - * @return this changed vector. - */ - public @NotNull Vector3f crossLocal(@NotNull Vector3f vector) { - return crossLocal(vector.x, vector.y, vector.z); - } - - /** - * Calculate distance to the vector. - * - * @param vector the vector. - * @return the distance. - */ - public float distance(@NotNull Vector3f vector) { - return ExtMath.sqrt(distanceSquared(vector)); - } - - /** - * Calculate squared distance to the coordinates. - * - * @param targetX the target x. - * @param targetY the target y. - * @param targetZ the target z. - * @return the squared distance. - */ - public float distanceSquared(float targetX, float targetY, float targetZ) { - - var dx = x - targetX; - var dy = y - targetY; - var dz = z - targetZ; - - return dx * dx + dy * dy + dz * dz; - } - - /** - * Calculate squared distance to the vector. - * - * @param vector the vector. - * @return the squared distance. - */ - public float distanceSquared(@NotNull Vector3f vector) { - return distanceSquared(vector.x, vector.y, vector.z); - } - - /** - * Calculate dot to the vector. - * - * @param vector the vector. - * @return the dot product. - */ - public float dot(@NotNull Vector3f vector) { - return x * vector.x + y * vector.y + z * vector.z; - } - - /** - * Get the X component. - * - * @return the X component. - */ - public float getX() { - return x; - } - - /** - * Set the X component. - * - * @param x the X component. - * @return this vector. - */ - public @NotNull Vector3f setX(float x) { - this.x = x; - return this; - } - - /** - * Get the Y component. - * - * @return the Y component. - */ - public float getY() { - return y; - } - - /** - * Set the Y component, - * - * @param y the Y component. - * @return this vector. - */ - public @NotNull Vector3f setY(float y) { - this.y = y; - return this; - } - - /** - * Get the Z component. - * - * @return the Z component. - */ - public float getZ() { - return z; - } - - /** - * Set the Z component, - * - * @param z the Z component. - * @return this vector. - */ - public @NotNull Vector3f setZ(float z) { - this.z = z; - return this; - } - - @Override - public int hashCode() { - var prime = 31; - var result = 1; - result = prime * result + Float.floatToIntBits(x); - result = prime * result + Float.floatToIntBits(y); - result = prime * result + Float.floatToIntBits(z); - return result; - } - - /** - * Return true if all components are zero. - * - * @return true if all components are zero. - */ - public boolean isZero() { - return this == ZERO || - ExtMath.isZero(x) && - ExtMath.isZero(y) && - ExtMath.isZero(z); - } - - /** - * Multiply this vector by the scalar. - * - * @param scalar the scalar. - * @return this vector. - */ - public Vector3f multLocal(float scalar) { - return multLocal(scalar, scalar, scalar); - } - - /** - * Multiply this vector by the scalar values. - * - * @param x the x scalar. - * @param y the y scalar. - * @param z the z scalar. - * @return this vector. - */ - public @NotNull Vector3f multLocal(float x, float y, float z) { - this.x *= x; - this.y *= y; - this.z *= z; - return this; - } - - /** - * Multiply this vector by the vector. - * - * @param vector the vector. - * @return this vector. - */ - public @NotNull Vector3f multLocal(@NotNull Vector3f vector) { - return multLocal(vector.getX(), vector.getY(), vector.getZ()); - } - - /** - * Create a new vector as negative version of this vector. - * - * @return the new negative vector. - */ - public @NotNull Vector3f negate() { - return new Vector3f(-getX(), -getY(), -getZ()); - } - - /** - * Invert this vector to get a negative vector. - * - * @return this vector. - */ - public @NotNull Vector3f negateLocal() { - x = -x; - y = -y; - z = -z; - return this; - } - - /** - * Create a normalized vector from this vector. - * - * @return the new normalized vector. - */ - public @NotNull Vector3f normalize() { - - var length = x * x + y * y + z * z; - - if (length != 1F && length != 0F) { - length = 1.0F / ExtMath.sqrt(length); - return new Vector3f(x * length, y * length, z * length); - } - - return new Vector3f(x, y, z); - } - - /** - * Normalize this vector. - * - * @return this vector. - */ - public @NotNull Vector3f normalizeLocal() { - - var length = x * x + y * y + z * z; - - if (length != 1f && length != 0f) { - length = 1.0f / ExtMath.sqrt(length); - x *= length; - y *= length; - z *= length; - } - - return this; - } - - /** - * Set components from the vector to this vector. - * - * @param vector the vector. - * @return this vector. - */ - public @NotNull Vector3f set(@NotNull Vector3f vector) { - return set(vector.x, vector.y, vector.z); - } - - /** - * Set the components to this vector. - * - * @param x x component. - * @param y y component. - * @param z z component. - * @return this vector. - */ - public @NotNull Vector3f set(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - return this; - } - - /** - * Subtract the vector from this vector and store the result to the result vector. - * - * @param vector the vector. - * @param result the result. - * @return the result vector. - */ - public @NotNull Vector3f subtract(@NotNull Vector3f vector, @NotNull Vector3f result) { - result.x = x - vector.x; - result.y = y - vector.y; - result.z = z - vector.z; - return result; - } - - /** - * Subtract the components from this vector. - * - * @param subX the sub x. - * @param subY the sub y. - * @param subZ the sub z. - * @return this changed vector. - */ - public @NotNull Vector3f subtractLocal(float subX, float subY, float subZ) { - x -= subX; - y -= subY; - z -= subZ; - return this; - } - - /** - * Subtract the vector from this vector. - * - * @param vector the vector. - * @return this changed vector. - */ - public @NotNull Vector3f subtractLocal(@NotNull Vector3f vector) { - return subtractLocal(vector.x, vector.y, vector.z); - } - - /** - * Return vector's length (magnitude). - * - * @return the vector's length. - */ - public float length() { - return ExtMath.sqrt(x * x + y * y + z * z); - } - - /** - * Return vector's squared length (magnitude). - * - * @return the vector's squared length. - */ - public float sqrLength() { - return x * x + y * y + z * z; - } - - /** - * Divide this vector by the components. - * - * @param x the divider x. - * @param y the divider y. - * @param z the divider z. - * @return this changed vector. - */ - public @NotNull Vector3f divideLocal(float x, float y, float z) { - this.x /= x; - this.y /= y; - this.z /= z; - return this; - } - - /** - * Divide this vector by the vector. - * - * @param vector the divider vector. - * @return this changed vector. - */ - public @NotNull Vector3f divideLocal(@NotNull Vector3f vector) { - return divideLocal(vector.x, vector.y, vector.z); - } - - /** - * Divide this vector by the scalar. - * - * @param scalar the divider scalar. - * @return this changed vector. - */ - public @NotNull Vector3f divideLocal(float scalar) { - return divideLocal(scalar, scalar, scalar); - } - - /** - * Move this vector to a new point by specified direction. - * - * @param direction move direction. - * @param distance move distance. - * @return this changed vector. - */ - public @NotNull Vector3f moveToDirection(@NotNull Vector3f direction, float distance) { - return addLocal( - direction.getX() * distance, - direction.getY() * distance, - direction.getZ() * distance - ); - } - - /** - * Move this vector to destination vector. - * If distance argument is greater or equal to real distance between this vector and - * destination vector then coordinates will be set to equal destination. - * - * @param destination destination vector - * @param distance move distance - * @return this vector with new position - */ - public @NotNull Vector3f moveToPoint(@NotNull Vector3f destination, float distance) { - - Vector3f direction = new Vector3f(destination) - .subtractLocal(this); - - double length = Math.sqrt( - direction.getX() * direction.getX() + - direction.getY() * direction.getY() + - direction.getZ() * direction.getZ() - ); - - if (length <= distance || length < ExtMath.EPSILON) { - set(destination); - return this; - } - - // normalize vector by exists length: - // avoid new vector length calculation via normalizeLocal - direction.divideLocal((float) length); - - return moveToDirection(direction, distance); - } - - /** - * Linear time-based interpolation stored to this vector. - * - * @param min the minimal vector. - * @param max the maximal vector. - * @param t the time. - * @return this vector. - */ - public Vector3f lerp(@NotNull Vector3f min, @NotNull Vector3f max, float t) { - - t = ExtMath.clamp(t); - - this.x = min.x + (max.x - min.x) * t; - this.y = min.y + (max.y - min.y) * t; - this.z = min.z + (max.z - min.z) * t; - - return this; - } - - @Override - protected @NotNull Vector3f clone() { - try { - return (Vector3f) super.clone(); - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(@Nullable Object obj) { - - if (this == obj) { - return true; - } else if (obj == null) { - return false; - } else if (getClass() != obj.getClass()) { - return false; - } - - var other = (Vector3f) obj; - - if (floatToIntBits(x) != floatToIntBits(other.x)) { - return false; - } else if (floatToIntBits(y) != floatToIntBits(other.y)) { - return false; - } else if (floatToIntBits(z) != floatToIntBits(other.z)) { - return false; - } - - return true; - } - - /** - * Return true if these vectors are equal with the epsilon. - * - * @param vector the vector. - * @param epsilon the epsilon. - * @return true if these vectors are equal with the epsilon. - */ - public boolean equals(@NotNull Vector3f vector, float epsilon) { - return Math.abs(x - vector.getX()) < epsilon && - Math.abs(y - vector.getY()) < epsilon && - Math.abs(z - vector.getZ()) < epsilon; - } - - @Override - public String toString() { - return "Vector3f(" + x + ", " + y + ", " + z + ')'; - } + public final static Vector3f ZERO = new Vector3f(0, 0, 0); + public final static Vector3f NAN = new Vector3f(Float.NaN, Float.NaN, Float.NaN); + + public final static Vector3f UNIT_X = new Vector3f(1, 0, 0); + public final static Vector3f UNIT_Y = new Vector3f(0, 1, 0); + public final static Vector3f UNIT_Z = new Vector3f(0, 0, 1); + public final static Vector3f UNIT_XYZ = new Vector3f(1, 1, 1); + + public final static Vector3f UNIT_X_NEGATIVE = new Vector3f(-1, 0, 0); + public final static Vector3f UNIT_Y_NEGATIVE = new Vector3f(0, -1, 0); + public final static Vector3f UNIT_Z_NEGATIVE = new Vector3f(0, 0, -1); + public final static Vector3f UNIT_XYZ_NEGATIVE = new Vector3f(-1, -1, -1); + + public final static Vector3f POSITIVE_INFINITY = new Vector3f( + Float.POSITIVE_INFINITY, + Float.POSITIVE_INFINITY, + Float.POSITIVE_INFINITY); + + public final static Vector3f NEGATIVE_INFINITY = new Vector3f( + Float.NEGATIVE_INFINITY, + Float.NEGATIVE_INFINITY, + Float.NEGATIVE_INFINITY); + + /** + * Return true if the vector is not null and valid. + * + * @param vector the vector. + * @return true if the vector is not null and valid. + */ + public static boolean isValid(@Nullable Vector3f vector) { + return vector != null && isFinite(vector.getX()) && isFinite(vector.getY()) && isFinite(vector.getZ()); + } + + /** + * Get a subtraction result between the two vectors. + * + * @param first the first vector. + * @param second the second vector. + * @return the subtraction result. + */ + public static Vector3f substract(Vector3f first, Vector3f second) { + return first + .clone() + .subtractLocal(second); + } + + /** + * The X component. + */ + protected float x; + + /** + * The Y component. + */ + protected float y; + + /** + * The Z component. + */ + protected float z; + + public Vector3f() { + super(); + } + + public Vector3f(float value) { + this.x = value; + this.y = value; + this.z = value; + } + + public Vector3f(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + public Vector3f(float[] components) { + this(components[0], components[1], components[2]); + } + + public Vector3f(Vector3f another) { + this(another.getX(), another.getY(), another.getZ()); + } + + /** + * Add the values to this vector. + * + * @param addX x axis value. + * @param addY y axis value. + * @param addZ z axis value. + * @return this vector. + */ + public Vector3f addLocal(float addX, float addY, float addZ) { + x += addX; + y += addY; + z += addZ; + return this; + } + + /** + * Add the vector to this vector. + * + * @param vector the vector. + * @return this vector. + */ + public Vector3f addLocal(Vector3f vector) { + return addLocal(vector.x, vector.y, vector.z); + } + + /** + * Calculate a cross vector between this vector and the coordinates. + * + * @param otherX the other x + * @param otherY the other y + * @param otherZ the other z + * @param result the result vector. + * @return the result vector. + */ + public Vector3f cross(float otherX, float otherY, float otherZ, Vector3f result) { + + var resX = y * otherZ - z * otherY; + var resY = z * otherX - x * otherZ; + var resZ = x * otherY - y * otherX; + + result.set(resX, resY, resZ); + + return result; + } + + /** + * Calculate a cross vector between this vector and the vector. + * + * @param vector the vector. + * @return the result vector. + */ + public Vector3f cross(Vector3f vector) { + return cross(vector, new Vector3f()); + } + + /** + * Calculate a cross vector between this vector and the vector. + * + * @param vector the vector. + * @param result the result vector to store result. + * @return the result vector. + */ + public Vector3f cross(Vector3f vector, Vector3f result) { + return cross(vector.x, vector.y, vector.z, result); + } + + /** + * Calculate a cross vector between this vector and the coordinates and store the result to this vector. + * + * @param otherX the other x. + * @param otherY the other y. + * @param otherZ the other z. + * @return this changed vector. + */ + public Vector3f crossLocal(float otherX, float otherY, float otherZ) { + + var tempx = y * otherZ - z * otherY; + var tempy = z * otherX - x * otherZ; + + z = x * otherY - y * otherX; + x = tempx; + y = tempy; + + return this; + } + + /** + * Calculate a cross vector between this vector and the coordinates and store the result to this vector. + * + * @param vector the vector. + * @return this changed vector. + */ + public Vector3f crossLocal(Vector3f vector) { + return crossLocal(vector.x, vector.y, vector.z); + } + + /** + * Calculate distance to the vector. + * + * @param vector the vector. + * @return the distance. + */ + public float distance(Vector3f vector) { + return ExtMath.sqrt(distanceSquared(vector)); + } + + /** + * Calculate squared distance to the coordinates. + * + * @param targetX the target x. + * @param targetY the target y. + * @param targetZ the target z. + * @return the squared distance. + */ + public float distanceSquared(float targetX, float targetY, float targetZ) { + + var dx = x - targetX; + var dy = y - targetY; + var dz = z - targetZ; + + return dx * dx + dy * dy + dz * dz; + } + + /** + * Calculate squared distance to the vector. + * + * @param vector the vector. + * @return the squared distance. + */ + public float distanceSquared(Vector3f vector) { + return distanceSquared(vector.x, vector.y, vector.z); + } + + /** + * Calculate dot to the vector. + * + * @param vector the vector. + * @return the dot product. + */ + public float dot(Vector3f vector) { + return x * vector.x + y * vector.y + z * vector.z; + } + + /** + * Get the X component. + * + * @return the X component. + */ + public float getX() { + return x; + } + + /** + * Set the X component. + * + * @param x the X component. + * @return this vector. + */ + public Vector3f setX(float x) { + this.x = x; + return this; + } + + /** + * Get the Y component. + * + * @return the Y component. + */ + public float getY() { + return y; + } + + /** + * Set the Y component, + * + * @param y the Y component. + * @return this vector. + */ + public Vector3f setY(float y) { + this.y = y; + return this; + } + + /** + * Get the Z component. + * + * @return the Z component. + */ + public float getZ() { + return z; + } + + /** + * Set the Z component, + * + * @param z the Z component. + * @return this vector. + */ + public Vector3f setZ(float z) { + this.z = z; + return this; + } + + @Override + public int hashCode() { + var prime = 31; + var result = 1; + result = prime * result + Float.floatToIntBits(x); + result = prime * result + Float.floatToIntBits(y); + result = prime * result + Float.floatToIntBits(z); + return result; + } + + /** + * Return true if all components are zero. + * + * @return true if all components are zero. + */ + public boolean isZero() { + return this == ZERO || ExtMath.isZero(x) && ExtMath.isZero(y) && ExtMath.isZero(z); + } + + /** + * Multiply this vector by the scalar. + * + * @param scalar the scalar. + * @return this vector. + */ + public Vector3f multLocal(float scalar) { + return multLocal(scalar, scalar, scalar); + } + + /** + * Multiply this vector by the scalar values. + * + * @param x the x scalar. + * @param y the y scalar. + * @param z the z scalar. + * @return this vector. + */ + public Vector3f multLocal(float x, float y, float z) { + this.x *= x; + this.y *= y; + this.z *= z; + return this; + } + + /** + * Multiply this vector by the vector. + * + * @param vector the vector. + * @return this vector. + */ + public Vector3f multLocal(Vector3f vector) { + return multLocal(vector.getX(), vector.getY(), vector.getZ()); + } + + /** + * Create a new vector as negative version of this vector. + * + * @return the new negative vector. + */ + public Vector3f negate() { + return new Vector3f(-getX(), -getY(), -getZ()); + } + + /** + * Invert this vector to get a negative vector. + * + * @return this vector. + */ + public Vector3f negateLocal() { + x = -x; + y = -y; + z = -z; + return this; + } + + /** + * Create a normalized vector from this vector. + * + * @return the new normalized vector. + */ + public Vector3f normalize() { + + var length = x * x + y * y + z * z; + + if (length != 1F && length != 0F) { + length = 1.0F / ExtMath.sqrt(length); + return new Vector3f(x * length, y * length, z * length); + } + + return new Vector3f(x, y, z); + } + + /** + * Normalize this vector. + * + * @return this vector. + */ + public Vector3f normalizeLocal() { + + var length = x * x + y * y + z * z; + + if (length != 1f && length != 0f) { + length = 1.0f / ExtMath.sqrt(length); + x *= length; + y *= length; + z *= length; + } + + return this; + } + + /** + * Set components from the vector to this vector. + * + * @param vector the vector. + * @return this vector. + */ + public Vector3f set(Vector3f vector) { + return set(vector.x, vector.y, vector.z); + } + + /** + * Set the components to this vector. + * + * @param x x component. + * @param y y component. + * @param z z component. + * @return this vector. + */ + public Vector3f set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + + /** + * Subtract the vector from this vector and store the result to the result vector. + * + * @param vector the vector. + * @param result the result. + * @return the result vector. + */ + public Vector3f subtract(Vector3f vector, Vector3f result) { + result.x = x - vector.x; + result.y = y - vector.y; + result.z = z - vector.z; + return result; + } + + /** + * Subtract the components from this vector. + * + * @param subX the sub x. + * @param subY the sub y. + * @param subZ the sub z. + * @return this changed vector. + */ + public Vector3f subtractLocal(float subX, float subY, float subZ) { + x -= subX; + y -= subY; + z -= subZ; + return this; + } + + /** + * Subtract the vector from this vector. + * + * @param vector the vector. + * @return this changed vector. + */ + public Vector3f subtractLocal(Vector3f vector) { + return subtractLocal(vector.x, vector.y, vector.z); + } + + /** + * Return vector's length (magnitude). + * + * @return the vector's length. + */ + public float length() { + return ExtMath.sqrt(x * x + y * y + z * z); + } + + /** + * Return vector's squared length (magnitude). + * + * @return the vector's squared length. + */ + public float sqrLength() { + return x * x + y * y + z * z; + } + + /** + * Divide this vector by the components. + * + * @param x the divider x. + * @param y the divider y. + * @param z the divider z. + * @return this changed vector. + */ + public Vector3f divideLocal(float x, float y, float z) { + this.x /= x; + this.y /= y; + this.z /= z; + return this; + } + + /** + * Divide this vector by the vector. + * + * @param vector the divider vector. + * @return this changed vector. + */ + public Vector3f divideLocal(Vector3f vector) { + return divideLocal(vector.x, vector.y, vector.z); + } + + /** + * Divide this vector by the scalar. + * + * @param scalar the divider scalar. + * @return this changed vector. + */ + public Vector3f divideLocal(float scalar) { + return divideLocal(scalar, scalar, scalar); + } + + /** + * Move this vector to a new point by specified direction. + * + * @param direction move direction. + * @param distance move distance. + * @return this changed vector. + */ + public Vector3f moveToDirection(Vector3f direction, float distance) { + return addLocal(direction.getX() * distance, direction.getY() * distance, direction.getZ() * distance); + } + + /** + * Move this vector to destination vector. If distance argument is greater or equal to real distance between this + * vector and destination vector then coordinates will be set to equal destination. + * + * @param destination destination vector + * @param distance move distance + * @return this vector with new position + */ + public Vector3f moveToPoint(Vector3f destination, float distance) { + + Vector3f direction = new Vector3f(destination).subtractLocal(this); + + double length = Math.sqrt(direction.getX() * direction.getX() + direction.getY() * direction.getY() + + direction.getZ() * direction.getZ()); + + if (length <= distance || length < ExtMath.EPSILON) { + set(destination); + return this; + } + + // normalize vector by exists length: + // avoid new vector length calculation via normalizeLocal + direction.divideLocal((float) length); + + return moveToDirection(direction, distance); + } + + /** + * Linear time-based interpolation stored to this vector. + * + * @param min the minimal vector. + * @param max the maximal vector. + * @param t the time. + * @return this vector. + */ + public Vector3f lerp(Vector3f min, Vector3f max, float t) { + + t = ExtMath.clamp(t); + + this.x = min.x + (max.x - min.x) * t; + this.y = min.y + (max.y - min.y) * t; + this.z = min.z + (max.z - min.z) * t; + + return this; + } + + @Override + protected Vector3f clone() { + try { + return (Vector3f) super.clone(); + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean equals(@Nullable Object obj) { + + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } + + var other = (Vector3f) obj; + + if (floatToIntBits(x) != floatToIntBits(other.x)) { + return false; + } else if (floatToIntBits(y) != floatToIntBits(other.y)) { + return false; + } else if (floatToIntBits(z) != floatToIntBits(other.z)) { + return false; + } + + return true; + } + + /** + * Return true if these vectors are equal with the epsilon. + * + * @param vector the vector. + * @param epsilon the epsilon. + * @return true if these vectors are equal with the epsilon. + */ + public boolean equals(Vector3f vector, float epsilon) { + return Math.abs(x - vector.getX()) < epsilon && Math.abs(y - vector.getY()) < epsilon + && Math.abs(z - vector.getZ()) < epsilon; + } + + @Override + public String toString() { + return "Vector3f(" + x + ", " + y + ", " + z + ')'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3fBuffer.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3fBuffer.java index 0a71d532..0454bfa6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3fBuffer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/Vector3fBuffer.java @@ -1,58 +1,59 @@ package javasabr.rlib.common.geom; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a buffer of vectors. * * @author JavaSaBr */ +@NullMarked public interface Vector3fBuffer { - Vector3fBuffer NO_REUSE = new Vector3fBuffer() { - - @Override - public @NotNull Vector3f nextVector() { - return new Vector3f(); - } - - @Override - public @NotNull Vector3f next(@NotNull Vector3f source) { - return new Vector3f(source); - } - - @Override - public @NotNull Vector3f next(float x, float y, float z) { - return new Vector3f(x, y, z); - } - }; - - /** - * Take a next free vector. - * - * @return the next vector. - */ - @NotNull Vector3f nextVector(); - - /** - * Take a next free vector with copied values from the source vector. - * - * @param source the source vector. - * @return the next free vector with copied values. - */ - default @NotNull Vector3f next(@NotNull Vector3f source) { - return nextVector().set(source); + Vector3fBuffer NO_REUSE = new Vector3fBuffer() { + + @Override + public Vector3f nextVector() { + return new Vector3f(); + } + + @Override + public Vector3f next(Vector3f source) { + return new Vector3f(source); } - /** - * Take a next free vector with copied values. - * - * @param x the X component. - * @param y the Y component. - * @param z the Z component. - * @return the next free vector with copied values. - */ - default @NotNull Vector3f next(float x, float y, float z) { - return nextVector().set(x, y, z); + @Override + public Vector3f next(float x, float y, float z) { + return new Vector3f(x, y, z); } + }; + + /** + * Take a next free vector. + * + * @return the next vector. + */ + Vector3f nextVector(); + + /** + * Take a next free vector with copied values from the source vector. + * + * @param source the source vector. + * @return the next free vector with copied values. + */ + default Vector3f next(Vector3f source) { + return nextVector().set(source); + } + + /** + * Take a next free vector with copied values. + * + * @param x the X component. + * @param y the Y component. + * @param z the Z component. + * @return the next free vector with copied values. + */ + default Vector3f next(float x, float y, float z) { + return nextVector().set(x, y, z); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/Bounding.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/Bounding.java index 5e236103..41872d06 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/Bounding.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/Bounding.java @@ -4,132 +4,132 @@ import javasabr.rlib.common.geom.Ray3f; import javasabr.rlib.common.geom.Vector3f; import javasabr.rlib.common.geom.Vector3fBuffer; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a bounding of objects. * * @author JavaSaBr */ +@NullMarked public interface Bounding { - - /** - * Return true if this bounding contains the point. - * - * @param x the X coordinate. - * @param y the Y coordinate. - * @param z the X coordinate. - * @return true if this bounding contains the point. - */ - boolean contains(float x, float y, float z); - - /** - * Return true if this bounding contains the point. - * - * @param point the point. - * @return true if this bounding contains the point. - */ - boolean contains(@NotNull Vector3f point); - - /** - * Get a distance from a center of a bounding to a point. - * - * @param point the point. - * @return the distance. - */ - float distanceTo(@NotNull Vector3f point); - - /** - * Get a type of a bounding. - * - * @return the type. - */ - @NotNull BoundingType getBoundingType(); - - /** - * Get a center of a bounding. - * - * @return the center. - */ - @NotNull Vector3f getCenter(); - - /** - * Change a center of a bounding. - * - * @param center the new center. - */ - void setCenter(@NotNull Vector3f center); - - /** - * Get an offset of a bounding. - * - * @return the offset. - */ - @NotNull Vector3f getOffset(); - - /** - * Get a result center of this bounding. - * - * @param buffer the vector buffer. - * @return the result center. - */ - @NotNull Vector3f getResultCenter(@NotNull Vector3fBuffer buffer); - - /** - * Get a result X coordinate of the center of this bounding. - * - * @return the result X coordinate. - */ - float getResultCenterX(); - - /** - * Get a result Y coordinate of the center of this bounding. - * - * @return the result Y coordinate. - */ - float getResultCenterY(); - - /** - * Get a result Z coordinate of the center of this bounding. - * - * @return the result X coordinate. - */ - float getResultCenterZ(); - - /** - * Check this bounding that it intersects with an other bounding. - * - * @param bounding the other bounding. - * @param buffer the vector buffer. - * @return true if this bounding interests with other bounding. - */ - boolean intersects(@NotNull Bounding bounding, @NotNull Vector3fBuffer buffer); - - /** - * Check this bounding that it intersects with a ray. - * - * @param ray the ray. - * @param buffer the vector buffer. - * @return true if this bounding interests with the ray. - */ - boolean intersects(@NotNull Ray3f ray, @NotNull Vector3fBuffer buffer); - - /** - * Check this bounding that it intersects with a ray. - * - * @param start the start point of the ray. - * @param direction the direction of the ray. - * @param buffer the vector buffer. - * @return true if this bounding interests with the ray. - */ - boolean intersects(@NotNull Vector3f start, @NotNull Vector3f direction, @NotNull Vector3fBuffer buffer); - - /** - * Update a rotation of a bounding. - * - * @param rotation the rotation. - * @param buffer the vector buffer. - */ - void update(@NotNull Quaternion4f rotation, @NotNull Vector3fBuffer buffer); + /** + * Return true if this bounding contains the point. + * + * @param x the X coordinate. + * @param y the Y coordinate. + * @param z the X coordinate. + * @return true if this bounding contains the point. + */ + boolean contains(float x, float y, float z); + + /** + * Return true if this bounding contains the point. + * + * @param point the point. + * @return true if this bounding contains the point. + */ + boolean contains(Vector3f point); + + /** + * Get a distance from a center of a bounding to a point. + * + * @param point the point. + * @return the distance. + */ + float distanceTo(Vector3f point); + + /** + * Get a type of a bounding. + * + * @return the type. + */ + BoundingType getBoundingType(); + + /** + * Get a center of a bounding. + * + * @return the center. + */ + Vector3f getCenter(); + + /** + * Change a center of a bounding. + * + * @param center the new center. + */ + void setCenter(Vector3f center); + + /** + * Get an offset of a bounding. + * + * @return the offset. + */ + Vector3f getOffset(); + + /** + * Get a result center of this bounding. + * + * @param buffer the vector buffer. + * @return the result center. + */ + Vector3f getResultCenter(Vector3fBuffer buffer); + + /** + * Get a result X coordinate of the center of this bounding. + * + * @return the result X coordinate. + */ + float getResultCenterX(); + + /** + * Get a result Y coordinate of the center of this bounding. + * + * @return the result Y coordinate. + */ + float getResultCenterY(); + + /** + * Get a result Z coordinate of the center of this bounding. + * + * @return the result X coordinate. + */ + float getResultCenterZ(); + + /** + * Check this bounding that it intersects with an other bounding. + * + * @param bounding the other bounding. + * @param buffer the vector buffer. + * @return true if this bounding interests with other bounding. + */ + boolean intersects(Bounding bounding, Vector3fBuffer buffer); + + /** + * Check this bounding that it intersects with a ray. + * + * @param ray the ray. + * @param buffer the vector buffer. + * @return true if this bounding interests with the ray. + */ + boolean intersects(Ray3f ray, Vector3fBuffer buffer); + + /** + * Check this bounding that it intersects with a ray. + * + * @param start the start point of the ray. + * @param direction the direction of the ray. + * @param buffer the vector buffer. + * @return true if this bounding interests with the ray. + */ + boolean intersects(Vector3f start, Vector3f direction, Vector3fBuffer buffer); + + /** + * Update a rotation of a bounding. + * + * @param rotation the rotation. + * @param buffer the vector buffer. + */ + void update(Quaternion4f rotation, Vector3fBuffer buffer); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingFactory.java index ea28b587..22d30738 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingFactory.java @@ -4,61 +4,57 @@ import javasabr.rlib.common.geom.bounding.impl.AbstractBounding; import javasabr.rlib.common.geom.bounding.impl.AxisAlignedBoundingBox; import javasabr.rlib.common.geom.bounding.impl.BoundingSphere; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The bounding's factory. * * @author JavaSaBr */ +@NullMarked public final class BoundingFactory { - /** - * Creates a new bounding box. - * - * @param center the center. - * @param offset the offset. - * @param sizeX the size x. - * @param sizeY the size y. - * @param sizeZ the size z. - * @return the new bounding box. - */ - public static Bounding newBoundingBox( - @NotNull Vector3f center, - @NotNull Vector3f offset, - float sizeX, - float sizeY, - float sizeZ - ) { - return new AxisAlignedBoundingBox(center, offset, sizeX, sizeY, sizeZ); - } + /** + * Creates a new bounding box. + * + * @param center the center. + * @param offset the offset. + * @param sizeX the size x. + * @param sizeY the size y. + * @param sizeZ the size z. + * @return the new bounding box. + */ + public static Bounding newBoundingBox( + Vector3f center, + Vector3f offset, + float sizeX, + float sizeY, + float sizeZ) { + return new AxisAlignedBoundingBox(center, offset, sizeX, sizeY, sizeZ); + } - /** - * Creates a new empty bounding. - * - * @return the new empty bounding. - */ - public static Bounding newBoundingEmpty() { - return new AbstractBounding(new Vector3f(), new Vector3f()) {}; - } + /** + * Creates a new empty bounding. + * + * @return the new empty bounding. + */ + public static Bounding newBoundingEmpty() { + return new AbstractBounding(new Vector3f(), new Vector3f()) {}; + } - /** - * Creates a new bounding sphere. - * - * @param center the center. - * @param offset the offset. - * @param radius the radius. - * @return the bounding sphere. - */ - public static Bounding newBoundingSphere( - @NotNull Vector3f center, - @NotNull Vector3f offset, - float radius - ) { - return new BoundingSphere(center, offset, radius); - } + /** + * Creates a new bounding sphere. + * + * @param center the center. + * @param offset the offset. + * @param radius the radius. + * @return the bounding sphere. + */ + public static Bounding newBoundingSphere(Vector3f center, Vector3f offset, float radius) { + return new BoundingSphere(center, offset, radius); + } - private BoundingFactory() { - throw new IllegalArgumentException(); - } + private BoundingFactory() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingType.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingType.java index 6de419d2..021fae9a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingType.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/BoundingType.java @@ -6,16 +6,16 @@ * @author JavaSaBr */ public enum BoundingType { - /** - * Axis aligned box bounding type. - */ - AXIS_ALIGNED_BOX, - /** - * Sphere bounding type. - */ - SPHERE, - /** - * Empty bounding type. - */ - EMPTY, + /** + * Axis aligned box bounding type. + */ + AXIS_ALIGNED_BOX, + /** + * Sphere bounding type. + */ + SPHERE, + /** + * Empty bounding type. + */ + EMPTY, } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AbstractBounding.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AbstractBounding.java index d8079b99..e64fd3d0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AbstractBounding.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AbstractBounding.java @@ -8,103 +8,103 @@ import javasabr.rlib.common.geom.bounding.BoundingType; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The base implementation of a bounding. * * @author JavaSaBr */ +@NullMarked public abstract class AbstractBounding implements Bounding { - protected static final Logger LOGGER = LoggerManager.getLogger(Bounding.class); - - /** - * The center. - */ - protected Vector3f center; - - /** - * The offset. - */ - protected Vector3f offset; - - protected AbstractBounding(@NotNull Vector3f center, @NotNull Vector3f offset) { - this.center = center; - this.offset = offset; - } - - @Override - public boolean contains(float x, float y, float z) { - return false; - } - - @Override - public boolean contains(@NotNull Vector3f point) { - return contains(point.getX(), point.getY(), point.getZ()); - } - - @Override - public final float distanceTo(@NotNull Vector3f point) { - return center.distance(point); - } - - @Override - public @NotNull BoundingType getBoundingType() { - return BoundingType.EMPTY; - } - - @Override - public final@NotNull Vector3f getCenter() { - return center; - } - - @Override - public void setCenter(@NotNull Vector3f center) { - this.center = center; - } - - @Override - public @NotNull Vector3f getOffset() { - return offset; - } - - @Override - public @NotNull Vector3f getResultCenter(@NotNull Vector3fBuffer buffer) { - return getCenter(); - } - - @Override - public float getResultCenterX() { - return getCenter().getX(); - } - - @Override - public float getResultCenterY() { - return getCenter().getY(); - } - - @Override - public float getResultCenterZ() { - return getCenter().getZ(); - } - - @Override - public boolean intersects(@NotNull Bounding bounding, @NotNull Vector3fBuffer buffer) { - return false; - } - - @Override - public final boolean intersects(@NotNull Ray3f ray, @NotNull Vector3fBuffer buffer) { - return intersects(ray.getStart(), ray.getDirection(), buffer); - } - - @Override - public boolean intersects(@NotNull Vector3f start, @NotNull Vector3f direction, @NotNull Vector3fBuffer buffer) { - return false; - } - - @Override - public void update(@NotNull Quaternion4f rotation, @NotNull Vector3fBuffer buffer) { - } + protected static final Logger LOGGER = LoggerManager.getLogger(Bounding.class); + + /** + * The center. + */ + protected Vector3f center; + + /** + * The offset. + */ + protected Vector3f offset; + + protected AbstractBounding(Vector3f center, Vector3f offset) { + this.center = center; + this.offset = offset; + } + + @Override + public boolean contains(float x, float y, float z) { + return false; + } + + @Override + public boolean contains(Vector3f point) { + return contains(point.getX(), point.getY(), point.getZ()); + } + + @Override + public final float distanceTo(Vector3f point) { + return center.distance(point); + } + + @Override + public BoundingType getBoundingType() { + return BoundingType.EMPTY; + } + + @Override + public final Vector3f getCenter() { + return center; + } + + @Override + public void setCenter(Vector3f center) { + this.center = center; + } + + @Override + public Vector3f getOffset() { + return offset; + } + + @Override + public Vector3f getResultCenter(Vector3fBuffer buffer) { + return getCenter(); + } + + @Override + public float getResultCenterX() { + return getCenter().getX(); + } + + @Override + public float getResultCenterY() { + return getCenter().getY(); + } + + @Override + public float getResultCenterZ() { + return getCenter().getZ(); + } + + @Override + public boolean intersects(Bounding bounding, Vector3fBuffer buffer) { + return false; + } + + @Override + public final boolean intersects(Ray3f ray, Vector3fBuffer buffer) { + return intersects(ray.getStart(), ray.getDirection(), buffer); + } + + @Override + public boolean intersects(Vector3f start, Vector3f direction, Vector3fBuffer buffer) { + return false; + } + + @Override + public void update(Quaternion4f rotation, Vector3fBuffer buffer) {} } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AxisAlignedBoundingBox.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AxisAlignedBoundingBox.java index 00606c40..73441844 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AxisAlignedBoundingBox.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/AxisAlignedBoundingBox.java @@ -6,284 +6,273 @@ import javasabr.rlib.common.geom.Vector3fBuffer; import javasabr.rlib.common.geom.bounding.Bounding; import javasabr.rlib.common.geom.bounding.BoundingType; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation AxisAlignedBoundingBox. * * @author JavaSaBr */ +@NullMarked public class AxisAlignedBoundingBox extends AbstractBounding { - /** - * The matrix. - */ - @NotNull - private final Matrix3f matrix; - - /** - * The vector size. - */ - @NotNull - private final Vector3f size; - - /** - * The size X. - */ - protected float sizeX; - - /** - * The size Y. - */ - protected float sizeY; - - /** - * The size Z. - */ - protected float sizeZ; - - /** - * The offset X. - */ - protected float offsetX; - - /** - * The offset Y. - */ - protected float offsetY; - - /** - * The offset Z. - */ - protected float offsetZ; - - public AxisAlignedBoundingBox( - @NotNull Vector3f center, - @NotNull Vector3f offset, - float sizeX, - float sizeY, - float sizeZ - ) { - super(center, offset); - - this.matrix = new Matrix3f(); - this.size = new Vector3f(sizeX, sizeY, sizeZ); - this.sizeX = sizeX; - this.sizeY = sizeY; - this.sizeZ = sizeZ; - this.offsetX = offset.getX(); - this.offsetY = offset.getY(); - this.offsetZ = offset.getZ(); + /** + * The matrix. + */ + private final Matrix3f matrix; + + /** + * The vector size. + */ + private final Vector3f size; + + /** + * The size X. + */ + protected float sizeX; + + /** + * The size Y. + */ + protected float sizeY; + + /** + * The size Z. + */ + protected float sizeZ; + + /** + * The offset X. + */ + protected float offsetX; + + /** + * The offset Y. + */ + protected float offsetY; + + /** + * The offset Z. + */ + protected float offsetZ; + + public AxisAlignedBoundingBox(Vector3f center, Vector3f offset, float sizeX, float sizeY, float sizeZ) { + super(center, offset); + this.matrix = new Matrix3f(); + this.size = new Vector3f(sizeX, sizeY, sizeZ); + this.sizeX = sizeX; + this.sizeY = sizeY; + this.sizeZ = sizeZ; + this.offsetX = offset.getX(); + this.offsetY = offset.getY(); + this.offsetZ = offset.getZ(); + } + + @Override + public boolean contains(float x, float y, float z) { + return Math.abs(getResultCenterX() - x) < sizeX && Math.abs(getResultCenterY() - y) < sizeY + && Math.abs(getResultCenterZ() - z) < sizeZ; + } + + @Override + public BoundingType getBoundingType() { + return BoundingType.AXIS_ALIGNED_BOX; + } + + @Override + public Vector3f getResultCenter(Vector3fBuffer buffer) { + + Vector3f vector = buffer + .nextVector() + .set(center); + + if (offset.isZero()) { + return vector; } - @Override - public boolean contains(float x, float y, float z) { - return Math.abs(getResultCenterX() - x) < sizeX && - Math.abs(getResultCenterY() - y) < sizeY && - Math.abs(getResultCenterZ() - z) < sizeZ; - } - - @Override - public @NotNull BoundingType getBoundingType() { - return BoundingType.AXIS_ALIGNED_BOX; - } + return vector.addLocal(offsetX, offsetY, offsetZ); + } + + @Override + public float getResultCenterZ() { + return center.getZ() + offsetZ; + } + + @Override + public float getResultCenterY() { + return center.getY() + offsetY; + } + + @Override + public float getResultCenterX() { + return center.getX() + offsetX; + } + + /** + * Get the size by X coordinates. + * + * @return the size. + */ + protected final float getSizeX() { + return sizeX; + } + + /** + * Get the size by Y coordinates. + * + * @return the size. + */ + protected final float getSizeY() { + return sizeY; + } + + /** + * Get the size by Z coordinates. + * + * @return the size. + */ + protected final float getSizeZ() { + return sizeZ; + } + + /** + * Get a copy of the AABB's size vector. + * + * @return AABB's size. + */ + public Vector3f getSize() { + return new Vector3f(size); + } + + /** + * Get AABB's size. + * + * @param buffer the vector buffer. + * @return AABB's size. + */ + public Vector3f getSize(Vector3fBuffer buffer) { + return buffer + .nextVector() + .set(size); + } + + @Override + public boolean intersects(Bounding bounding, Vector3fBuffer buffer) { + switch (bounding.getBoundingType()) { + case EMPTY: { + return false; + } + case AXIS_ALIGNED_BOX: { - @Override - public @NotNull Vector3f getResultCenter(@NotNull Vector3fBuffer buffer) { + AxisAlignedBoundingBox box = (AxisAlignedBoundingBox) bounding; - Vector3f vector = buffer.nextVector() - .set(center); + Vector3f target = box.getResultCenter(buffer); + Vector3f center = getResultCenter(buffer); - if (offset.isZero()) { - return vector; + float sizeX = getSizeX(); + float sizeY = getSizeY(); + float sizeZ = getSizeZ(); + + if (center.getX() + sizeX < target.getX() - box.getSizeX() + || center.getX() - sizeX > target.getX() + box.getSizeX()) { + return false; + } else if (center.getY() + sizeY < target.getY() - box.getSizeY() + || center.getY() - sizeY > target.getY() + box.getSizeY()) { + return false; + } else if (center.getZ() + sizeZ < target.getZ() - box.getSizeZ() + || center.getZ() - sizeZ > target.getZ() + box.getSizeZ()) { + return false; } - return vector.addLocal(offsetX, offsetY, offsetZ); - } - - @Override - public float getResultCenterZ() { - return center.getZ() + offsetZ; - } - - @Override - public float getResultCenterY() { - return center.getY() + offsetY; - } + return true; + } + case SPHERE: { - @Override - public float getResultCenterX() { - return center.getX() + offsetX; - } + BoundingSphere sphere = (BoundingSphere) bounding; - /** - * Get the size by X coordinates. - * - * @return the size. - */ - protected final float getSizeX() { - return sizeX; - } - - /** - * Get the size by Y coordinates. - * - * @return the size. - */ - protected final float getSizeY() { - return sizeY; - } + Vector3f target = sphere.getResultCenter(buffer); + Vector3f center = getResultCenter(buffer); - /** - * Get the size by Z coordinates. - * - * @return the size. - */ - protected final float getSizeZ() { - return sizeZ; - } - - /** - * Get a copy of the AABB's size vector. - * - * @return AABB's size. - */ - public @NotNull Vector3f getSize() { - return new Vector3f(size); - } + float radius = sphere.getRadius(); - /** - * Get AABB's size. - * - * @param buffer the vector buffer. - * @return AABB's size. - */ - public Vector3f getSize(@NotNull Vector3fBuffer buffer) { - return buffer.nextVector() - .set(size); - } - - @Override - public boolean intersects(@NotNull Bounding bounding, @NotNull Vector3fBuffer buffer) { - switch (bounding.getBoundingType()) { - case EMPTY: { - return false; - } - case AXIS_ALIGNED_BOX: { - - AxisAlignedBoundingBox box = (AxisAlignedBoundingBox) bounding; - - Vector3f target = box.getResultCenter(buffer); - Vector3f center = getResultCenter(buffer); - - float sizeX = getSizeX(); - float sizeY = getSizeY(); - float sizeZ = getSizeZ(); - - if (center.getX() + sizeX < target.getX() - box.getSizeX() || - center.getX() - sizeX > target.getX() + box.getSizeX()) { - return false; - } else if (center.getY() + sizeY < target.getY() - box.getSizeY() || - center.getY() - sizeY > target.getY() + box.getSizeY()) { - return false; - } else if (center.getZ() + sizeZ < target.getZ() - box.getSizeZ() || - center.getZ() - sizeZ > target.getZ() + box.getSizeZ()) { - return false; - } - - return true; - } - case SPHERE: { - - BoundingSphere sphere = (BoundingSphere) bounding; - - Vector3f target = sphere.getResultCenter(buffer); - Vector3f center = getResultCenter(buffer); - - float radius = sphere.getRadius(); - - if (Math.abs(center.getX() - target.getX()) > radius + getSizeX()) { - return false; - } else if (Math.abs(center.getY() - target.getY()) > radius + getSizeY()) { - return false; - } else { - return !(Math.abs(center.getZ() - target.getZ()) > radius + getSizeZ()); - } - - } - default: { - LOGGER.warning(new IllegalArgumentException("incorrect bounding type " + bounding.getBoundingType())); - } + if (Math.abs(center.getX() - target.getX()) > radius + getSizeX()) { + return false; + } else if (Math.abs(center.getY() - target.getY()) > radius + getSizeY()) { + return false; + } else { + return !(Math.abs(center.getZ() - target.getZ()) > radius + getSizeZ()); } - return false; + } + default: { + LOGGER.warning(new IllegalArgumentException("incorrect bounding type " + bounding.getBoundingType())); + } } - @Override - public boolean intersects( - @NotNull Vector3f start, - @NotNull Vector3f direction, - @NotNull Vector3fBuffer buffer - ) { + return false; + } - float divX = 1.0F / (Float.compare(direction.getX(), 0) == 0 ? 0.00001F : direction.getX()); - float divY = 1.0F / (Float.compare(direction.getY(), 0) == 0 ? 0.00001F : direction.getY()); - float divZ = 1.0F / (Float.compare(direction.getZ(), 0) == 0 ? 0.00001F : direction.getZ()); + @Override + public boolean intersects(Vector3f start, Vector3f direction, Vector3fBuffer buffer) { - float sizeX = getSizeX() * 0.5F; - float sizeY = getSizeY() * 0.5F; - float sizeZ = getSizeZ() * 0.5F; + float divX = 1.0F / (Float.compare(direction.getX(), 0) == 0 ? 0.00001F : direction.getX()); + float divY = 1.0F / (Float.compare(direction.getY(), 0) == 0 ? 0.00001F : direction.getY()); + float divZ = 1.0F / (Float.compare(direction.getZ(), 0) == 0 ? 0.00001F : direction.getZ()); - Vector3f center = getResultCenter(buffer); + float sizeX = getSizeX() * 0.5F; + float sizeY = getSizeY() * 0.5F; + float sizeZ = getSizeZ() * 0.5F; - float minX = center.getX() - sizeX; - float minY = center.getY() - sizeY; - float minZ = center.getZ() - sizeZ; + Vector3f center = getResultCenter(buffer); - float maxX = center.getX() + sizeX; - float maxY = center.getY() + sizeY; - float maxZ = center.getZ() + sizeZ; + float minX = center.getX() - sizeX; + float minY = center.getY() - sizeY; + float minZ = center.getZ() - sizeZ; - float t1 = (minX - start.getX()) * divX; - float t2 = (maxX - start.getX()) * divX; - float t3 = (minY - start.getY()) * divY; - float t4 = (maxY - start.getY()) * divY; - float t5 = (minZ - start.getZ()) * divZ; - float t6 = (maxZ - start.getZ()) * divZ; + float maxX = center.getX() + sizeX; + float maxY = center.getY() + sizeY; + float maxZ = center.getZ() + sizeZ; - float tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6)); - float tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); + float t1 = (minX - start.getX()) * divX; + float t2 = (maxX - start.getX()) * divX; + float t3 = (minY - start.getY()) * divY; + float t4 = (maxY - start.getY()) * divY; + float t5 = (minZ - start.getZ()) * divZ; + float t6 = (maxZ - start.getZ()) * divZ; - return tmin <= tmax && tmax > 0.f; - } - - @Override - public void update(@NotNull Quaternion4f rotation, @NotNull Vector3fBuffer buffer) { + float tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6)); + float tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); - matrix.set(rotation); - matrix.absoluteLocal(); + return tmin <= tmax && tmax > 0.f; + } - Vector3f vector = matrix.mult(size, buffer.nextVector()); + @Override + public void update(Quaternion4f rotation, Vector3fBuffer buffer) { - sizeX = Math.abs(vector.getX()); - sizeY = Math.abs(vector.getY()); - sizeZ = Math.abs(vector.getZ()); + matrix.set(rotation); + matrix.absoluteLocal(); - if (offset.isZero()) { - return; - } + Vector3f vector = matrix.mult(size, buffer.nextVector()); - matrix.mult(offset, vector); + sizeX = Math.abs(vector.getX()); + sizeY = Math.abs(vector.getY()); + sizeZ = Math.abs(vector.getZ()); - offsetX = vector.getX(); - offsetY = vector.getY(); - offsetZ = vector.getZ(); + if (offset.isZero()) { + return; } - @Override - public String toString() { - return getClass().getSimpleName() + " size = " + size + ", sizeX = " + sizeX + - ", sizeY = " + sizeY + ", sizeZ = " + sizeZ + ", center = " + center + ", offset = " + offset; - } + matrix.mult(offset, vector); + + offsetX = vector.getX(); + offsetY = vector.getY(); + offsetZ = vector.getZ(); + } + + @Override + public String toString() { + return getClass().getSimpleName() + " size = " + size + ", sizeX = " + sizeX + ", sizeY = " + sizeY + ", sizeZ = " + + sizeZ + ", center = " + center + ", offset = " + offset; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/BoundingSphere.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/BoundingSphere.java index 756c3a55..8807bf6e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/BoundingSphere.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/bounding/impl/BoundingSphere.java @@ -7,138 +7,140 @@ import javasabr.rlib.common.geom.bounding.Bounding; import javasabr.rlib.common.geom.bounding.BoundingType; import javasabr.rlib.common.geom.util.GeometryUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of sphere bounding. * * @author JavaSaBr */ +@NullMarked public class BoundingSphere extends AbstractBounding { - /** - * The sphere radius. - */ - protected float radius; - - /** - * The square radius. - */ - protected float squareRadius; - - public BoundingSphere(@NotNull Vector3f center, @NotNull Vector3f offset, float radius) { - super(center, offset); - - this.radius = radius; - this.squareRadius = radius * radius; - } - - @Override - public boolean contains(float x, float y, float z) { - - float startX = getResultCenterX(); - float centerY = getResultCenterY(); - float centerZ = getResultCenterZ(); - - return GeometryUtils.getSquareDistance(startX, centerY, centerZ, x, y, z) < squareRadius; + /** + * The sphere radius. + */ + protected float radius; + + /** + * The square radius. + */ + protected float squareRadius; + + public BoundingSphere(Vector3f center, Vector3f offset, float radius) { + super(center, offset); + + this.radius = radius; + this.squareRadius = radius * radius; + } + + @Override + public boolean contains(float x, float y, float z) { + + float startX = getResultCenterX(); + float centerY = getResultCenterY(); + float centerZ = getResultCenterZ(); + + return GeometryUtils.getSquareDistance(startX, centerY, centerZ, x, y, z) < squareRadius; + } + + @Override + public float getResultCenterZ() { + return center.getZ() + offset.getZ(); + } + + @Override + public float getResultCenterY() { + return center.getY() + offset.getY(); + } + + @Override + public float getResultCenterX() { + return center.getX() + offset.getX(); + } + + @Override + public BoundingType getBoundingType() { + return BoundingType.SPHERE; + } + + /** + * Get the sphere's radius. + * + * @return the sphere's radius. + */ + public float getRadius() { + return radius; + } + + @Override + public Vector3f getResultCenter(Vector3fBuffer buffer) { + + Vector3f vector = buffer + .nextVector() + .set(center); + + if (offset.isZero()) { + return vector; } - @Override - public float getResultCenterZ() { - return center.getZ() + offset.getZ(); - } + return vector.addLocal(offset); + } - @Override - public float getResultCenterY() { - return center.getY() + offset.getY(); - } + @Override + public boolean intersects(Bounding bounding, Vector3fBuffer buffer) { + switch (bounding.getBoundingType()) { + case EMPTY: { + return false; + } + case SPHERE: { - @Override - public float getResultCenterX() { - return center.getX() + offset.getX(); - } + BoundingSphere sphere = (BoundingSphere) bounding; - @Override - public @NotNull BoundingType getBoundingType() { - return BoundingType.SPHERE; - } + Vector3f diff = getResultCenter(buffer).subtractLocal(sphere.getResultCenter(buffer)); - /** - * Get the sphere's radius. - * - * @return the sphere's radius. - */ - public float getRadius() { - return radius; - } + float rsum = getRadius() + sphere.getRadius(); - @Override - public @NotNull Vector3f getResultCenter(@NotNull Vector3fBuffer buffer) { + return diff.dot(diff) <= rsum * rsum; + } + case AXIS_ALIGNED_BOX: { - Vector3f vector = buffer.nextVector() - .set(center); + AxisAlignedBoundingBox box = (AxisAlignedBoundingBox) bounding; - if (offset.isZero()) { - return vector; - } + Vector3f center = getResultCenter(buffer); + Vector3f target = box.getResultCenter(buffer); - return vector.addLocal(offset); + return abs(target.getX() - center.getX()) < getRadius() + box.getSizeX() + && abs(target.getY() - center.getY()) < getRadius() + box.getSizeY() + && abs(target.getZ() - center.getZ()) < getRadius() + box.getSizeZ(); + } } - @Override - public boolean intersects(@NotNull Bounding bounding, @NotNull Vector3fBuffer buffer) { - switch (bounding.getBoundingType()) { - case EMPTY: { - return false; - } - case SPHERE: { - - BoundingSphere sphere = (BoundingSphere) bounding; - - Vector3f diff = getResultCenter(buffer) - .subtractLocal(sphere.getResultCenter(buffer)); + return false; + } - float rsum = getRadius() + sphere.getRadius(); + @Override + public boolean intersects(Vector3f start, Vector3f direction, Vector3fBuffer buffer) { - return diff.dot(diff) <= rsum * rsum; - } - case AXIS_ALIGNED_BOX: { + Vector3f diff = buffer + .nextVector() + .set(start) + .subtractLocal(getResultCenter(buffer)); - AxisAlignedBoundingBox box = (AxisAlignedBoundingBox) bounding; + float a = start.dot(diff) - squareRadius; - Vector3f center = getResultCenter(buffer); - Vector3f target = box.getResultCenter(buffer); - - return abs(target.getX() - center.getX()) < getRadius() + box.getSizeX() && - abs(target.getY() - center.getY()) < getRadius() + box.getSizeY() && - abs(target.getZ() - center.getZ()) < getRadius() + box.getSizeZ(); - } - } - - return false; + if (a <= 0.0) { + return true; } - @Override - public boolean intersects(@NotNull Vector3f start, @NotNull Vector3f direction, @NotNull Vector3fBuffer buffer) { + float b = direction.dot(diff); - Vector3f diff = buffer.nextVector() - .set(start) - .subtractLocal(getResultCenter(buffer)); + return b < 0.0 && b * b >= a; - float a = start.dot(diff) - squareRadius; + } - if (a <= 0.0) { - return true; - } - - float b = direction.dot(diff); - - return b < 0.0 && b * b >= a; - - } - - @Override - public String toString() { - return getClass().getSimpleName() + " [radius=" + radius + ", squareRadius=" + squareRadius + "]"; - } + @Override + public String toString() { + return getClass().getSimpleName() + " [radius=" + radius + ", squareRadius=" + squareRadius + "]"; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/util/AngleUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/util/AngleUtils.java index ffb31c63..7f97c85b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/util/AngleUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/util/AngleUtils.java @@ -1,159 +1,176 @@ package javasabr.rlib.common.geom.util; +import org.jspecify.annotations.NullMarked; + /** * Реализация утильного класса с методами по работе с углами. * * @author JavaSaBr */ +@NullMarked public final class AngleUtils { - /** - * The constant HEADINGS_IN_PI. - */ - public static final float HEADINGS_IN_PI = 10430.378350470452724949566316381F; - /** - * The constant PI. - */ - public static final float PI = 3.14159265358979323846F; - - /** - * Расчет разворота в указанные координаты. - * - * @param x начальная координата. - * @param y начальная координата. - * @param targetX целевая координата. - * @param targetY целевая координата. - * @return нужный разворот. - */ - public static int calcHeading(final float x, final float y, final float targetX, final float targetY) { - return (int) (Math.atan2(y - targetY, x - targetX) * HEADINGS_IN_PI) + 32768; + /** + * The constant HEADINGS_IN_PI. + */ + public static final float HEADINGS_IN_PI = 10430.378350470452724949566316381F; + /** + * The constant PI. + */ + public static final float PI = 3.14159265358979323846F; + + /** + * Расчет разворота в указанные координаты. + * + * @param x начальная координата. + * @param y начальная координата. + * @param targetX целевая координата. + * @param targetY целевая координата. + * @return нужный разворот. + */ + public static int calcHeading(float x, float y, float targetX, float targetY) { + return (int) (Math.atan2(y - targetY, x - targetX) * HEADINGS_IN_PI) + 32768; + } + + /** + * Расчет относительного положения. + * + * @param x начальная координата. + * @param y начальная координата. + * @param heading разворот. + * @param targetX целевая координата. + * @param targetY целевая координата. + * @return нужный разворот. + */ + public static int calcHeadingTo(float x, float y, int heading, float targetX, float targetY) { + + int newHeading = calcHeading(x, y, targetX, targetY); + + newHeading = heading - newHeading; + + if (newHeading < 0) { + newHeading = newHeading + 1 + Integer.MAX_VALUE & 0xFFFF; + } else if (newHeading > 0xFFFF) { + newHeading &= 0xFFFF; } - /** - * Расчет относительного положения. - * - * @param x начальная координата. - * @param y начальная координата. - * @param heading разворот. - * @param targetX целевая координата. - * @param targetY целевая координата. - * @return нужный разворот. - */ - public static int calcHeadingTo(final float x, final float y, final int heading, - final float targetX, final float targetY) { - - int newHeading = calcHeading(x, y, targetX, targetY); - - newHeading = heading - newHeading; - - if (newHeading < 0) { - newHeading = newHeading + 1 + Integer.MAX_VALUE & 0xFFFF; - } else if (newHeading > 0xFFFF) { - newHeading &= 0xFFFF; - } - - return newHeading; + return newHeading; + } + + /** + * Конвектирует градус в heading. + * + * @param degree кол-во градусов. + * @return heading направление разворота. + */ + public static int degreeToHeading(float degree) { + if (degree < 0) { + degree += 360f; } - - /** - * Конвектирует градус в heading. - * - * @param degree кол-во градусов. - * @return heading направление разворота. - */ - public static int degreeToHeading(float degree) { - if (degree < 0) degree += 360f; - return (int) (degree * 182.044444444f); + return (int) (degree * 182.044444444f); + } + + /** + * Конвектирование градусы в радианы. + * + * @param angle кол-во градусов. + * @return кол -во радианов. + */ + public static float degreeToRadians(float angle) { + return angle * PI / 180F; + } + + /** + * Получаем относительный градус между 2 точками. + * + * @param startX х координата первой точки. + * @param startY у координата второй точки. + * @param endX х координата второй точки. + * @param endY у координата второй точки. + * @return кол -во градусов. + */ + public static float getAngleFrom(float startX, float startY, float endX, float endY) { + float angle = (float) Math.toDegrees(Math.atan2(startY - endY, startX - endX)); + if (angle <= 0F) { + angle += 360F; } - - /** - * Конвектирование градусы в радианы. - * - * @param angle кол-во градусов. - * @return кол -во радианов. - */ - public static float degreeToRadians(final float angle) { - return angle * PI / 180F; + return angle; + } + + /** + * Конвектирование heading в градусы. + * + * @param heading направление разворота. + * @return кол -во градусов. + */ + public static float headingToDegree(int heading) { + float angle = heading / 182.044444444f; + if (angle == 0) { + angle = 360f; } - - /** - * Получаем относительный градус между 2 точками. - * - * @param startX х координата первой точки. - * @param startY у координата второй точки. - * @param endX х координата второй точки. - * @param endY у координата второй точки. - * @return кол -во градусов. - */ - public static float getAngleFrom(final float startX, final float startY, final float endX, final float endY) { - float angle = (float) Math.toDegrees(Math.atan2(startY - endY, startX - endX)); - if (angle <= 0F) angle += 360F; - return angle; + return angle; + } + + /** + * Конвектирование heading в радианы. + * + * @param heading направление разворота. + * @return кол -во радианов. + */ + public static float headingToRadians(int heading) { + float angle = heading / 182.044444444f; + if (angle == 0) { + angle = 360f; } - - /** - * Конвектирование heading в градусы. - * - * @param heading направление разворота. - * @return кол -во градусов. - */ - public static float headingToDegree(final int heading) { - float angle = heading / 182.044444444f; - if (angle == 0) angle = 360f; - return angle; + return angle * 3.141592653f / 180f; + } + + /** + * Рассчет вхождения в относительную область перед точкой точки. + * + * @param x координата первой точки. + * @param y координата первой точки. + * @param heading направление области. + * @param targetX координата второй точки. + * @param targetY координата второй точки. + * @param width ширина области. + * @return входит ли. + */ + public static boolean isInDegree(float x, float y, int heading, float targetX, float targetY, int width) { + + int angle = (int) AngleUtils.headingToDegree(calcHeadingTo(x, y, heading, targetX, targetY)); + final int degree = (int) headingToDegree(heading); + + int min = degree - width; + int max = degree + width; + + if (min < 0) { + min += 360; } - - /** - * Конвектирование heading в радианы. - * - * @param heading направление разворота. - * @return кол -во радианов. - */ - public static float headingToRadians(final int heading) { - float angle = heading / 182.044444444f; - if (angle == 0) angle = 360f; - return angle * 3.141592653f / 180f; + if (max < 0) { + max += 360; } - /** - * Рассчет вхождения в относительную область перед точкой точки. - * - * @param x координата первой точки. - * @param y координата первой точки. - * @param heading направление области. - * @param targetX координата второй точки. - * @param targetY координата второй точки. - * @param width ширина области. - * @return входит ли. - */ - public static boolean isInDegree(final float x, final float y, final int heading, - final float targetX, final float targetY, final int width) { - - int angle = (int) AngleUtils.headingToDegree(calcHeadingTo(x, y, heading, targetX, targetY)); - final int degree = (int) headingToDegree(heading); - - int min = degree - width; - int max = degree + width; - - if (min < 0) min += 360; - if (max < 0) max += 360; - - final boolean flag = angle - degree > 180; - if (flag) angle -= 360; - if (angle > max) return false; + final boolean flag = angle - degree > 180; + if (flag) { + angle -= 360; + } + if (angle > max) { + return false; + } - angle += 360; + angle += 360; - return angle > min; - } + return angle > min; + } - /** - * Конвектироввание радианов в градусы. - * - * @param radians угол в радианах. - * @return угол в градусах. - */ - public static float radiansToDegree(final float radians) { - return radians * 180F / PI; - } + /** + * Конвектироввание радианов в градусы. + * + * @param radians угол в радианах. + * @return угол в градусах. + */ + public static float radiansToDegree(float radians) { + return radians * 180F / PI; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/util/CoordsUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/util/CoordsUtils.java index a515d91c..c2370431 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/util/CoordsUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/util/CoordsUtils.java @@ -5,258 +5,268 @@ import javasabr.rlib.common.util.ExtMath; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * Реализация утильного класса с методами для рассчета координат. * * @author JavaSaBr */ +@NullMarked public final class CoordsUtils { - private static final Logger LOGGER = LoggerManager.getLogger(CoordsUtils.class); + private static final Logger LOGGER = LoggerManager.getLogger(CoordsUtils.class); - /** - * Генерация дуговых позиций. - * - * @param x целевая координата. - * @param y целевая координата. - * @param z целевая координата. - * @param heading разворот. - * @param radius радиус формирования. - * @param count кол-во необходимых позиций. - * @param degree положение на окружности центра дуги. - * @param width ширина дуги. - * @return массив позиций. - */ - @NotNull - public static Vector3f[] arcCoords(final float x, final float y, final float z, final int heading, - final int radius, final int count, final int degree, final int width) { + /** + * Генерация дуговых позиций. + * + * @param x целевая координата. + * @param y целевая координата. + * @param z целевая координата. + * @param heading разворот. + * @param radius радиус формирования. + * @param count кол-во необходимых позиций. + * @param degree положение на окружности центра дуги. + * @param width ширина дуги. + * @return массив позиций. + */ + public static Vector3f[] arcCoords( + float x, + float y, + float z, + int heading, + int radius, + int count, + int degree, + int width) { - final Vector3f[] vectors = new Vector3f[count]; + Vector3f[] vectors = new Vector3f[count]; + float current = AngleUtils.headingToDegree(heading) - degree; - final float current = AngleUtils.headingToDegree(heading) - degree; + float min = current - width; + float max = current + width; - final float min = current - width; - final float max = current + width; + float angle = Math.abs(min - max) / count; - final float angle = Math.abs(min - max) / count; + for (int i = 0; i < count; i++) { - for (int i = 0; i < count; i++) { + Vector3f vector = new Vector3f(); - final Vector3f vector = new Vector3f(); + float radians = AngleUtils.degreeToRadians(min + angle * i); - final float radians = AngleUtils.degreeToRadians(min + angle * i); + float newX = calcX(x, radius, radians); + float newY = calcY(y, radius, radians); - final float newX = calcX(x, radius, radians); - final float newY = calcY(y, radius, radians); + vector.set(newX, newY, z); - vector.set(newX, newY, z); - - vectors[i] = vector; - } - - return vectors; - } - - /** - * Рассчет х координаты с учетом дистанции и разворота. - * - * @param x стартовая х координата. - * @param distance дистанция сдвига. - * @param radians направление сдвига. - * @return новая х координата. - */ - public static float calcX(final float x, final int distance, final float radians) { - return x + distance * (float) Math.cos(radians); - } - - /** - * Рассчет х координаты с учетом дистанции и разворота. - * - * @param x стартовая х координата. - * @param distance дистанция сдвига. - * @param heading направление сдвига. - * @return новая х координата. - */ - public static float calcX(final float x, final int distance, final int heading) { - return x + distance * (float) Math.cos(AngleUtils.headingToRadians(heading)); - } - - /** - * Рассчет х координаты с учетом дистанции и разворота. - * - * @param x стартовая х координата. - * @param distance дистанция сдвига. - * @param heading направление сдвига. - * @param offset смещение по градусам. - * @return новая х координата. - */ - public static float calcX(final float x, final int distance, final int heading, final int offset) { - return x + distance * (float) Math.cos(AngleUtils.headingToRadians(heading + offset)); - } - - /** - * Рассчет у координаты с учетом дистанции и разворота. - * - * @param y стартовая у координата. - * @param distance дистанция сдвига. - * @param radians направление сдвига. - * @return новая у координата. - */ - public static float calcY(final float y, final int distance, final float radians) { - return y + distance * (float) Math.sin(radians); + vectors[i] = vector; } - /** - * Рассчет у координаты с учетом дистанции и разворота. - * - * @param y стартовая у координата. - * @param distance дистанция сдвига. - * @param heading направление сдвига. - * @return новая у координата. - */ - public static float calcY(final float y, final int distance, final int heading) { - return y + distance * (float) Math.sin(AngleUtils.headingToRadians(heading)); + return vectors; + } + + /** + * Рассчет х координаты с учетом дистанции и разворота. + * + * @param x стартовая х координата. + * @param distance дистанция сдвига. + * @param radians направление сдвига. + * @return новая х координата. + */ + public static float calcX(float x, int distance, float radians) { + return x + distance * (float) Math.cos(radians); + } + + /** + * Рассчет х координаты с учетом дистанции и разворота. + * + * @param x стартовая х координата. + * @param distance дистанция сдвига. + * @param heading направление сдвига. + * @return новая х координата. + */ + public static float calcX(float x, int distance, int heading) { + return x + distance * (float) Math.cos(AngleUtils.headingToRadians(heading)); + } + + /** + * Рассчет х координаты с учетом дистанции и разворота. + * + * @param x стартовая х координата. + * @param distance дистанция сдвига. + * @param heading направление сдвига. + * @param offset смещение по градусам. + * @return новая х координата. + */ + public static float calcX(float x, int distance, int heading, int offset) { + return x + distance * (float) Math.cos(AngleUtils.headingToRadians(heading + offset)); + } + + /** + * Рассчет у координаты с учетом дистанции и разворота. + * + * @param y стартовая у координата. + * @param distance дистанция сдвига. + * @param radians направление сдвига. + * @return новая у координата. + */ + public static float calcY(float y, int distance, float radians) { + return y + distance * (float) Math.sin(radians); + } + + /** + * Рассчет у координаты с учетом дистанции и разворота. + * + * @param y стартовая у координата. + * @param distance дистанция сдвига. + * @param heading направление сдвига. + * @return новая у координата. + */ + public static float calcY(float y, int distance, int heading) { + return y + distance * (float) Math.sin(AngleUtils.headingToRadians(heading)); + } + + /** + * Рассчет у координаты с учетом дистанции и разворота. + * + * @param y стартовая у координата. + * @param distance дистанция сдвига. + * @param heading направление сдвига. + * @param offset смещение по градусам. + * @return новая у координата. + */ + public static float calcY(float y, int distance, int heading, int offset) { + return y + distance * (float) Math.sin(AngleUtils.headingToRadians(heading + offset)); + } + + /** + * Генерация массива круговых позиций с одинаковым интервлаом. + * + * @param x центральная координата. + * @param y центральная координата. + * @param z центральная координата. + * @param radius радиус разброса. + * @param count кол-во позиций. + * @return массив позиций. + */ + @SuppressWarnings("unchecked") + public static Vector3f[] circularCoords(float x, float y, float z, int radius, int count) { + + Vector3f[] locs = new Vector3f[count]; + float angle = 360F / count; + + for (int i = 1; i <= count; i++) { + + Vector3f loc = new Vector3f(); + float radians = AngleUtils.degreeToRadians(i * angle); + + float newX = calcX(x, radius, radians); + float newY = calcY(y, radius, radians); + + loc.set(newX, newY, z); + + locs[i - 1] = loc; } - /** - * Рассчет у координаты с учетом дистанции и разворота. - * - * @param y стартовая у координата. - * @param distance дистанция сдвига. - * @param heading направление сдвига. - * @param offset смещение по градусам. - * @return новая у координата. - */ - public static float calcY(final float y, final int distance, final int heading, final int offset) { - return y + distance * (float) Math.sin(AngleUtils.headingToRadians(heading + offset)); + return locs; + } + + /** + * Получение точек по кругу от указанной точки. + * + * @param source массив исходных точек. + * @param x координата центра. + * @param y координата центра. + * @param z координата центра. + * @param count кол-во точек. + * @param radius радиус от центра. + * @return массив точек. + */ + public static Vector3f[] getCircularPoints( + Vector3f[] source, + float x, + float y, + float z, + int count, + int radius) { + + if (count < 1) { + return source; } - /** - * Генерация массива круговых позиций с одинаковым интервлаом. - * - * @param x центральная координата. - * @param y центральная координата. - * @param z центральная координата. - * @param radius радиус разброса. - * @param count кол-во позиций. - * @return массив позиций. - */ - @SuppressWarnings("unchecked") - @NotNull - public static Vector3f[] circularCoords(final float x, final float y, final float z, final int radius, final int count) { - - final Vector3f[] locs = new Vector3f[count]; - - final float angle = 360F / count; - - for (int i = 1; i <= count; i++) { - - final Vector3f loc = new Vector3f(); + float angle = 360F / count; - final float radians = AngleUtils.degreeToRadians(i * angle); + for (int i = 1; i <= count; i++) { - final float newX = calcX(x, radius, radians); - final float newY = calcY(y, radius, radians); + float radians = AngleUtils.degreeToRadians(angle * i); - loc.set(newX, newY, z); + float newX = x + radius * (float) Math.cos(radians); + float newY = y + radius * (float) Math.sin(radians); - locs[i - 1] = loc; - } + Vector3f point = source[i - 1]; - return locs; + point.set(newX, newY, z); } - /** - * Получение точек по кругу от указанной точки. - * - * @param source массив исходных точек. - * @param x координата центра. - * @param y координата центра. - * @param z координата центра. - * @param count кол-во точек. - * @param radius радиус от центра. - * @return массив точек. - */ - @NotNull - public static Vector3f[] getCircularPoints(@NotNull final Vector3f[] source, final float x, final float y, - final float z, final int count, final int radius) { - - if (count < 1) { - return source; - } - - final float angle = 360F / count; - - for (int i = 1; i <= count; i++) { - - final float radians = AngleUtils.degreeToRadians(angle * i); - - final float newX = x + radius * (float) Math.cos(radians); - final float newY = y + radius * (float) Math.sin(radians); - - final Vector3f point = source[i - 1]; - - point.set(newX, newY, z); - } - - return source; - } - - /** - * Рассчет случайной точки. - * - * @param loc the loc - * @param x центральная координата. - * @param y центральная координата. - * @param z центральная координата. - * @param radiusMin минимальный радиус рандома. - * @param radiusMax максимальный радиус рандома. - * @return новая точка. - */ - @NotNull - public static Vector3f randomCoords(@NotNull final Vector3f loc, final float x, final float y, final float z, - final int radiusMin, final int radiusMax) { - - final ThreadLocalRandom current = ThreadLocalRandom.current(); - - if (radiusMax == 0 || radiusMax < radiusMin) { - loc.set(x, y, z); - return loc; - } - - final int radius = current.nextInt(radiusMin, radiusMax); - final float radians = AngleUtils.degreeToRadians(current.nextInt(0, 360)); - - final float newX = calcX(x, radius, radians); - final float newY = calcY(y, radius, radians); - - loc.set(newX, newY, z); - - return loc; + return source; + } + + /** + * Рассчет случайной точки. + * + * @param loc the loc + * @param x центральная координата. + * @param y центральная координата. + * @param z центральная координата. + * @param radiusMin минимальный радиус рандома. + * @param radiusMax максимальный радиус рандома. + * @return новая точка. + */ + public static Vector3f randomCoords( + Vector3f loc, + float x, + float y, + float z, + int radiusMin, + int radiusMax) { + + ThreadLocalRandom current = ThreadLocalRandom.current(); + + if (radiusMax == 0 || radiusMax < radiusMin) { + loc.set(x, y, z); + return loc; } - /** - * Calculates the magnitude of the vector. - * - * @param x the X component. - * @param y the Y component. - * @return the length or magnitude of the vector. - */ - public static float length(float x, float y) { - return ExtMath.sqrt(lengthSquared(x, y)); - } - - /** - * Calculates the squared value of the - * magnitude of the vector. - * - * @param x the X component. - * @param y the Y component. - * @return the magnitude squared of the vector. - */ - public static float lengthSquared(float x, float y) { - return x * x + y * y; - } + int radius = current.nextInt(radiusMin, radiusMax); + float radians = AngleUtils.degreeToRadians(current.nextInt(0, 360)); + + float newX = calcX(x, radius, radians); + float newY = calcY(y, radius, radians); + + loc.set(newX, newY, z); + + return loc; + } + + /** + * Calculates the magnitude of the vector. + * + * @param x the X component. + * @param y the Y component. + * @return the length or magnitude of the vector. + */ + public static float length(float x, float y) { + return ExtMath.sqrt(lengthSquared(x, y)); + } + + /** + * Calculates the squared value of the magnitude of the vector. + * + * @param x the X component. + * @param y the Y component. + * @return the magnitude squared of the vector. + */ + public static float lengthSquared(float x, float y) { + return x * x + y * y; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/geom/util/GeometryUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/geom/util/GeometryUtils.java index bbab7835..803d4525 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/geom/util/GeometryUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/geom/util/GeometryUtils.java @@ -1,219 +1,257 @@ package javasabr.rlib.common.geom.util; +import org.jspecify.annotations.NullMarked; + /** * Набор геометрически методов. * * @author JavaSaBr */ +@NullMarked public final class GeometryUtils { - /** - * Рассчет расстояния между 2мя точками. - * - * @param startX координата первой точки. - * @param startY координата первой точки. - * @param startZ координата первой точки. - * @param targetX координата второй точки. - * @param targetY координата второй точки. - * @param targetZ координата второй точки. - * @return расстояние между точками. - */ - public static float getDistance(final float startX, final float startY, final float startZ, - final float targetX, final float targetY, final float targetZ) { - return (float) Math.sqrt(getSquareDistance(startX, startY, startZ, targetX, targetY, targetZ)); + /** + * Рассчет расстояния между 2мя точками. + * + * @param startX координата первой точки. + * @param startY координата первой точки. + * @param startZ координата первой точки. + * @param targetX координата второй точки. + * @param targetY координата второй точки. + * @param targetZ координата второй точки. + * @return расстояние между точками. + */ + public static float getDistance( + float startX, + float startY, + float startZ, + float targetX, + float targetY, + float targetZ) { + return (float) Math.sqrt(getSquareDistance(startX, startY, startZ, targetX, targetY, targetZ)); + } + + /** + * Возвращает расстояние от точки до отрезка. + * + * @param startX начальная координата отрезка. + * @param startY начальная координата отрезка. + * @param endX конечная координата отрезка. + * @param endY конечная координата отрезка. + * @param targetX координата точки. + * @param targetY координата точки. + * @return расстояние от точки до отрезка. + */ + public static float getDistanceToLine( + float startX, + float startY, + float endX, + float endY, + float targetX, + float targetY) { + return (float) Math.sqrt(getSquareDistanceToLine(startX, startY, endX, endY, targetX, targetY)); + } + + /** + * Возвращает расстояние от точки до отрезка. + * + * @param startX начальная координата отрезка. + * @param startY начальная координата отрезка. + * @param startZ начальная координата отрезка. + * @param endX конечная координата отрезка. + * @param endY конечная координата отрезка. + * @param endZ конечная координата отрезка. + * @param targetX координата точки. + * @param targetY координата точки. + * @param targetZ координата точки. + * @return расстояние от точки до отрезка. + */ + public static float getDistanceToLine( + float startX, + float startY, + float startZ, + float endX, + float endY, + float endZ, + float targetX, + float targetY, + float targetZ) { + return (float) Math.sqrt(getSquareDistanceToLine( + startX, + startY, + startZ, + endX, + endY, + endZ, + targetX, + targetY, + targetZ)); + } + + /** + * Get squared distance distance between two points. + * + * @param startX the start X coordinate. + * @param startY the start Y coordinate. + * @param startZ the start Z coordinate. + * @param targetX the end X coordinate. + * @param targetY the end Y coordinate. + * @param targetZ the end Z coordinate. + * @return the squared distance. + */ + public static float getSquareDistance( + float startX, + float startY, + float startZ, + float targetX, + float targetY, + float targetZ) { + + float dx = targetX - startX; + float dy = targetY - startY; + float dz = targetZ - startZ; + + return dx * dx + dy * dy + dz * dz; + } + + /** + * Возвращает квадрат расстояния от точки до отрезка. + * + * @param startX начальная координата отрезка. + * @param startY начальная координата отрезка. + * @param endX конечная координата отрезка. + * @param endY конечная координата отрезка. + * @param targetX координата точки. + * @param targetY координата точки. + * @return квадрат расстояния от точки до отрезка. + */ + public static float getSquareDistanceToLine( + final float startX, + final float startY, + float endX, + float endY, + float targetX, + float targetY) { + + endX -= startX; + endY -= startY; + + targetX -= startX; + targetY -= startY; + + float dotprod = targetX * endX + targetY * endY; + + float projlenSq; + + if (dotprod <= 0.0F) { + projlenSq = 0.0F; + } else { + + targetX = endX - targetX; + targetY = endY - targetY; + + dotprod = targetX * endX + targetY * endY; + + if (dotprod <= 0.0F) { + projlenSq = 0.0F; + } else { + projlenSq = dotprod * dotprod / (endX * endX + endY * endY); + } } - /** - * Возвращает расстояние от точки до отрезка. - * - * @param startX начальная координата отрезка. - * @param startY начальная координата отрезка. - * @param endX конечная координата отрезка. - * @param endY конечная координата отрезка. - * @param targetX координата точки. - * @param targetY координата точки. - * @return расстояние от точки до отрезка. - */ - public static float getDistanceToLine(final float startX, final float startY, final float endX, - final float endY, final float targetX, final float targetY) { - return (float) Math.sqrt(getSquareDistanceToLine(startX, startY, endX, endY, targetX, targetY)); - } + float lenSq = targetX * targetX + targetY * targetY - projlenSq; - /** - * Возвращает расстояние от точки до отрезка. - * - * @param startX начальная координата отрезка. - * @param startY начальная координата отрезка. - * @param startZ начальная координата отрезка. - * @param endX конечная координата отрезка. - * @param endY конечная координата отрезка. - * @param endZ конечная координата отрезка. - * @param targetX координата точки. - * @param targetY координата точки. - * @param targetZ координата точки. - * @return расстояние от точки до отрезка. - */ - public static float getDistanceToLine(final float startX, final float startY, final float startZ, - final float endX, final float endY, final float endZ, final float targetX, - final float targetY, final float targetZ) { - return (float) Math.sqrt(getSquareDistanceToLine(startX, startY, startZ, endX, endY, endZ, targetX, targetY, targetZ)); + if (lenSq < 0F) { + lenSq = 0F; } - /** - * Get squared distance distance between two points. - * - * @param startX the start X coordinate. - * @param startY the start Y coordinate. - * @param startZ the start Z coordinate. - * @param targetX the end X coordinate. - * @param targetY the end Y coordinate. - * @param targetZ the end Z coordinate. - * @return the squared distance. - */ - public static float getSquareDistance( - float startX, - float startY, - float startZ, - float targetX, - float targetY, - float targetZ - ) { - - float dx = targetX - startX; - float dy = targetY - startY; - float dz = targetZ - startZ; - - return dx * dx + dy * dy + dz * dz; + return lenSq; + } + + /** + * Возвращает квадрат расстояния от точки до отрезка. + * + * @param startX начальная координата отрезка. + * @param startY начальная координата отрезка. + * @param startZ начальная координата отрезка. + * @param endX конечная координата отрезка. + * @param endY конечная координата отрезка. + * @param endZ конечная координата отрезка. + * @param targetX координата точки. + * @param targetY координата точки. + * @param targetZ координата точки. + * @return квадрат расстояния от точки до отрезка. + */ + public static float getSquareDistanceToLine( + float startX, + float startY, + float startZ, + float endX, + float endY, + float endZ, + float targetX, + float targetY, + float targetZ) { + + float lineX = endX - startX; + float lineY = endY - startY; + float lineZ = endZ - startZ; + + float pointX = targetX - startX; + float pointY = targetY - startY; + float pointZ = targetZ - startZ; + + float c1 = scalar(pointX, pointY, pointZ, lineX, lineY, lineZ); + + if (c1 < 0F) { + return squareLength(targetX, targetY, targetZ, startX, startY, startZ); } - /** - * Возвращает квадрат расстояния от точки до отрезка. - * - * @param startX начальная координата отрезка. - * @param startY начальная координата отрезка. - * @param endX конечная координата отрезка. - * @param endY конечная координата отрезка. - * @param targetX координата точки. - * @param targetY координата точки. - * @return квадрат расстояния от точки до отрезка. - */ - public static float getSquareDistanceToLine(final float startX, final float startY, float endX, - float endY, float targetX, float targetY) { - - endX -= startX; - endY -= startY; - - targetX -= startX; - targetY -= startY; - - float dotprod = targetX * endX + targetY * endY; - - float projlenSq; - - if (dotprod <= 0.0F) { - projlenSq = 0.0F; - } else { - - targetX = endX - targetX; - targetY = endY - targetY; - - dotprod = targetX * endX + targetY * endY; + float c2 = scalar(lineX, lineY, lineZ, lineX, lineY, lineZ); - if (dotprod <= 0.0F) { - projlenSq = 0.0F; - } else { - projlenSq = dotprod * dotprod / (endX * endX + endY * endY); - } - } - - float lenSq = targetX * targetX + targetY * targetY - projlenSq; - - if (lenSq < 0F) { - lenSq = 0F; - } - - return lenSq; - } - - /** - * Возвращает квадрат расстояния от точки до отрезка. - * - * @param startX начальная координата отрезка. - * @param startY начальная координата отрезка. - * @param startZ начальная координата отрезка. - * @param endX конечная координата отрезка. - * @param endY конечная координата отрезка. - * @param endZ конечная координата отрезка. - * @param targetX координата точки. - * @param targetY координата точки. - * @param targetZ координата точки. - * @return квадрат расстояния от точки до отрезка. - */ - public static float getSquareDistanceToLine(final float startX, final float startY, final float startZ, - final float endX, final float endY, final float endZ, - final float targetX, final float targetY, final float targetZ) { - - final float lineX = endX - startX; - final float lineY = endY - startY; - final float lineZ = endZ - startZ; - - float pointX = targetX - startX; - float pointY = targetY - startY; - float pointZ = targetZ - startZ; - - final float c1 = scalar(pointX, pointY, pointZ, lineX, lineY, lineZ); - - if (c1 < 0F) { - return squareLength(targetX, targetY, targetZ, startX, startY, startZ); - } - - final float c2 = scalar(lineX, lineY, lineZ, lineX, lineY, lineZ); - - if (c2 <= c1) { - return squareLength(targetX, targetY, targetZ, endX, endY, endZ); - } - - final float b = c1 / c2; - - pointX = startX + lineX * b; - pointY = startY + lineY * b; - pointZ = startZ + lineZ * b; - - return squareLength(targetX, targetY, targetZ, pointX, pointY, pointZ); - } - - /** - * Производит скалярное произведение двух точек. - * - * @param x1 координата первой точки. - * @param y1 координата первой точки. - * @param z1 координата первой точки. - * @param x2 координата второй точки. - * @param y2 координата второй точки. - * @param z2 координата второй точки. - * @return произведение двух точек. - */ - public static float scalar(final float x1, final float y1, final float z1, final float x2, final float y2, final float z2) { - return x1 * x2 + y1 * y2 + z1 * z2; + if (c2 <= c1) { + return squareLength(targetX, targetY, targetZ, endX, endY, endZ); } - /** - * Находит квадрат длинны между двумя точками. - * - * @param x1 координата первой точки. - * @param y1 координата первой точки. - * @param z1 координата первой точки. - * @param x2 координата второй точки. - * @param y2 координата второй точки. - * @param z2 координата второй точки. - * @return квадрат длинны между точками. - */ - public static float squareLength(final float x1, final float y1, final float z1, final float x2, final float y2, final float z2) { - - final float dx = x1 - x2; - final float dy = y1 - y2; - final float dz = z1 - z2; - - return dx * dx + dy * dy + dz * dz; - } + float b = c1 / c2; + + pointX = startX + lineX * b; + pointY = startY + lineY * b; + pointZ = startZ + lineZ * b; + + return squareLength(targetX, targetY, targetZ, pointX, pointY, pointZ); + } + + /** + * Производит скалярное произведение двух точек. + * + * @param x1 координата первой точки. + * @param y1 координата первой точки. + * @param z1 координата первой точки. + * @param x2 координата второй точки. + * @param y2 координата второй точки. + * @param z2 координата второй точки. + * @return произведение двух точек. + */ + public static float scalar(float x1, float y1, float z1, float x2, float y2, float z2) { + return x1 * x2 + y1 * y2 + z1 * z2; + } + + /** + * Находит квадрат длинны между двумя точками. + * + * @param x1 координата первой точки. + * @param y1 координата первой точки. + * @param z1 координата первой точки. + * @param x2 координата второй точки. + * @param y2 координата второй точки. + * @param z2 координата второй точки. + * @return квадрат длинны между точками. + */ + public static float squareLength(float x1, float y1, float z1, float x2, float y2, float z2) { + float dx = x1 - x2; + float dy = y1 - y2; + float dz = z1 - z2; + return dx * dx + dy * dy + dz * dz; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/graphics/color/ColorRGBA.java b/rlib-common/src/main/java/javasabr/rlib/common/graphics/color/ColorRGBA.java index 3b386c55..bd8cad88 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/graphics/color/ColorRGBA.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/graphics/color/ColorRGBA.java @@ -1,278 +1,275 @@ package javasabr.rlib.common.graphics.color; +import java.io.Serial; import java.io.Serializable; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * THe implementation of a color class. * * @author JavaSaBr */ +@NullMarked public final class ColorRGBA implements Cloneable, Serializable { - private static final long serialVersionUID = -3342702659372723983L; + @Serial + private static final long serialVersionUID = -3342702659372723983L; - /** - * The red channel. - */ - public float r; + /** + * The red channel. + */ + public float r; - /** - * The green channel. - */ - public float g; + /** + * The green channel. + */ + public float g; - /** - * The blue channel. - */ - public float b; + /** + * The blue channel. + */ + public float b; - /** - * The alpha channel. - */ - public float a; + /** + * The alpha channel. + */ + public float a; - /** - * Instantiates a new Color rgba. - */ - public ColorRGBA() { - r = g = b = a = 1.0f; - } - - /** - * Instantiates a new Color rgba. - * - * @param rgba the rgba - */ - public ColorRGBA(@NotNull final ColorRGBA rgba) { - this.a = rgba.a; - this.r = rgba.r; - this.g = rgba.g; - this.b = rgba.b; - } + /** + * Instantiates a new Color rgba. + */ + public ColorRGBA() { + r = g = b = a = 1.0f; + } - /** - * Instantiates a new Color rgba. - * - * @param r the r - * @param g the g - * @param b the b - */ - public ColorRGBA(final float r, final float g, final float b) { - this.r = r; - this.g = g; - this.b = b; - this.a = 1F; - } + /** + * Instantiates a new Color rgba. + * + * @param rgba the rgba + */ + public ColorRGBA(ColorRGBA rgba) { + this.a = rgba.a; + this.r = rgba.r; + this.g = rgba.g; + this.b = rgba.b; + } - /** - * Instantiates a new Color rgba. - * - * @param r the r - * @param g the g - * @param b the b - * @param a the a - */ - public ColorRGBA(final float r, final float g, final float b, final float a) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } + /** + * Instantiates a new Color rgba. + * + * @param r the r + * @param g the g + * @param b the b + */ + public ColorRGBA(float r, float g, float b) { + this.r = r; + this.g = g; + this.b = b; + this.a = 1F; + } - /** - * Instantiates a new Color rgba. - * - * @param array the array - */ - public ColorRGBA(final float[] array) { - this.r = array[0]; - this.g = array.length > 1 ? array[1] : 1F; - this.b = array.length > 2 ? array[2] : 1F; - this.a = array.length > 3 ? array[3] : 1F; - } + /** + * Instantiates a new Color rgba. + * + * @param r the r + * @param g the g + * @param b the b + * @param a the a + */ + public ColorRGBA(float r, float g, float b, float a) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } - /** - * As int abgr int. - * - * @return the int - */ - public int asIntABGR() { - return ((int) (a * 255) & 0xFF) << 24 | - ((int) (b * 255) & 0xFF) << 16 | - ((int) (g * 255) & 0xFF) << 8 | - (int) (r * 255) & 0xFF; - } - - /** - * As int argb int. - * - * @return the int - */ - public int asIntARGB() { - return ((int) (a * 255) & 0xFF) << 24 | - ((int) (r * 255) & 0xFF) << 16 | - ((int) (g * 255) & 0xFF) << 8 | - (int) (b * 255) & 0xFF; - } - - /** - * As int rgba int. - * - * @return the int - */ - public int asIntRGBA() { - return ((int) (r * 255) & 0xFF) << 24 | - ((int) (g * 255) & 0xFF) << 16 | - ((int) (b * 255) & 0xFF) << 8 | - (int) (a * 255) & 0xFF; - } + /** + * Instantiates a new Color rgba. + * + * @param array the array + */ + public ColorRGBA(float[] array) { + this.r = array[0]; + this.g = array.length > 1 ? array[1] : 1F; + this.b = array.length > 2 ? array[2] : 1F; + this.a = array.length > 3 ? array[3] : 1F; + } - @Override - public boolean equals(final Object o) { + /** + * As int abgr int. + * + * @return the int + */ + public int asIntABGR() { + return + ((int) (a * 255) & 0xFF) << 24 | + ((int) (b * 255) & 0xFF) << 16 | + ((int) (g * 255) & 0xFF) << 8 | + (int) (r * 255) & 0xFF; + } - if (!(o instanceof ColorRGBA)) { - return false; - } else if (this == o) { - return true; - } + /** + * As int argb int. + * + * @return the int + */ + public int asIntARGB() { + return + ((int) (a * 255) & 0xFF) << 24 | + ((int) (r * 255) & 0xFF) << 16 | + ((int) (g * 255) & 0xFF) << 8 | + (int) (b * 255) & 0xFF; + } - final ColorRGBA comp = (ColorRGBA) o; + /** + * As int rgba int. + * + * @return the int + */ + public int asIntRGBA() { + return + ((int) (r * 255) & 0xFF) << 24 | + ((int) (g * 255) & 0xFF) << 16 | + ((int) (b * 255) & 0xFF) << 8 | + (int) (a * 255) & 0xFF; + } - if (Float.compare(r, comp.r) != 0) { - return false; - } else if (Float.compare(g, comp.g) != 0) { - return false; - } else if (Float.compare(b, comp.b) != 0) { - return false; - } else if (Float.compare(a, comp.a) != 0) { - return false; - } + @Override + public boolean equals(Object o) { - return true; + if (!(o instanceof ColorRGBA comp)) { + return false; + } else if (this == o) { + return true; } - /** - * From int argb. - * - * @param color the color - */ - public void fromIntARGB(final int color) { - a = ((byte) (color >> 24) & 0xFF) / 255f; - r = ((byte) (color >> 16) & 0xFF) / 255f; - g = ((byte) (color >> 8) & 0xFF) / 255f; - b = ((byte) color & 0xFF) / 255f; + if (Float.compare(r, comp.r) != 0) { + return false; + } else if (Float.compare(g, comp.g) != 0) { + return false; + } else if (Float.compare(b, comp.b) != 0) { + return false; + } else { + return Float.compare(a, comp.a) == 0; } + } - /** - * From int rgba. - * - * @param color the color - */ - public void fromIntRGBA(final int color) { - r = ((byte) (color >> 24) & 0xFF) / 255f; - g = ((byte) (color >> 16) & 0xFF) / 255f; - b = ((byte) (color >> 8) & 0xFF) / 255f; - a = ((byte) color & 0xFF) / 255f; - } + /** + * From int argb. + * + * @param color the color + */ + public void fromIntARGB(int color) { + a = ((byte) (color >> 24) & 0xFF) / 255f; + r = ((byte) (color >> 16) & 0xFF) / 255f; + g = ((byte) (color >> 8) & 0xFF) / 255f; + b = ((byte) color & 0xFF) / 255f; + } - /** - * Gets alpha. - * - * @return the alpha channel. - */ - public float getAlpha() { - return a; - } + /** + * From int rgba. + * + * @param color the color + */ + public void fromIntRGBA(int color) { + r = ((byte) (color >> 24) & 0xFF) / 255f; + g = ((byte) (color >> 16) & 0xFF) / 255f; + b = ((byte) (color >> 8) & 0xFF) / 255f; + a = ((byte) color & 0xFF) / 255f; + } - /** - * Gets blue. - * - * @return the blue channel. - */ - public float getBlue() { - return b; - } + /** + * Gets alpha. + * + * @return the alpha channel. + */ + public float getAlpha() { + return a; + } - /** - * Gets green. - * - * @return the green channel. - */ - public float getGreen() { - return g; - } + /** + * Gets blue. + * + * @return the blue channel. + */ + public float getBlue() { + return b; + } - /** - * Gets red. - * - * @return the red channel. - */ - public float getRed() { - return r; - } + /** + * Gets green. + * + * @return the green channel. + */ + public float getGreen() { + return g; + } - @Override - public int hashCode() { - int hash = 37; - hash += 37 * hash + Float.floatToIntBits(r); - hash += 37 * hash + Float.floatToIntBits(g); - hash += 37 * hash + Float.floatToIntBits(b); - hash += 37 * hash + Float.floatToIntBits(a); - return hash; - } + /** + * Gets red. + * + * @return the red channel. + */ + public float getRed() { + return r; + } - /** - * Interpolate. - * - * @param beginColor the begin color - * @param finalColor the final color - * @param changeAmnt the change amnt - */ - public void interpolate(@NotNull final ColorRGBA beginColor, @NotNull final ColorRGBA finalColor, final float changeAmnt) { - this.r = (1 - changeAmnt) * beginColor.r + changeAmnt * finalColor.r; - this.g = (1 - changeAmnt) * beginColor.g + changeAmnt * finalColor.g; - this.b = (1 - changeAmnt) * beginColor.b + changeAmnt * finalColor.b; - this.a = (1 - changeAmnt) * beginColor.a + changeAmnt * finalColor.a; - } + @Override + public int hashCode() { + int hash = 37; + hash += 37 * hash + Float.floatToIntBits(r); + hash += 37 * hash + Float.floatToIntBits(g); + hash += 37 * hash + Float.floatToIntBits(b); + hash += 37 * hash + Float.floatToIntBits(a); + return hash; + } - /** - * Interpolate. - * - * @param finalColor the final color - * @param changeAmnt the change amnt - */ - public void interpolate(@NotNull final ColorRGBA finalColor, final float changeAmnt) { - this.r = (1 - changeAmnt) * this.r + changeAmnt * finalColor.r; - this.g = (1 - changeAmnt) * this.g + changeAmnt * finalColor.g; - this.b = (1 - changeAmnt) * this.b + changeAmnt * finalColor.b; - this.a = (1 - changeAmnt) * this.a + changeAmnt * finalColor.a; - } + /** + * Interpolate. + * + * @param beginColor the begin color + * @param finalColor the final color + * @param changeAmnt the change amnt + */ + public void interpolate(ColorRGBA beginColor, ColorRGBA finalColor, float changeAmnt) { + this.r = (1 - changeAmnt) * beginColor.r + changeAmnt * finalColor.r; + this.g = (1 - changeAmnt) * beginColor.g + changeAmnt * finalColor.g; + this.b = (1 - changeAmnt) * beginColor.b + changeAmnt * finalColor.b; + this.a = (1 - changeAmnt) * beginColor.a + changeAmnt * finalColor.a; + } - /** - * Set color rgba. - * - * @param r the r - * @param g the g - * @param b the b - * @param a the a - * @return the color rgba - */ - public ColorRGBA set(final float r, final float g, final float b, final float a) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - return this; - } + /** + * Interpolate. + * + * @param finalColor the final color + * @param changeAmnt the change amnt + */ + public void interpolate(ColorRGBA finalColor, float changeAmnt) { + this.r = (1 - changeAmnt) * this.r + changeAmnt * finalColor.r; + this.g = (1 - changeAmnt) * this.g + changeAmnt * finalColor.g; + this.b = (1 - changeAmnt) * this.b + changeAmnt * finalColor.b; + this.a = (1 - changeAmnt) * this.a + changeAmnt * finalColor.a; + } - @Override - public String toString() { - return "ColorRGBA{" + - "red=" + r + - ", green=" + g + - ", blue=" + b + - ", alpha=" + a + - '}'; - } + /** + * Set color rgba. + * + * @param r the r + * @param g the g + * @param b the b + * @param a the a + * @return the color rgba + */ + public ColorRGBA set(float r, float g, float b, float a) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + return this; + } + + @Override + public String toString() { + return "ColorRGBA{" + "red=" + r + ", green=" + g + ", blue=" + b + ", alpha=" + a + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/io/ReusableStream.java b/rlib-common/src/main/java/javasabr/rlib/common/io/ReusableStream.java index ff6254ca..3dc3a257 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/io/ReusableStream.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/io/ReusableStream.java @@ -1,28 +1,29 @@ package javasabr.rlib.common.io; import java.io.IOException; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a reusable streams. * * @author JavaSaBr */ +@NullMarked public interface ReusableStream { - /** - * Reset this stream. - * - * @throws IOException the io exception - */ - void reset() throws IOException; + /** + * Reset this stream. + * + * @throws IOException the io exception + */ + void reset() throws IOException; - /** - * Initialize this string using the buffer. - * - * @param buffer the buffer data. - * @param offset the offset. - * @param length the length. - */ - void initFor(@NotNull byte[] buffer, int offset, int length); + /** + * Initialize this string using the buffer. + * + * @param buffer the buffer data. + * @param offset the offset. + * @param length the length. + */ + void initFor(byte[] buffer, int offset, int length); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java index eb60782d..c2e3b316 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java @@ -5,63 +5,66 @@ import java.io.OutputStream; import javax.imageio.stream.ImageOutputStreamImpl; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of a redirector image input stream. * * @author JavaSaBr */ +@NullMarked public class RedirectImageOutputStream extends ImageOutputStreamImpl { - /** - * The output stream. - */ - private OutputStream out; + /** + * The output stream. + */ + private @Nullable OutputStream out; - /** - * The input stream. - */ - private InputStream in; + /** + * The input stream. + */ + private @Nullable InputStream in; - @Override - public void close() throws IOException { - } + @Override + public void close() throws IOException { + } - @Override - public int read() throws IOException { - return in.read(); - } + @Override + public int read() throws IOException { + return in.read(); + } - @Override - public int read(@NotNull final byte[] b, final int off, final int len) throws IOException { - return in.read(b, off, len); - } + @Override + public int read(byte[] b, int off, int len) throws IOException { + return in.read(b, off, len); + } - /** - * Sets in. - * - * @param in the input stream. - */ - public void setIn(@NotNull final InputStream in) { - this.in = in; - } + /** + * Sets in. + * + * @param in the input stream. + */ + public void setIn(InputStream in) { + this.in = in; + } - /** - * Sets out. - * - * @param out the output stream. - */ - public void setOut(@NotNull final OutputStream out) { - this.out = out; - } + /** + * Sets out. + * + * @param out the output stream. + */ + public void setOut(OutputStream out) { + this.out = out; + } - @Override - public void write(@NotNull final byte[] b, final int off, final int len) throws IOException { - out.write(b, off, len); - } + @Override + public void write(byte[] b, int off, int len) throws IOException { + out.write(b, off, len); + } - @Override - public void write(final int b) throws IOException { - out.write(b); - } + @Override + public void write(int b) throws IOException { + out.write(b); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesInputStream.java b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesInputStream.java index 0ee1015d..955d7dba 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesInputStream.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesInputStream.java @@ -3,97 +3,96 @@ import java.io.InputStream; import javasabr.rlib.common.io.ReusableStream; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of reusable input stream. * * @author JavaSaBr */ +@NullMarked public final class ReuseBytesInputStream extends InputStream implements ReusableStream { - /** - * The data buffer. - */ - @NotNull - protected byte buffer[]; - - /** - * The position. - */ - protected int pos; - - /** - * The count bytes. - */ - protected int count; - - public ReuseBytesInputStream() { - this.buffer = ArrayUtils.EMPTY_BYTE_ARRAY; + /** + * The data buffer. + */ + protected byte[] buffer; + + /** + * The position. + */ + protected int pos; + + /** + * The count bytes. + */ + protected int count; + + public ReuseBytesInputStream() { + this.buffer = ArrayUtils.EMPTY_BYTE_ARRAY; + } + + public ReuseBytesInputStream(byte buffer[]) { + this.buffer = buffer; + this.pos = 0; + this.count = buffer.length; + } + + public ReuseBytesInputStream(byte[] buffer, int offset, int length) { + this.buffer = buffer; + this.pos = offset; + this.count = Math.min(offset + length, buffer.length); + } + + @Override + public void initFor(byte[] buffer, int offset, int length) { + this.buffer = buffer; + this.pos = offset; + this.count = length; + } + + @Override + public synchronized int read() { + return (pos < count) ? (buffer[pos++] & 0xff) : -1; + } + + @Override + public synchronized int read(byte[] buffer, int offset, int length) { + + if (offset < 0 || length < 0 || length > buffer.length - offset) { + throw new IndexOutOfBoundsException(); } - public ReuseBytesInputStream(@NotNull final byte buffer[]) { - this.buffer = buffer; - this.pos = 0; - this.count = buffer.length; + if (pos >= count) { + return -1; } - public ReuseBytesInputStream(@NotNull final byte buffer[], final int offset, final int length) { - this.buffer = buffer; - this.pos = offset; - this.count = Math.min(offset + length, buffer.length); - } + int available = count - pos; - @Override - public void initFor(@NotNull final byte[] buffer, final int offset, final int length) { - this.buffer = buffer; - this.pos = offset; - this.count = length; + if (length > available) { + length = available; } - @Override - public synchronized int read() { - return (pos < count) ? (buffer[pos++] & 0xff) : -1; + if (length <= 0) { + return 0; } - @Override - public synchronized int read(@NotNull final byte buffer[], int offset, int length) { - - if (offset < 0 || length < 0 || length > buffer.length - offset) { - throw new IndexOutOfBoundsException(); - } - - if (pos >= count) { - return -1; - } - - int available = count - pos; + System.arraycopy(this.buffer, pos, buffer, offset, length); + pos += length; - if (length > available) { - length = available; - } + return length; + } - if (length <= 0) { - return 0; - } + @Override + public synchronized int available() { + return count - pos; + } - System.arraycopy(this.buffer, pos, buffer, offset, length); - pos += length; + @Override + public void close() {} - return length; - } - - @Override - public synchronized int available() { - return count - pos; - } - - @Override - public void close() { - } - - @Override - public synchronized void reset() { - this.pos = 0; - } + @Override + public synchronized void reset() { + this.pos = 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesOutputStream.java b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesOutputStream.java index a7df85fa..a3dd12e1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesOutputStream.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/ReuseBytesOutputStream.java @@ -4,143 +4,144 @@ import java.io.UnsupportedEncodingException; import java.util.Arrays; import javasabr.rlib.common.io.ReusableStream; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of reusable output stream. * * @author JavaSaBr */ +@NullMarked public final class ReuseBytesOutputStream extends OutputStream implements ReusableStream { - /** - * The data buffer. - */ - @NotNull - protected byte[] data; + /** + * The data buffer. + */ + protected byte[] data; - /** - * The size of stream. - */ - protected int size; + /** + * The size of stream. + */ + protected int size; - public ReuseBytesOutputStream() { - this(32); - } + public ReuseBytesOutputStream() { + this(32); + } - public ReuseBytesOutputStream(final int size) { - if (size < 0) throw new IllegalArgumentException("Negative initial size: " + size); - data = new byte[size]; + public ReuseBytesOutputStream(int size) { + if (size < 0) { + throw new IllegalArgumentException("Negative initial size: " + size); } + data = new byte[size]; + } - @Override - public void initFor(@NotNull final byte[] buffer, final int offset, final int length) { - - if (offset != 0) { - throw new IllegalArgumentException("doesn't support offset."); - } - - this.data = buffer; - this.size = length; - } + @Override + public void initFor(byte[] buffer, int offset, int length) { - /** - * Check needing resizing the buffer. - * - * @param minCapacity the min capacity. - */ - private void checkLength(final int minCapacity) { - if (minCapacity - data.length > 0) { - resizeData(minCapacity); - } + if (offset != 0) { + throw new IllegalArgumentException("doesn't support offset."); } - @Override - public void close() { + this.data = buffer; + this.size = length; + } + + /** + * Check needing resizing the buffer. + * + * @param minCapacity the min capacity. + */ + private void checkLength(int minCapacity) { + if (minCapacity - data.length > 0) { + resizeData(minCapacity); } - - /** - * Get the wrapped data array. - * - * @return the wrapped data array. - */ - public @NotNull byte[] getData() { - return data; + } + + @Override + public void close() { + } + + /** + * Get the wrapped data array. + * + * @return the wrapped data array. + */ + public byte[] getData() { + return data; + } + + @Override + public void reset() { + size = 0; + } + + /** + * Resize the data buffer. + * + * @param minCapacity the min capacity. + */ + private void resizeData(int minCapacity) { + + int oldCapacity = data.length; + int newCapacity = oldCapacity << 1; + + if (newCapacity - minCapacity < 0) { + newCapacity = minCapacity; } - @Override - public void reset() { - size = 0; - } - - /** - * Resize the data buffer. - * - * @param minCapacity the min capacity. - */ - private void resizeData(final int minCapacity) { - - final int oldCapacity = data.length; - - int newCapacity = oldCapacity << 1; - - if (newCapacity - minCapacity < 0) { - newCapacity = minCapacity; - } - - if (newCapacity < 0) { + if (newCapacity < 0) { - if (minCapacity < 0) { - throw new OutOfMemoryError(); - } + if (minCapacity < 0) { + throw new OutOfMemoryError(); + } - newCapacity = Integer.MAX_VALUE; - } - - data = Arrays.copyOf(data, newCapacity); - } - - /** - * Get the current size. - * - * @return the current size. - */ - public int size() { - return size; - } - - @Override - public String toString() { - return new String(data, 0, size); + newCapacity = Integer.MAX_VALUE; } - /** - * To string string. - * - * @param charsetName the charset name - * @return the string - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - public String toString(final String charsetName) throws UnsupportedEncodingException { - return new String(data, 0, size, charsetName); + data = Arrays.copyOf(data, newCapacity); + } + + /** + * Get the current size. + * + * @return the current size. + */ + public int size() { + return size; + } + + @Override + public String toString() { + return new String(data, 0, size); + } + + /** + * To string string. + * + * @param charsetName the charset name + * @return the string + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + public String toString(String charsetName) throws UnsupportedEncodingException { + return new String(data, 0, size, charsetName); + } + + @Override + public void write(byte[] buffer, int offset, int length) { + + if (offset < 0 || offset > buffer.length || length < 0 || offset + length - buffer.length > 0) { + throw new IndexOutOfBoundsException(); } - @Override - public void write(@NotNull final byte[] buffer, final int offset, final int length) { - - if (offset < 0 || offset > buffer.length || length < 0 || offset + length - buffer.length > 0) { - throw new IndexOutOfBoundsException(); - } - - checkLength(size + length); - System.arraycopy(buffer, offset, data, size, length); - size += length; - } - - @Override - public void write(final int b) { - checkLength(size + 1); - data[size] = (byte) b; - size += 1; - } + checkLength(size + length); + System.arraycopy(buffer, offset, data, size, length); + size += length; + } + + @Override + public void write(int b) { + checkLength(size + 1); + data[size] = (byte) b; + size += 1; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/manager/InitializeManager.java b/rlib-common/src/main/java/javasabr/rlib/common/manager/InitializeManager.java index db2f94b1..73a97b37 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/manager/InitializeManager.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/manager/InitializeManager.java @@ -7,76 +7,77 @@ import java.util.Iterator; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The manager to initialize singletons in some order. * * @author JavaSaBr */ +@NullMarked public final class InitializeManager { - private static final Logger LOGGER = LoggerManager.getLogger(InitializeManager.class); + private static final Logger LOGGER = LoggerManager.getLogger(InitializeManager.class); - private static final String METHOD_NAME = "getInstance"; + private static final String METHOD_NAME = "getInstance"; - private static final Deque> QUEUE = new ArrayDeque<>(); + private static final Deque> QUEUE = new ArrayDeque<>(); - /** - * Initialize. - */ - public synchronized static void initialize() { + /** + * Initialize. + */ + public synchronized static void initialize() { - for (Iterator> iterator = QUEUE.iterator(); iterator.hasNext(); ) { + for (Iterator> iterator = QUEUE.iterator(); iterator.hasNext(); ) { - Class next = iterator.next(); - try { + Class next = iterator.next(); + try { - Method method = next.getMethod(METHOD_NAME); - Object instance = method.invoke(null); + Method method = next.getMethod(METHOD_NAME); + Object instance = method.invoke(null); - if (instance == null) { - LOGGER.warning("no initialize class " + next); - } - - iterator.remove(); - - } catch (InvocationTargetException e) { - LOGGER.warning(e.getTargetException()); - } catch (Throwable e) { - LOGGER.warning(e); - } + if (instance == null) { + LOGGER.warning("no initialize class " + next); } - } - /** - * Add a class with static method 'getInstance' to initialization queue. - * - * @param cs the class. - */ - public static synchronized void register(@NotNull Class cs) { - - try { - cs.getMethod(METHOD_NAME); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } + iterator.remove(); - QUEUE.add(cs); + } catch (InvocationTargetException e) { + LOGGER.warning(e.getTargetException()); + } catch (Throwable e) { + LOGGER.warning(e); + } } - - /** - * Check validity of the class in initialization order. - * - * @param cs the class. - */ - public static synchronized void valid(@NotNull Class cs) { - if (QUEUE.getFirst() != cs) { - throw new IllegalStateException("The class has invalid initialization position."); - } + } + + /** + * Add a class with static method 'getInstance' to initialization queue. + * + * @param cs the class. + */ + public static synchronized void register(Class cs) { + + try { + cs.getMethod(METHOD_NAME); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); } - private InitializeManager() { - throw new RuntimeException(); + QUEUE.add(cs); + } + + /** + * Check validity of the class in initialization order. + * + * @param cs the class. + */ + public static synchronized void valid(Class cs) { + if (QUEUE.getFirst() != cs) { + throw new IllegalStateException("The class has invalid initialization position."); } + } + + private InitializeManager() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java index 0d3ff62c..983669dc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java @@ -5,206 +5,239 @@ import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class to monitor memory usage. * * @author JavaSaBr */ +@NullMarked public class MemoryMonitoring { - /** - * The constant MEMORY_POOL_CODE_CACHE. - */ - public static final String MEMORY_POOL_CODE_CACHE = "Code Cache"; - /** - * The constant MEMORY_POOL_COMPRESSED_CLASS_SPACE. - */ - public static final String MEMORY_POOL_COMPRESSED_CLASS_SPACE = "Compressed Class Space"; - /** - * The constant MEMORY_POOL_METASPACE. - */ - public static final String MEMORY_POOL_METASPACE = "Metaspace"; - /** - * The constant MEMORY_POOL_EDEN_SPACE. - */ - public static final String MEMORY_POOL_EDEN_SPACE = "PS Eden Space"; - /** - * The constant MEMORY_POOL_SURVIVOR_SPACE. - */ - public static final String MEMORY_POOL_SURVIVOR_SPACE = "PS Survivor Space"; - /** - * The constant MEMORY_POOL_OLD_GEN. - */ - public static final String MEMORY_POOL_OLD_GEN = "PS Old Gen"; - - /** - * The list of memory pools. - */ - @NotNull - private final List memoryPoolMXBeans; - - /** - * The memory manager. - */ - @NotNull - private final MemoryMXBean memoryMXBean; - - /** - * Instantiates a new Memory monitoring. - */ - public MemoryMonitoring() { - this.memoryMXBean = ManagementFactory.getMemoryMXBean(); - this.memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); + /** + * The constant MEMORY_POOL_CODE_CACHE. + */ + public static final String MEMORY_POOL_CODE_CACHE = "Code Cache"; + /** + * The constant MEMORY_POOL_COMPRESSED_CLASS_SPACE. + */ + public static final String MEMORY_POOL_COMPRESSED_CLASS_SPACE = "Compressed Class Space"; + /** + * The constant MEMORY_POOL_METASPACE. + */ + public static final String MEMORY_POOL_METASPACE = "Metaspace"; + /** + * The constant MEMORY_POOL_EDEN_SPACE. + */ + public static final String MEMORY_POOL_EDEN_SPACE = "PS Eden Space"; + /** + * The constant MEMORY_POOL_SURVIVOR_SPACE. + */ + public static final String MEMORY_POOL_SURVIVOR_SPACE = "PS Survivor Space"; + /** + * The constant MEMORY_POOL_OLD_GEN. + */ + public static final String MEMORY_POOL_OLD_GEN = "PS Old Gen"; + + /** + * The list of memory pools. + */ + private final List memoryPoolMXBeans; + + /** + * The memory manager. + */ + private final MemoryMXBean memoryMXBean; + + /** + * Instantiates a new Memory monitoring. + */ + public MemoryMonitoring() { + this.memoryMXBean = ManagementFactory.getMemoryMXBean(); + this.memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); + } + + /** + * Find a memory pool been by a name. + * + * @param name the name. + * @return the found bean or null. + */ + @Nullable + private MemoryPoolMXBean findMemoryPoolMXBeen(String name) { + return memoryPoolMXBeans + .stream() + .filter(bean -> bean + .getName() + .contains(name)) + .findAny() + .orElse(null); + } + + /** + * Get max heap size. + * + * @return the max heap size. + */ + public long getHeapMaxSize() { + return getHeapMaxSize(memoryMXBean.getHeapMemoryUsage()); + } + + private long getHeapMaxSize(MemoryUsage memoryUsage) { + return memoryUsage.getMax(); + } + + /** + * Get current heap size. + * + * @return the current heap size. + */ + public long getHeapSize() { + return getHeapSize(memoryMXBean.getHeapMemoryUsage()); + } + + private long getHeapSize(MemoryUsage memoryUsage) { + return memoryUsage.getCommitted(); + } + + /** + * Get heap usage percent. + * + * @return the heap usage percent. + */ + public double getHeapUsagePercent() { + return getHeapUsagePercent(memoryMXBean.getHeapMemoryUsage()); + } + + private double getHeapUsagePercent(MemoryUsage memoryUsage) { + return getHeapUsedSize(memoryUsage) / (double) getHeapSize(memoryUsage) * 100; + } + + /** + * Get heap usage size. + * + * @return the heap usage size. + */ + public long getHeapUsedSize() { + return getHeapUsedSize(memoryMXBean.getHeapMemoryUsage()); + } + + private long getHeapUsedSize(MemoryUsage memoryUsage) { + return memoryUsage.getUsed(); + } + + /** + * Get max size of a memory pool. + * + * @param name the name of a memory pool. + * @return the max size. + */ + public long getMemoryPoolMaxSize(String name) { + + MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); + if (mxBean == null) { + throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); } - /** - * Find a memory pool been by a name. - * - * @param name the name. - * @return the found bean or null. - */ - @Nullable - private MemoryPoolMXBean findMemoryPoolMXBeen(@NotNull final String name) { - return memoryPoolMXBeans.stream() - .filter(bean -> bean.getName().contains(name)) - .findAny().orElse(null); + MemoryUsage usage = mxBean.getUsage(); + return usage.getMax(); + } + + /** + * Get current size a memory pool. + * + * @param name the name of a memory pool. + * @return the current size. + */ + public long getMemoryPoolSize(String name) { + + MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); + if (mxBean == null) { + throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); } - /** - * Get max heap size. - * - * @return the max heap size. - */ - public long getHeapMaxSize() { - return getHeapMaxSize(memoryMXBean.getHeapMemoryUsage()); + MemoryUsage usage = mxBean.getUsage(); + return usage.getCommitted(); + } + + /** + * Get used size a memory pool. + * + * @param name the name of a memory pool. + * @return the used size. + */ + public long getMemoryPoolUsed(String name) { + + MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); + if (mxBean == null) { + throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); } - private long getHeapMaxSize(@NotNull final MemoryUsage memoryUsage) { - return memoryUsage.getMax(); + MemoryUsage usage = mxBean.getUsage(); + return usage.getUsed(); + } + + @Override + public String toString() { + + MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage(); + + StringBuilder builder = new StringBuilder(); + builder + .append("HeapMaxSize: ") + .append(getHeapMaxSize(memoryUsage) / 1024 / 1024) + .append(" MiB.\n"); + builder + .append("HeapSize: ") + .append(getHeapSize(memoryUsage) / 1024 / 1024) + .append(" MiB.\n"); + builder + .append("HeapUsedSize: ") + .append(getHeapUsedSize(memoryUsage) / 1024 / 1024) + .append(" MiB.\n"); + builder + .append("HeapUsagePercent: ") + .append(getHeapUsagePercent(memoryUsage)) + .append("%."); + + if (!memoryPoolMXBeans.isEmpty()) { + builder + .append('\n') + .append("Memory Pools:"); } - /** - * Get current heap size. - * - * @return the current heap size. - */ - public long getHeapSize() { - return getHeapSize(memoryMXBean.getHeapMemoryUsage()); + for (MemoryPoolMXBean mxBeen : memoryPoolMXBeans) { + + MemoryUsage usage = mxBeen.getUsage(); + + builder + .append('\n') + .append(mxBeen.getName()) + .append(":\n"); + builder + .append(" ") + .append("MemoryType: ") + .append(mxBeen.getType()) + .append('\n'); + builder + .append(" ") + .append("MemoryMaxSize: ") + .append(usage.getMax() / 1024 / 1024) + .append(" MiB.\n"); + builder + .append(" ") + .append("MemorySize: ") + .append(usage.getCommitted() / 1024 / 1024) + .append(" MiB.\n"); + builder + .append(" ") + .append("MemoryUsed: ") + .append(usage.getUsed() / 1024 / 1024) + .append(" MiB."); } - private long getHeapSize(@NotNull final MemoryUsage memoryUsage) { - return memoryUsage.getCommitted(); - } - - /** - * Get heap usage percent. - * - * @return the heap usage percent. - */ - public double getHeapUsagePercent() { - return getHeapUsagePercent(memoryMXBean.getHeapMemoryUsage()); - } - - private double getHeapUsagePercent(@NotNull final MemoryUsage memoryUsage) { - return getHeapUsedSize(memoryUsage) / (double) getHeapSize(memoryUsage) * 100; - } - - /** - * Get heap usage size. - * - * @return the heap usage size. - */ - public long getHeapUsedSize() { - return getHeapUsedSize(memoryMXBean.getHeapMemoryUsage()); - } - - private long getHeapUsedSize(@NotNull final MemoryUsage memoryUsage) { - return memoryUsage.getUsed(); - } - - /** - * Get max size of a memory pool. - * - * @param name the name of a memory pool. - * @return the max size. - */ - public long getMemoryPoolMaxSize(@NotNull final String name) { - - final MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); - - if (mxBean == null) { - throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); - } - - final MemoryUsage usage = mxBean.getUsage(); - return usage.getMax(); - } - - /** - * Get current size a memory pool. - * - * @param name the name of a memory pool. - * @return the current size. - */ - public long getMemoryPoolSize(@NotNull final String name) { - - final MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); - - if (mxBean == null) { - throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); - } - - final MemoryUsage usage = mxBean.getUsage(); - return usage.getCommitted(); - } - - /** - * Get used size a memory pool. - * - * @param name the name of a memory pool. - * @return the used size. - */ - public long getMemoryPoolUsed(@NotNull final String name) { - - final MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); - - if (mxBean == null) { - throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); - } - - final MemoryUsage usage = mxBean.getUsage(); - return usage.getUsed(); - } - - @Override - public String toString() { - - final MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage(); - - final StringBuilder builder = new StringBuilder(); - builder.append("HeapMaxSize: ").append(getHeapMaxSize(memoryUsage) / 1024 / 1024).append(" MiB.\n"); - builder.append("HeapSize: ").append(getHeapSize(memoryUsage) / 1024 / 1024).append(" MiB.\n"); - builder.append("HeapUsedSize: ").append(getHeapUsedSize(memoryUsage) / 1024 / 1024).append(" MiB.\n"); - builder.append("HeapUsagePercent: ").append(getHeapUsagePercent(memoryUsage)).append("%."); - - if (!memoryPoolMXBeans.isEmpty()) { - builder.append('\n').append("Memory Pools:"); - } - - for (final MemoryPoolMXBean mxBeen : memoryPoolMXBeans) { - - final MemoryUsage usage = mxBeen.getUsage(); - - builder.append('\n').append(mxBeen.getName()).append(":\n"); - builder.append(" ").append("MemoryType: ").append(mxBeen.getType()).append('\n'); - builder.append(" ").append("MemoryMaxSize: ").append(usage.getMax() / 1024 / 1024).append(" MiB.\n"); - builder.append(" ").append("MemorySize: ").append(usage.getCommitted() / 1024 / 1024).append(" MiB.\n"); - builder.append(" ").append("MemoryUsed: ").append(usage.getUsed() / 1024 / 1024).append(" MiB."); - } - - return builder.toString(); - } + return builder.toString(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java index 6cace892..4cf0a8e5 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java @@ -1,94 +1,95 @@ package javasabr.rlib.common.monitoring; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The class to monitor a state a Java process. * * @author JavaSaBr */ +@NullMarked public final class MonitoringManager { - @NotNull - private static final MonitoringManager INSTANCE = new MonitoringManager(); + private static final MonitoringManager INSTANCE = new MonitoringManager(); - /** - * Gets instance. - * - * @return the instance - */ - @NotNull - public static MonitoringManager getInstance() { - return INSTANCE; - } + /** + * Gets instance. + * + * @return the instance + */ + public static MonitoringManager getInstance() { + return INSTANCE; + } - /** - * The memory monitoring. - */ - @NotNull - private final MemoryMonitoring memoryMonitoring; + /** + * The memory monitoring. + */ + private final MemoryMonitoring memoryMonitoring; - /** - * The runtime monitoring. - */ - @NotNull - private final RuntimeMonitoring runtimeMonitoring; + /** + * The runtime monitoring. + */ + private final RuntimeMonitoring runtimeMonitoring; - /** - * The threads monitoring. - */ - @NotNull - private final ThreadMonitoring threadMonitoring; + /** + * The threads monitoring. + */ + private final ThreadMonitoring threadMonitoring; - private MonitoringManager() { - this.memoryMonitoring = new MemoryMonitoring(); - this.runtimeMonitoring = new RuntimeMonitoring(); - this.threadMonitoring = new ThreadMonitoring(); - } + private MonitoringManager() { + this.memoryMonitoring = new MemoryMonitoring(); + this.runtimeMonitoring = new RuntimeMonitoring(); + this.threadMonitoring = new ThreadMonitoring(); + } - /** - * Gets memory monitoring. - * - * @return the memory monitoring. - */ - @NotNull - public MemoryMonitoring getMemoryMonitoring() { - return memoryMonitoring; - } + /** + * Gets memory monitoring. + * + * @return the memory monitoring. + */ + public MemoryMonitoring getMemoryMonitoring() { + return memoryMonitoring; + } - /** - * Gets runtime monitoring. - * - * @return the runtime monitoring. - */ - @NotNull - public RuntimeMonitoring getRuntimeMonitoring() { - return runtimeMonitoring; - } + /** + * Gets runtime monitoring. + * + * @return the runtime monitoring. + */ + public RuntimeMonitoring getRuntimeMonitoring() { + return runtimeMonitoring; + } - /** - * Gets thread monitoring. - * - * @return the threads monitoring. - */ - @NotNull - public ThreadMonitoring getThreadMonitoring() { - return threadMonitoring; - } + /** + * Gets thread monitoring. + * + * @return the threads monitoring. + */ + public ThreadMonitoring getThreadMonitoring() { + return threadMonitoring; + } - @Override - public String toString() { + @Override + public String toString() { - final StringBuilder builder = new StringBuilder("\n"); - builder.append("#==========Java Process Info==========#").append('\n'); - builder.append("#=============Memory Info=============#"); - builder.append('\n').append(getMemoryMonitoring()).append('\n'); - builder.append("#============Runtime Info=============#"); - builder.append('\n').append(getRuntimeMonitoring()).append('\n'); - // builder.append("#============Current state============#"); - // builder.append('\n').append(getThreadMonitoring()).append('\n'); - builder.append("#=====================================#"); + StringBuilder builder = new StringBuilder("\n"); + builder + .append("#==========Java Process Info==========#") + .append('\n'); + builder.append("#=============Memory Info=============#"); + builder + .append('\n') + .append(getMemoryMonitoring()) + .append('\n'); + builder.append("#============Runtime Info=============#"); + builder + .append('\n') + .append(getRuntimeMonitoring()) + .append('\n'); + // builder.append("#============Current state============#"); + // builder.append('\n').append(getThreadMonitoring()).append('\n'); + builder.append("#=====================================#"); - return builder.toString(); - } + return builder.toString(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java index 24bee274..b9deef49 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java @@ -8,63 +8,108 @@ import java.text.SimpleDateFormat; import java.util.Date; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The class to monitor a runtime state of a java process. * * @author JavaSaBr */ +@NullMarked public class RuntimeMonitoring { - @NotNull - private static final ThreadLocal LOCAL_DATE_FORMAT = withInitial(SimpleDateFormat::new); + private static final ThreadLocal LOCAL_DATE_FORMAT = withInitial(SimpleDateFormat::new); - @NotNull - private static final ThreadLocal LOCAL_DATE = withInitial(Date::new); + private static final ThreadLocal LOCAL_DATE = withInitial(Date::new); - /** - * The OS manager. - */ - @NotNull - private final OperatingSystemMXBean operatingSystemMXBean; + /** + * The OS manager. + */ + private final OperatingSystemMXBean operatingSystemMXBean; - /** - * The runtime manager. - */ - @NotNull - private final RuntimeMXBean runtimeMXBean; + /** + * The runtime manager. + */ + private final RuntimeMXBean runtimeMXBean; - /** - * Instantiates a new Runtime monitoring. - */ - public RuntimeMonitoring() { - this.operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); - this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); - } + /** + * Instantiates a new Runtime monitoring. + */ + public RuntimeMonitoring() { + this.operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); + this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); + } - @Override - public String toString() { + @Override + public String toString() { - final Date date = LOCAL_DATE.get(); - date.setTime(runtimeMXBean.getStartTime()); + Date date = LOCAL_DATE.get(); + date.setTime(runtimeMXBean.getStartTime()); - final SimpleDateFormat format = LOCAL_DATE_FORMAT.get(); + SimpleDateFormat format = LOCAL_DATE_FORMAT.get(); + StringBuilder builder = new StringBuilder(); + builder + .append("Operating System:") + .append('\n'); + builder + .append(" ") + .append("OS Name: ") + .append(operatingSystemMXBean.getName()) + .append('\n'); + builder + .append(" ") + .append("OS Arch: ") + .append(operatingSystemMXBean.getArch()) + .append('\n'); + builder + .append(" ") + .append("OS Version: ") + .append(operatingSystemMXBean.getVersion()) + .append('\n'); + builder + .append(" ") + .append("OS System Load: ") + .append(operatingSystemMXBean.getSystemLoadAverage()) + .append('\n'); + builder + .append(" ") + .append("OS Available Processors: ") + .append(operatingSystemMXBean.getAvailableProcessors()) + .append('\n'); + builder + .append("Runtime:") + .append('\n'); + builder + .append(" ") + .append("JVM StartTime: ") + .append(format.format(date)) + .append('\n'); + builder + .append(" ") + .append("JVM UpTime: ") + .append(runtimeMXBean.getUptime() / 1000 / 60) + .append(" minuts") + .append('\n'); + builder + .append(" ") + .append("JVM Name: ") + .append(runtimeMXBean.getVmName()) + .append('\n'); + builder + .append(" ") + .append("JVM Vendor: ") + .append(runtimeMXBean.getVmVendor()) + .append('\n'); + builder + .append(" ") + .append("JVM Version: ") + .append(runtimeMXBean.getVmVersion()) + .append('\n'); + builder + .append(" ") + .append("JVM Java Version: ") + .append(runtimeMXBean.getSpecVersion()); - final StringBuilder builder = new StringBuilder(); - builder.append("Operating System:").append('\n'); - builder.append(" ").append("OS Name: ").append(operatingSystemMXBean.getName()).append('\n'); - builder.append(" ").append("OS Arch: ").append(operatingSystemMXBean.getArch()).append('\n'); - builder.append(" ").append("OS Version: ").append(operatingSystemMXBean.getVersion()).append('\n'); - builder.append(" ").append("OS System Load: ").append(operatingSystemMXBean.getSystemLoadAverage()).append('\n'); - builder.append(" ").append("OS Available Processors: ").append(operatingSystemMXBean.getAvailableProcessors()).append('\n'); - builder.append("Runtime:").append('\n'); - builder.append(" ").append("JVM StartTime: ").append(format.format(date)).append('\n'); - builder.append(" ").append("JVM UpTime: ").append(runtimeMXBean.getUptime() / 1000 / 60).append(" minuts").append('\n'); - builder.append(" ").append("JVM Name: ").append(runtimeMXBean.getVmName()).append('\n'); - builder.append(" ").append("JVM Vendor: ").append(runtimeMXBean.getVmVendor()).append('\n'); - builder.append(" ").append("JVM Version: ").append(runtimeMXBean.getVmVersion()).append('\n'); - builder.append(" ").append("JVM Java Version: ").append(runtimeMXBean.getSpecVersion()); - - return builder.toString(); - } + return builder.toString(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/ConfigurablePluginSystem.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/ConfigurablePluginSystem.java index 1999270f..b661f9d0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/ConfigurablePluginSystem.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/ConfigurablePluginSystem.java @@ -3,80 +3,81 @@ import java.nio.file.Path; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface to implement configurable plugin system. * * @author JavaSaBr */ +@NullMarked public interface ConfigurablePluginSystem extends PluginSystem { - /** - * Configure the path to installed plugins. - * - * @param installationPluginsPath the path. - */ - void configureInstallationPluginsPath(@NotNull Path installationPluginsPath); + /** + * Configure the path to installed plugins. + * + * @param installationPluginsPath the path. + */ + void configureInstallationPluginsPath(Path installationPluginsPath); - /** - * Configure the path to embedded plugins. - * - * @param embeddedPluginPath the path. - */ - void configureEmbeddedPluginPath(@NotNull Path embeddedPluginPath); + /** + * Configure the path to embedded plugins. + * + * @param embeddedPluginPath the path. + */ + void configureEmbeddedPluginPath(Path embeddedPluginPath); - /** - * Set the app version. - * - * @param version the app version. - */ - void setAppVersion(@Nullable Version version); + /** + * Set the app version. + * + * @param version the app version. + */ + void setAppVersion(@Nullable Version version); - /** - * Preload all plugins. - * - * @return the async result of pre-loaded plugin system. - */ - @NotNull CompletableFuture preLoad(); + /** + * Preload all plugins. + * + * @return the async result of pre-loaded plugin system. + */ + CompletableFuture preLoad(); - /** - * Preload all plugins. - * - * @param executor the executor. - * @return the async result of pre-loaded plugin system. - */ - @NotNull CompletableFuture preLoad(@NotNull Executor executor); + /** + * Preload all plugins. + * + * @param executor the executor. + * @return the async result of pre-loaded plugin system. + */ + CompletableFuture preLoad(Executor executor); - /** - * Initialize all plugins. - * - * @return the async result of initialized plugin system. - */ - @NotNull CompletableFuture initialize(); + /** + * Initialize all plugins. + * + * @return the async result of initialized plugin system. + */ + CompletableFuture initialize(); - /** - * Initialize all plugins. - * - * @param executor the executor. - * @return the async result of initialized plugin system. - */ - @NotNull CompletableFuture initialize(@NotNull Executor executor); + /** + * Initialize all plugins. + * + * @param executor the executor. + * @return the async result of initialized plugin system. + */ + CompletableFuture initialize(Executor executor); - /** - * Install a new plugin. - * - * @param file the path to the plugin. - * @param needInitialize true if need to initialize the plugin. - * @return the installed plugin or null. - */ - @Nullable Plugin installPlugin(@NotNull Path file, boolean needInitialize); + /** + * Install a new plugin. + * + * @param file the path to the plugin. + * @param needInitialize true if need to initialize the plugin. + * @return the installed plugin or null. + */ + @Nullable Plugin installPlugin(Path file, boolean needInitialize); - /** - * Remove the plugin. - * - * @param plugin the plugin. - */ - void removePlugin(@NotNull Plugin plugin); + /** + * Remove the plugin. + * + * @param plugin the plugin. + */ + void removePlugin(Plugin plugin); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/Plugin.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/Plugin.java index c51298f4..1df8cf44 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/Plugin.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/Plugin.java @@ -1,77 +1,78 @@ package javasabr.rlib.common.plugin; import javasabr.rlib.common.plugin.annotation.PluginDescription; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a plugin. * * @author JavaSaBr */ +@NullMarked public interface Plugin { - /** - * Get a class loader of this plugin. - * - * @return the class loader. - */ - @NotNull ClassLoader getClassLoader(); + /** + * Get a class loader of this plugin. + * + * @return the class loader. + */ + ClassLoader getClassLoader(); - /** - * Get the ID of this plugin. - * - * @return the plugin id. - */ - default @NotNull String getId() { - return getClass() - .getAnnotation(PluginDescription.class) - .id(); - } + /** + * Get the ID of this plugin. + * + * @return the plugin id. + */ + default String getId() { + return getClass() + .getAnnotation(PluginDescription.class) + .id(); + } - /** - * Get the version of this plugin. - * - * @return the plugin version. - */ - default @NotNull Version getVersion() { - return new Version(getClass() - .getAnnotation(PluginDescription.class) - .version()); - } + /** + * Get the version of this plugin. + * + * @return the plugin version. + */ + default Version getVersion() { + return new Version(getClass() + .getAnnotation(PluginDescription.class) + .version()); + } - /** - * Gets a name of this plugin. - * - * @return the name of this plugin. - */ - default @NotNull String getName() { - return getClass() - .getAnnotation(PluginDescription.class) - .name(); - } + /** + * Gets a name of this plugin. + * + * @return the name of this plugin. + */ + default String getName() { + return getClass() + .getAnnotation(PluginDescription.class) + .name(); + } - /** - * Gets a description of this plugin. - * - * @return the description of this plugin. - */ - default @NotNull String getDescription() { - return getClass() - .getAnnotation(PluginDescription.class) - .description(); - } + /** + * Gets a description of this plugin. + * + * @return the description of this plugin. + */ + default String getDescription() { + return getClass() + .getAnnotation(PluginDescription.class) + .description(); + } - /** - * Return true if this plugin is embedded. - * - * @return true if this plugin is embedded. - */ - boolean isEmbedded(); + /** + * Return true if this plugin is embedded. + * + * @return true if this plugin is embedded. + */ + boolean isEmbedded(); - /** - * Initialize this plugin. - * - * @param pluginSystem the plugin system. - */ - void initialize(@NotNull PluginSystem pluginSystem); + /** + * Initialize this plugin. + * + * @param pluginSystem the plugin system. + */ + void initialize(PluginSystem pluginSystem); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginContainer.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginContainer.java index db63fced..7e1086a1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginContainer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginContainer.java @@ -4,158 +4,150 @@ import java.nio.file.Path; import javasabr.rlib.common.classpath.ClassPathScanner; import javasabr.rlib.common.plugin.annotation.PluginDescription; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of a plugin container. * * @author JavaSaBr */ +@NullMarked public class PluginContainer { - /** - * The plugin class. - */ - @NotNull - private final Class pluginClass; - - /** - * The class loader of this class. - */ - @NotNull - private final URLClassLoader classLoader; - - /** - * The classpath scanner of this plugin. - */ - @NotNull - private final ClassPathScanner scanner; - - /** - * The path to a plugin folder. - */ - @NotNull - private final Path path; - - /** - * The plugin id. - */ - @NotNull - private final String id; - - /** - * The name. - */ - @NotNull - private final String name; - - /** - * The description. - */ - @NotNull - private final String description; - - /** - * The version. - */ - @NotNull - private final Version version; - - /** - * The flag of that this container is of an embedded plugin. - */ - private final boolean embedded; - - public PluginContainer( - @NotNull Class pluginClass, - @NotNull URLClassLoader classLoader, - @NotNull ClassPathScanner scanner, - @NotNull Path path, - boolean embedded - ) { - final PluginDescription description = pluginClass.getAnnotation(PluginDescription.class); - this.pluginClass = pluginClass; - this.classLoader = classLoader; - this.scanner = scanner; - this.path = path; - this.embedded = embedded; - this.id = description.id(); - this.name = description.name(); - this.version = new Version(description.version()); - this.description = description.description(); - } - - public @NotNull Class getPluginClass() { - return pluginClass; - } - - /** - * Gets the ID of this plugin. - * - * @return the ID. - */ - public @NotNull String getId() { - return id; - } - - /** - * Get the version of this plugin. - * - * @return the plugin version. - */ - public @NotNull Version getVersion() { - return version; - } - - /** - * Gets a name of this plugin. - * - * @return the name of this plugin. - */ - public @NotNull String getName() { - return name; - } - - /** - * Gets a description of this plugin. - * - * @return the description of this plugin. - */ - public @NotNull String getDescription() { - return description; - } - - /** - * @return true if this container is of an embedded plugin. - */ - public boolean isEmbedded() { - return embedded; - } - - /** - * Get the scanner of this plugin. - * - * @return the scanner. - */ - public @NotNull ClassPathScanner getScanner() { - return scanner; - } - - /** - * Get the class loader of this plugin. - * - * @return the class loader. - */ - public @NotNull URLClassLoader getClassLoader() { - return classLoader; - } - - public @NotNull Path getPath() { - return path; - } - - @Override - public String toString() { - return "PluginContainer{" + "pluginClass=" + pluginClass + ", path=" + path + '}'; - } + /** + * The plugin class. + */ + private final Class pluginClass; + + /** + * The class loader of this class. + */ + private final URLClassLoader classLoader; + + /** + * The classpath scanner of this plugin. + */ + private final ClassPathScanner scanner; + + /** + * The path to a plugin folder. + */ + private final Path path; + + /** + * The plugin id. + */ + private final String id; + + /** + * The name. + */ + private final String name; + + /** + * The description. + */ + private final String description; + + /** + * The version. + */ + private final Version version; + + /** + * The flag of that this container is of an embedded plugin. + */ + private final boolean embedded; + + public PluginContainer( + Class pluginClass, + URLClassLoader classLoader, + ClassPathScanner scanner, + Path path, + boolean embedded) { + PluginDescription description = pluginClass.getAnnotation(PluginDescription.class); + this.pluginClass = pluginClass; + this.classLoader = classLoader; + this.scanner = scanner; + this.path = path; + this.embedded = embedded; + this.id = description.id(); + this.name = description.name(); + this.version = new Version(description.version()); + this.description = description.description(); + } + + public Class getPluginClass() { + return pluginClass; + } + + /** + * Gets the ID of this plugin. + * + * @return the ID. + */ + public String getId() { + return id; + } + + /** + * Get the version of this plugin. + * + * @return the plugin version. + */ + public Version getVersion() { + return version; + } + + /** + * Gets a name of this plugin. + * + * @return the name of this plugin. + */ + public String getName() { + return name; + } + + /** + * Gets a description of this plugin. + * + * @return the description of this plugin. + */ + public String getDescription() { + return description; + } + + /** + * @return true if this container is of an embedded plugin. + */ + public boolean isEmbedded() { + return embedded; + } + + /** + * Get the scanner of this plugin. + * + * @return the scanner. + */ + public ClassPathScanner getScanner() { + return scanner; + } + + /** + * Get the class loader of this plugin. + * + * @return the class loader. + */ + public URLClassLoader getClassLoader() { + return classLoader; + } + + public Path getPath() { + return path; + } + + @Override + public String toString() { + return "PluginContainer{" + "pluginClass=" + pluginClass + ", path=" + path + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginSystem.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginSystem.java index 57d3658b..8c20b009 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginSystem.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/PluginSystem.java @@ -2,63 +2,65 @@ import java.util.Optional; import javasabr.rlib.common.util.array.Array; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface to implement a plugin system. * * @author JavaSaBr */ +@NullMarked public interface PluginSystem { - /** - * Get all available plugin containers. - * - * @return the list of all available plugin containers. - */ - @NotNull Array getPluginContainers(); + /** + * Get all available plugin containers. + * + * @return the list of all available plugin containers. + */ + Array getPluginContainers(); - /** - * Get a plugin container by the plugin id. - * - * @param id the plugin id. - * @return the container or null. - */ - @Nullable PluginContainer getPluginContainer(@NotNull String id); + /** + * Get a plugin container by the plugin id. + * + * @param id the plugin id. + * @return the container or null. + */ + @Nullable + PluginContainer getPluginContainer(String id); - /** - * Get a plugin container by the plugin id. - * - * @param id the plugin id. - * @return the optional value of container. - */ - default @NotNull Optional getPluginContainerOpt(@NotNull String id) { - return Optional.ofNullable(getPluginContainer(id)); - } + /** + * Get a plugin container by the plugin id. + * + * @param id the plugin id. + * @return the optional value of container. + */ + default Optional getPluginContainerOpt(String id) { + return Optional.ofNullable(getPluginContainer(id)); + } - /** - * Get all available plugins. - * - * @return the list of all available plugins. - */ - @NotNull Array getPlugins(); + /** + * Get all available plugins. + * + * @return the list of all available plugins. + */ + Array getPlugins(); - /** - * Get a plugin by the plugin id. - * - * @param id the plugin id. - * @return the plugin or null. - */ - @Nullable Plugin getPlugin(@NotNull String id); + /** + * Get a plugin by the plugin id. + * + * @param id the plugin id. + * @return the plugin or null. + */ + @Nullable Plugin getPlugin(String id); - /** - * Get a plugin by the plugin id. - * - * @param id the plugin id. - * @return the optional value of a plugin. - */ - default @NotNull Optional getPluginOpt(@NotNull String id) { - return Optional.ofNullable(getPlugin(id)); - } + /** + * Get a plugin by the plugin id. + * + * @param id the plugin id. + * @return the optional value of a plugin. + */ + default Optional getPluginOpt(String id) { + return Optional.ofNullable(getPlugin(id)); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/Version.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/Version.java index 1459e4e8..6a911846 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/Version.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/Version.java @@ -4,54 +4,54 @@ import java.util.stream.Stream; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The class to present a version. * * @author JavaSaBr */ +@NullMarked public class Version implements Comparable { - /** - * The version segments. - */ - @NotNull - private final int[] segments; - - public Version(@NotNull String version) { - this.segments = parseSegments(version); + /** + * The version segments. + */ + private final int[] segments; + + public Version(String version) { + this.segments = parseSegments(version); + } + + private int[] parseSegments(String stringVersion) { + return Stream + .of(stringVersion.split("\\.")) + .mapToInt(Integer::parseInt) + .toArray(); + } + + @Override + public int compareTo(Version other) { + + int[] otherSegments = other.segments; + + for (int i = 0, min = min(segments.length, otherSegments.length); i < min; i++) { + if (segments[i] < otherSegments[i]) { + return -1; + } else if (segments[i] > otherSegments[i]) { + return 1; + } } - @NotNull - private int[] parseSegments(@NotNull String stringVersion) { - return Stream.of(stringVersion.split("\\.")) - .mapToInt(Integer::parseInt) - .toArray(); + if (otherSegments.length == segments.length) { + return 0; } - @Override - public int compareTo(@NotNull Version other) { - - int[] otherSegments = other.segments; - - for (int i = 0, min = min(segments.length, otherSegments.length); i < min; i++) { - if (segments[i] < otherSegments[i]) { - return -1; - } else if (segments[i] > otherSegments[i]) { - return 1; - } - } - - if (otherSegments.length == segments.length) { - return 0; - } + return otherSegments.length - segments.length; + } - return otherSegments.length - segments.length; - } - - @Override - public String toString() { - return ArrayUtils.toString(segments, ".", false, false); - } + @Override + public String toString() { + return ArrayUtils.toString(segments, ".", false, false); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java index cd98eef5..669dcffb 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java @@ -6,56 +6,58 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The annotation to describe a plugin. * * @author JavaSaBr */ +@NullMarked @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE) public @interface PluginDescription { - /** - * Get the plugin id. - * - * @return the plugin id. - */ - @NotNull String id() default "unknown"; - - /** - * Get dependencies of this plugin. - * - * @return dependencies of this plugin. - */ - @NotNull String[] dependences() default {}; - - /** - * Get the plugin version. - * - * @return the plugin version. - */ - @NotNull String version() default "0.1.0"; - - /** - * Get the min version of application. - * - * @return the min version of application. - */ - @NotNull String minAppVersion() default "0.0.0"; - - /** - * Get the plugin name. - * - * @return the plugin name. - */ - @NotNull String name() default "no name"; - - /** - * Get the plugin description. - * - * @return the plugin description. - */ - @NotNull String description() default "no description"; + /** + * Get the plugin id. + * + * @return the plugin id. + */ + String id() default "unknown"; + + /** + * Get dependencies of this plugin. + * + * @return dependencies of this plugin. + */ + String[] dependences() default {}; + + /** + * Get the plugin version. + * + * @return the plugin version. + */ + String version() default "0.1.0"; + + /** + * Get the min version of application. + * + * @return the min version of application. + */ + String minAppVersion() default "0.0.0"; + + /** + * Get the plugin name. + * + * @return the plugin name. + */ + String name() default "no name"; + + /** + * Get the plugin description. + * + * @return the plugin description. + */ + String description() default "no description"; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/InitializePluginException.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/InitializePluginException.java index 6c68360a..ada8e22d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/InitializePluginException.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/InitializePluginException.java @@ -1,38 +1,34 @@ package javasabr.rlib.common.plugin.exception; import java.nio.file.Path; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The exception about problems with initializing plugins. * * @author JavaSaBr */ +@NullMarked public class InitializePluginException extends PluginException { - @NotNull - private final Path path; + private final Path path; - public InitializePluginException(@NotNull String message, @NotNull Path path) { - super(message); - this.path = path; - } + public InitializePluginException(String message, Path path) { + super(message); + this.path = path; + } - public InitializePluginException( - @NotNull String message, - @NotNull Path path, - @NotNull Throwable e - ) { - super(message, e); - this.path = path; - } + public InitializePluginException(String message, Path path, Throwable e) { + super(message, e); + this.path = path; + } - /** - * Get the path of the plugin. - * - * @return the path of the plugin. - */ - public @NotNull Path getPath() { - return path; - } + /** + * Get the path of the plugin. + * + * @return the path of the plugin. + */ + public Path getPath() { + return path; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java index 7784f4eb..736c3813 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java @@ -1,19 +1,21 @@ package javasabr.rlib.common.plugin.exception; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The base implementation of a plugin exception. * * @author JavaSaBr */ +@NullMarked public class PluginException extends RuntimeException { - public PluginException(@NotNull String message) { - super(message); - } + public PluginException(String message) { + super(message); + } - public PluginException(@NotNull String message, @NotNull Throwable cause) { - super(message, cause); - } + public PluginException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java index 5f7e465f..be484425 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java @@ -2,28 +2,29 @@ import java.nio.file.Path; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The exception about problems with pre-loading plugins. * * @author JavaSaBr */ +@NullMarked public class PreloadPluginException extends PluginException { - @NotNull - private final Path path; + private final Path path; - public PreloadPluginException(@NotNull String message, @NotNull Path path) { - super(message); - this.path = path; - } + public PreloadPluginException(String message, Path path) { + super(message); + this.path = path; + } - /** - * Get the path of the plugin. - * - * @return the path of the plugin. - */ - public @NotNull Path getPath() { - return path; - } + /** + * Get the path of the plugin. + * + * @return the path of the plugin. + */ + public Path getPath() { + return path; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPoint.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPoint.java index 4dcedaa9..167fc150 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPoint.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPoint.java @@ -16,378 +16,375 @@ import java.util.stream.StreamSupport; import javasabr.rlib.common.function.TriplePredicate; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class to present an extension point. * * @author JavaSaBr */ +@NullMarked public class ExtensionPoint implements Iterable { - private static class State { - - /** - * The read only list of extensions. - */ - @NotNull - private final List extensions; - - /** - * The array for fast access. - */ - @NotNull - private final Object[] array; - - public State() { - this.extensions = Collections.emptyList(); - this.array = ArrayUtils.EMPTY_OBJECT_ARRAY; - } - - public State(@NotNull List extensions, @NotNull Object[] array) { - this.extensions = extensions; - this.array = array; - } - - /** - * Append the extension to the current state as new state. - * - * @param extension the extension. - * @return the new state. - */ - public @NotNull State append(@NotNull T extension) { - - List result = new ArrayList<>(extensions); - result.add(extension); - - boolean canBeSorted = result.stream() - .allMatch(Comparable.class::isInstance); - - if (canBeSorted) { - result.sort((first, second) -> ((Comparable) first).compareTo(second)); - } - - List extensions = Collections.unmodifiableList(result); - Object[] array = result.toArray(); - - return new State<>(extensions, array); - } - - /** - * Append the additional extensions to the current state as new state. - * - * @param additionalExtensions the additional extension. - * @return the new state. - */ - public @NotNull State append(@NotNull T[] additionalExtensions) { - - List result = new ArrayList<>(extensions); - result.addAll(Arrays.asList(additionalExtensions)); - - boolean canBeSorted = result.stream() - .allMatch(Comparable.class::isInstance); - - if (canBeSorted) { - result.sort((first, second) -> ((Comparable) first).compareTo(second)); - } - - List extensions = Collections.unmodifiableList(result); - Object[] array = result.toArray(); - - return new State<>(extensions, array); - } - } + @NullMarked + private static class State { /** - * The reference to the current state. + * The read only list of extensions. */ - @NotNull - private final AtomicReference> state; - - public ExtensionPoint() { - this.state = new AtomicReference<>(new State<>()); - } + private final List extensions; /** - * Register a new extension. - * - * @param extension the new extension. - * @return this point. + * The array for fast access. */ - public ExtensionPoint register(@NotNull T extension) { + private final Object[] array; - State currentState = state.get(); - State newState = currentState.append(extension); - - while (!state.compareAndSet(currentState, newState)) { - currentState = state.get(); - newState = currentState.append(extension); - } - - return this; + public State() { + this.extensions = Collections.emptyList(); + this.array = ArrayUtils.EMPTY_OBJECT_ARRAY; } - /** - * Register the new extensions. - * - * @param extensions the new extensions. - * @return this point. - */ - public ExtensionPoint register(@NotNull T... extensions) { - - State currentState = state.get(); - State newState = currentState.append(extensions); - - while (!state.compareAndSet(currentState, newState)) { - currentState = state.get(); - newState = currentState.append(extensions); - } - - return this; - } - - /** - * Get all registered extensions. - * - * @return the all registered extensions. - */ - public @NotNull List getExtensions() { - return state.get().extensions; + public State(List extensions, Object[] array) { + this.extensions = extensions; + this.array = array; } /** - * Handle each extension. + * Append the extension to the current state as new state. * - * @param consumer the consumer. + * @param extension the extension. + * @return the new state. */ - @Override - public void forEach(@NotNull Consumer consumer) { + public State append(T extension) { - Object[] array = state.get().array; + List result = new ArrayList<>(extensions); + result.add(extension); - for (Object obj : array) { - consumer.accept((T) obj); - } - } + boolean canBeSorted = result + .stream() + .allMatch(Comparable.class::isInstance); - /** - * Handle each extension. - * - * @param first the first argument. - * @param consumer the consumer. - * @param the argument's type. - */ - public void forEach(@NotNull F first, @NotNull BiConsumer consumer) { + if (canBeSorted) { + result.sort((first, second) -> ((Comparable) first).compareTo(second)); + } - Object[] array = state.get().array; + List extensions = Collections.unmodifiableList(result); + Object[] array = result.toArray(); - for (Object obj : array) { - consumer.accept((T) obj, first); - } + return new State<>(extensions, array); } /** - * Find an extension using the condition. + * Append the additional extensions to the current state as new state. * - * @param predicate the condition. - * @return the found extension or null. + * @param additionalExtensions the additional extension. + * @return the new state. */ - public @Nullable T findAny(@NotNull Predicate predicate) { + public State append(T[] additionalExtensions) { - for (Object element : state.get().array) { - if (predicate.test((T) element)) { - return (T) element; - } - } + List result = new ArrayList<>(extensions); + result.addAll(Arrays.asList(additionalExtensions)); - return null; - } + boolean canBeSorted = result + .stream() + .allMatch(Comparable.class::isInstance); - /** - * Find an extension using the condition. - * - * @param the argument's type. - * @param argument the argument. - * @param predicate the condition. - * @return the found extension or null. - */ - public @Nullable T findAny(@Nullable F argument, @NotNull BiPredicate predicate) { + if (canBeSorted) { + result.sort((first, second) -> ((Comparable) first).compareTo(second)); + } - for (Object element : state.get().array) { - if (predicate.test((T) element, argument)) { - return (T) element; - } - } + List extensions = Collections.unmodifiableList(result); + Object[] array = result.toArray(); - return null; + return new State<>(extensions, array); } - - /** - * Return true if there is at least an extension for the condition. - * - * @param the argument's type. - * @param argument the argument. - * @param predicate the condition. - * @return true if there is at least an extension for the condition. - */ - public boolean anyMatch(@Nullable F argument, @NotNull BiPredicate predicate) { - return findAny(argument, predicate) != null; + } + + /** + * The reference to the current state. + */ + private final AtomicReference> state; + + public ExtensionPoint() { + this.state = new AtomicReference<>(new State<>()); + } + + /** + * Register a new extension. + * + * @param extension the new extension. + * @return this point. + */ + public ExtensionPoint register(T extension) { + + State currentState = state.get(); + State newState = currentState.append(extension); + + while (!state.compareAndSet(currentState, newState)) { + currentState = state.get(); + newState = currentState.append(extension); } - /** - * Find an extension using the inverted condition. - * - * @param the argument's type. - * @param argument the argument. - * @param predicate the condition. - * @return the found extension or null. - */ - public @Nullable T findAnyNot(@Nullable F argument, @NotNull BiPredicate predicate) { + return this; + } - for (Object element : state.get().array) { - if (!predicate.test((T) element, argument)) { - return (T) element; - } - } + /** + * Register the new extensions. + * + * @param extensions the new extensions. + * @return this point. + */ + @SafeVarargs + public final ExtensionPoint register(T... extensions) { - return null; - } + State currentState = state.get(); + State newState = currentState.append(extensions); - /** - * Return true if there is at least an extension for the inverted condition. - * - * @param the argument's type. - * @param argument the argument. - * @param predicate the condition. - * @return true if there is at least an extension for the inverted condition. - */ - public boolean anyMatchNot(@Nullable F argument, @NotNull BiPredicate predicate) { - return findAnyNot(argument, predicate) != null; + while (!state.compareAndSet(currentState, newState)) { + currentState = state.get(); + newState = currentState.append(extensions); } - /** - * Find an extension using the condition. - * - * @param the first argument's type. - * @param the second argument's type. - * @param first the first argument. - * @param second the second argument. - * @param predicate the condition. - * @return the found extension or null. - */ - public @Nullable T findAny( - @Nullable F first, - @Nullable S second, - @NotNull TriplePredicate predicate - ) { - - for (Object element : state.get().array) { - if (predicate.test((T) element, first, second)) { - return (T) element; - } - } - - return null; + return this; + } + + /** + * Get all registered extensions. + * + * @return the all registered extensions. + */ + public List getExtensions() { + return state.get().extensions; + } + + /** + * Handle each extension. + * + * @param consumer the consumer. + */ + @Override + public void forEach(Consumer consumer) { + + Object[] array = state.get().array; + + for (Object obj : array) { + consumer.accept((T) obj); } + } - /** - * Return true if there is at least an extension for the condition. - * - * @param the first argument's type. - * @param the second argument's type. - * @param first the first argument. - * @param second the second argument. - * @param predicate the condition. - * @return true if there is at least an extension for the condition. - */ - public boolean anyMatch( - @Nullable F first, - @Nullable S second, - @NotNull TriplePredicate predicate - ) { - return findAny(first, second, predicate) != null; - } + /** + * Handle each extension. + * + * @param first the first argument. + * @param consumer the consumer. + * @param the argument's type. + */ + public void forEach(F first, BiConsumer consumer) { + Object[] array = state.get().array; - /** - * Find an extension using the inverted condition. - * - * @param the first argument's type. - * @param the second argument's type. - * @param first the first argument. - * @param second the second argument. - * @param predicate the condition. - * @return the found extension or null. - */ - public @Nullable T findAnyNot( - @Nullable F first, - @Nullable S second, - @NotNull TriplePredicate predicate - ) { - - for (Object element : state.get().array) { - if (!predicate.test((T) element, first, second)) { - return (T) element; - } - } - - return null; + for (Object obj : array) { + consumer.accept((T) obj, first); } - - /** - * Return true if there is at least an extension for the inverted condition. - * - * @param the first argument's type. - * @param the second argument's type. - * @param first the first argument. - * @param second the second argument. - * @param predicate the condition. - * @return the found extension or null. - */ - public boolean anyMatchNot( - @Nullable F first, - @Nullable S second, - @NotNull TriplePredicate predicate - ) { - return findAnyNot(first, second, predicate) != null; + } + + /** + * Find an extension using the condition. + * + * @param predicate the condition. + * @return the found extension or null. + */ + public @Nullable T findAny(Predicate predicate) { + + for (Object element : state.get().array) { + if (predicate.test((T) element)) { + return (T) element; + } } - /** - * Search an extension using the condition. - * - * @param the argument's type. - * @param argument the argument. - * @param predicate the condition. - * @return the found extension or null. - */ - public @Nullable T anyMatchR(@Nullable F argument, @NotNull BiPredicate predicate) { - - for (Object element : state.get().array) { - if (predicate.test(argument, (T) element)) { - return (T) element; - } - } + return null; + } + + /** + * Find an extension using the condition. + * + * @param the argument's type. + * @param argument the argument. + * @param predicate the condition. + * @return the found extension or null. + */ + public @Nullable T findAny(@Nullable F argument, BiPredicate predicate) { + + for (Object element : state.get().array) { + if (predicate.test((T) element, argument)) { + return (T) element; + } + } - return null; + return null; + } + + /** + * Return true if there is at least an extension for the condition. + * + * @param the argument's type. + * @param argument the argument. + * @param predicate the condition. + * @return true if there is at least an extension for the condition. + */ + public boolean anyMatch(@Nullable F argument, BiPredicate predicate) { + return findAny(argument, predicate) != null; + } + + /** + * Find an extension using the inverted condition. + * + * @param the argument's type. + * @param argument the argument. + * @param predicate the condition. + * @return the found extension or null. + */ + public @Nullable T findAnyNot(@Nullable F argument, BiPredicate predicate) { + + for (Object element : state.get().array) { + if (!predicate.test((T) element, argument)) { + return (T) element; + } } - @Override - public @NotNull Iterator iterator() { - return state.get().extensions.iterator(); + return null; + } + + /** + * Return true if there is at least an extension for the inverted condition. + * + * @param the argument's type. + * @param argument the argument. + * @param predicate the condition. + * @return true if there is at least an extension for the inverted condition. + */ + public boolean anyMatchNot(@Nullable F argument, BiPredicate predicate) { + return findAnyNot(argument, predicate) != null; + } + + /** + * Find an extension using the condition. + * + * @param the first argument's type. + * @param the second argument's type. + * @param first the first argument. + * @param second the second argument. + * @param predicate the condition. + * @return the found extension or null. + */ + public @Nullable T findAny( + @Nullable F first, + @Nullable S second, + TriplePredicate predicate) { + + for (Object element : state.get().array) { + if (predicate.test((T) element, first, second)) { + return (T) element; + } } - /** - * Get a stream of extensions. - * - * @return the stream of extensions. - */ - public @NotNull Stream stream() { - return StreamSupport.stream(spliterator(), false); + return null; + } + + /** + * Return true if there is at least an extension for the condition. + * + * @param the first argument's type. + * @param the second argument's type. + * @param first the first argument. + * @param second the second argument. + * @param predicate the condition. + * @return true if there is at least an extension for the condition. + */ + public boolean anyMatch( + @Nullable F first, + @Nullable S second, + TriplePredicate predicate) { + return findAny(first, second, predicate) != null; + } + + /** + * Find an extension using the inverted condition. + * + * @param the first argument's type. + * @param the second argument's type. + * @param first the first argument. + * @param second the second argument. + * @param predicate the condition. + * @return the found extension or null. + */ + public @Nullable T findAnyNot( + @Nullable F first, + @Nullable S second, + TriplePredicate predicate) { + + for (Object element : state.get().array) { + if (!predicate.test((T) element, first, second)) { + return (T) element; + } } - @Override - public @NotNull Spliterator spliterator() { - return Spliterators.spliterator(state.get().array, 0); + return null; + } + + /** + * Return true if there is at least an extension for the inverted condition. + * + * @param the first argument's type. + * @param the second argument's type. + * @param first the first argument. + * @param second the second argument. + * @param predicate the condition. + * @return the found extension or null. + */ + public boolean anyMatchNot( + @Nullable F first, + @Nullable S second, + TriplePredicate predicate) { + return findAnyNot(first, second, predicate) != null; + } + + /** + * Search an extension using the condition. + * + * @param the argument's type. + * @param argument the argument. + * @param predicate the condition. + * @return the found extension or null. + */ + public @Nullable T anyMatchR(@Nullable F argument, BiPredicate predicate) { + + for (Object element : state.get().array) { + if (predicate.test(argument, (T) element)) { + return (T) element; + } } + + return null; + } + + @Override + public Iterator iterator() { + return state.get().extensions.iterator(); + } + + /** + * Get a stream of extensions. + * + * @return the stream of extensions. + */ + public Stream stream() { + return StreamSupport.stream(spliterator(), false); + } + + @Override + public Spliterator spliterator() { + return Spliterators.spliterator(state.get().array, 0); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPointManager.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPointManager.java index 4e06a1ef..8be10915 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPointManager.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/extension/ExtensionPointManager.java @@ -6,142 +6,139 @@ import javasabr.rlib.common.util.dictionary.ObjectDictionary; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The manager to manage all extension points. * * @author JavaSaBr */ +@NullMarked public class ExtensionPointManager { - private static final Logger LOGGER = LoggerManager.getLogger(ExtensionPointManager.class); - - /** - * Register a new extension point. - * - * @param id the extension id. - * @param the extension's type. - * @return the new extension point. - * @throws IllegalArgumentException if an extension with the id is already exists. - */ - public static @NotNull ExtensionPoint register(@NotNull String id) { - return getInstance().create(id); - } + private static final Logger LOGGER = LoggerManager.getLogger(ExtensionPointManager.class); - private static final ExtensionPointManager INSTANCE = new ExtensionPointManager(); + /** + * Register a new extension point. + * + * @param id the extension id. + * @param the extension's type. + * @return the new extension point. + * @throws IllegalArgumentException if an extension with the id is already exists. + */ + public static ExtensionPoint register(String id) { + return getInstance().create(id); + } - public static @NotNull ExtensionPointManager getInstance() { - return INSTANCE; - } + private static final ExtensionPointManager INSTANCE = new ExtensionPointManager(); - /** - * All created extension points. - */ - private final @NotNull ConcurrentObjectDictionary> extensionPoints; + public static ExtensionPointManager getInstance() { + return INSTANCE; + } - private ExtensionPointManager() { - this.extensionPoints = DictionaryFactory.newConcurrentAtomicObjectDictionary(); - } + /** + * All created extension points. + */ + private final ConcurrentObjectDictionary> extensionPoints; - private @NotNull ExtensionPoint create(@NotNull String id) { + private ExtensionPointManager() { + this.extensionPoints = DictionaryFactory.newConcurrentAtomicObjectDictionary(); + } - long stamp = extensionPoints.writeLock(); - try { + private ExtensionPoint create(String id) { - var exists = extensionPoints.get(id); + long stamp = extensionPoints.writeLock(); + try { - if (exists != null) { - LOGGER.warning("The extension point with the id " + id + " is already registered."); - return ClassUtils.unsafeNNCast(exists); - } + var exists = extensionPoints.get(id); - var extensionPoint = new ExtensionPoint(); + if (exists != null) { + LOGGER.warning("The extension point with the id " + id + " is already registered."); + return ClassUtils.unsafeNNCast(exists); + } - extensionPoints.put(id, extensionPoint); + var extensionPoint = new ExtensionPoint(); - return extensionPoint; + extensionPoints.put(id, extensionPoint); - } finally { - extensionPoints.writeUnlock(stamp); - } - } + return extensionPoint; - /** - * Add the new extension to the extension point. - * - * @param id the extension point's id. - * @param type the extension's type. - * @param extension the new extension. - * @param the extension's type. - * @return this manager. - */ - public @NotNull ExtensionPointManager addExtension( - @NotNull String id, - @NotNull Class type, - @NotNull T extension - ) { - getExtensionPoint(id).register(extension); - return this; + } finally { + extensionPoints.writeUnlock(stamp); } - - /** - * Add the new extension to the extension point. - * - * @param id the extension point's id. - * @param extension the new extension. - * @param the extension's type. - * @return this manager. - */ - public @NotNull ExtensionPointManager addExtension(@NotNull String id, @NotNull T extension) { - getExtensionPoint(id).register(extension); - return this; - } - - /** - * Add the new extensions to the extension point. - * - * @param id the extension point's id. - * @param extensions the new extensions. - * @param the extension's type. - * @return this manager. - */ - public @NotNull ExtensionPointManager addExtension(@NotNull String id, @NotNull T... extensions) { - getExtensionPoint(id).register(extensions); - return this; - } - - /** - * Get or create an extension point. - * - * @param id the id. - * @param type the extension's type. - * @param the extension's type. - * @return the extension point. - */ - public @NotNull ExtensionPoint getExtensionPoint(@NotNull String id, @NotNull Class type) { - return getExtensionPoint(id); + } + + /** + * Add the new extension to the extension point. + * + * @param id the extension point's id. + * @param type the extension's type. + * @param extension the new extension. + * @param the extension's type. + * @return this manager. + */ + public ExtensionPointManager addExtension(String id, Class type, T extension) { + getExtensionPoint(id).register(extension); + return this; + } + + /** + * Add the new extension to the extension point. + * + * @param id the extension point's id. + * @param extension the new extension. + * @param the extension's type. + * @return this manager. + */ + public ExtensionPointManager addExtension(String id, T extension) { + getExtensionPoint(id).register(extension); + return this; + } + + /** + * Add the new extensions to the extension point. + * + * @param id the extension point's id. + * @param extensions the new extensions. + * @param the extension's type. + * @return this manager. + */ + public ExtensionPointManager addExtension(String id, T... extensions) { + getExtensionPoint(id).register(extensions); + return this; + } + + /** + * Get or create an extension point. + * + * @param id the id. + * @param type the extension's type. + * @param the extension's type. + * @return the extension point. + */ + public ExtensionPoint getExtensionPoint(String id, Class type) { + return getExtensionPoint(id); + } + + /** + * Get or create an extension point. + * + * @param id the id. + * @param the extension's type. + * @return the extension point. + */ + public ExtensionPoint getExtensionPoint(String id) { + + var extensionPoint = extensionPoints.getInReadLock(id, ObjectDictionary::get); + + if (extensionPoint != null) { + return ClassUtils.unsafeNNCast(extensionPoint); } - /** - * Get or create an extension point. - * - * @param id the id. - * @param the extension's type. - * @return the extension point. - */ - public @NotNull ExtensionPoint getExtensionPoint(@NotNull String id) { - - var extensionPoint = extensionPoints.getInReadLock(id, ObjectDictionary::get); - - if (extensionPoint != null) { - return ClassUtils.unsafeNNCast(extensionPoint); - } - - try { - return create(id); - } catch (IllegalArgumentException e) { - return getExtensionPoint(id); - } + try { + return create(id); + } catch (IllegalArgumentException e) { + return getExtensionPoint(id); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePlugin.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePlugin.java index 0e716ddc..280927cc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePlugin.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePlugin.java @@ -4,65 +4,65 @@ import javasabr.rlib.common.plugin.PluginContainer; import javasabr.rlib.common.plugin.PluginSystem; import javasabr.rlib.common.plugin.Version; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The base implementation of the {@link Plugin}. * * @author JavaSaBr */ +@NullMarked public class BasePlugin implements Plugin { - /** - * The plugin container. - */ - @NotNull - private final PluginContainer container; + /** + * The plugin container. + */ + private final PluginContainer container; - public BasePlugin(@NotNull final PluginContainer container) { - this.container = container; - } + public BasePlugin(PluginContainer container) { + this.container = container; + } - @Override - public @NotNull ClassLoader getClassLoader() { - return container.getClassLoader(); - } + @Override + public ClassLoader getClassLoader() { + return container.getClassLoader(); + } - @Override - public boolean isEmbedded() { - return container.isEmbedded(); - } + @Override + public boolean isEmbedded() { + return container.isEmbedded(); + } - @Override - public @NotNull String getId() { - return container.getId(); - } + @Override + public String getId() { + return container.getId(); + } - @Override - public @NotNull Version getVersion() { - return container.getVersion(); - } + @Override + public Version getVersion() { + return container.getVersion(); + } - @Override - public @NotNull String getDescription() { - return container.getDescription(); - } + @Override + public String getDescription() { + return container.getDescription(); + } - @Override - public @NotNull String getName() { - return container.getName(); - } + @Override + public String getName() { + return container.getName(); + } - /** - * The container of this plugin. - * - * @return the container. - */ - protected @NotNull PluginContainer getContainer() { - return container; - } + /** + * The container of this plugin. + * + * @return the container. + */ + protected PluginContainer getContainer() { + return container; + } - @Override - public void initialize(@NotNull final PluginSystem pluginSystem) { - } + @Override + public void initialize(PluginSystem pluginSystem) { + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePluginSystem.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePluginSystem.java index 2f3becad..f0976d85 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePluginSystem.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/BasePluginSystem.java @@ -35,565 +35,562 @@ import javasabr.rlib.common.util.dictionary.ObjectDictionary; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of the {@link PluginSystem}. * * @author JavaSaBr */ +@NullMarked public class BasePluginSystem implements ConfigurablePluginSystem { - protected static final Logger LOGGER = LoggerManager.getLogger(BasePluginSystem.class); + protected static final Logger LOGGER = LoggerManager.getLogger(BasePluginSystem.class); - private static class State { + @NullMarked + private static class State { - static final State EMPTY = new State(Array.empty(), ObjectDictionary.empty(), ObjectDictionary.empty()); - - /** - * The list of preload plugin containers. - */ - private final @NotNull Array containers; - - /** - * The result map of plugin containers. - */ - private final @NotNull ObjectDictionary idToContainer; - - /** - * The result map of plugins. - */ - private final @NotNull ObjectDictionary idToPlugin; - - private State( - @NotNull Array containers, - @NotNull ObjectDictionary idToContainer, - @NotNull ObjectDictionary idToPlugin - ) { - this.containers = containers; - this.idToContainer = idToContainer; - this.idToPlugin = idToPlugin; - } - } - - /** - * The base classloader. - */ - private final @NotNull ClassLoader baseLoader; - - /** - * The app version. - */ - private volatile @Nullable Version appVersion; - - /** - * The path to folder with embedded plugins. - */ - private volatile @Nullable Path embeddedPluginsPath; + static final State EMPTY = new State(Array.empty(), ObjectDictionary.empty(), ObjectDictionary.empty()); /** - * The path to folder with installed plugins. + * The list of preload plugin containers. */ - private volatile @Nullable Path installationPluginsPath; + private final Array containers; /** - * The flag of this plugin system was pre-loaded. + * The result map of plugin containers. */ - private final @NotNull AtomicBoolean preLoaded; + private final ObjectDictionary idToContainer; /** - * The flag of this plugin system was initialized. + * The result map of plugins. */ - private final @NotNull AtomicBoolean initialized; - - /** - * The system's state. - */ - private final @NotNull AtomicReference state; - - public BasePluginSystem() { - this(StackWalker.getInstance(RETAIN_CLASS_REFERENCE) - .getCallerClass() - .getClassLoader()); + private final ObjectDictionary idToPlugin; + + private State( + Array containers, + ObjectDictionary idToContainer, + ObjectDictionary idToPlugin) { + this.containers = containers; + this.idToContainer = idToContainer; + this.idToPlugin = idToPlugin; } - - public BasePluginSystem(@NotNull ClassLoader baseLoader) { - this.baseLoader = baseLoader; - this.state = new AtomicReference<>(State.EMPTY); - this.preLoaded = new AtomicBoolean(false); - this.initialized = new AtomicBoolean(false); + } + + /** + * The base classloader. + */ + private final ClassLoader baseLoader; + + /** + * The app version. + */ + private volatile @Nullable Version appVersion; + + /** + * The path to folder with embedded plugins. + */ + private volatile @Nullable Path embeddedPluginsPath; + + /** + * The path to folder with installed plugins. + */ + private volatile @Nullable Path installationPluginsPath; + + /** + * The flag of this plugin system was pre-loaded. + */ + private final AtomicBoolean preLoaded; + + /** + * The flag of this plugin system was initialized. + */ + private final AtomicBoolean initialized; + + /** + * The system's state. + */ + private final AtomicReference state; + + public BasePluginSystem() { + this(StackWalker + .getInstance(RETAIN_CLASS_REFERENCE) + .getCallerClass() + .getClassLoader()); + } + + public BasePluginSystem(ClassLoader baseLoader) { + this.baseLoader = baseLoader; + this.state = new AtomicReference<>(State.EMPTY); + this.preLoaded = new AtomicBoolean(false); + this.initialized = new AtomicBoolean(false); + } + + @Override + public void setAppVersion(@Nullable Version appVersion) { + this.appVersion = appVersion; + } + + @Override + public CompletableFuture preLoad() { + return preLoad(ForkJoinPool.commonPool()); + } + + @Override + public CompletableFuture preLoad(Executor executor) { + + if (!preLoaded.compareAndSet(false, true)) { + throw new PluginException("This system was already pre-loaded."); } - @Override - public void setAppVersion(@Nullable Version appVersion) { - this.appVersion = appVersion; - } + return supplyAsync( + () -> { - @Override - public @NotNull CompletableFuture preLoad() { - return preLoad(ForkJoinPool.commonPool()); - } + var current = state.get(); - @Override - public @NotNull CompletableFuture preLoad(@NotNull Executor executor) { + LOGGER.debug("Start to pre-load all plugins."); - if (!preLoaded.compareAndSet(false, true)) { - throw new PluginException("This system was already pre-loaded."); - } + var futures = Array.optionals( + CompletableFuture.class, + getEmbeddedPluginsPath().map(path -> loadPlugins(path, executor, true)), + getInstallationPluginsPath().map(path -> loadPlugins(path, executor, false))); - return supplyAsync(() -> { + var containers = futures + .stream() + .map(CompletableFuture::join) + .flatMap(Array::stream) + .collect(toArray(PluginContainer.class)); - var current = state.get(); + var idToContainer = containers + .stream() + .collect(toObjectDictionary(PluginContainer::getId, container -> container)); - LOGGER.debug("Start to pre-load all plugins."); + if (state.compareAndSet(current, new State(containers, idToContainer, ObjectDictionary.empty()))) { + LOGGER.debug(containers, arg -> "Pre-loaded: " + arg); + LOGGER.debug("All plugins were pre-loaded."); + return this; + } - var futures = Array.optionals( - CompletableFuture.class, - getEmbeddedPluginsPath().map(path -> loadPlugins(path, executor, true)), - getInstallationPluginsPath().map(path -> loadPlugins(path, executor, false)) - ); - - var containers = futures.stream() - .map(CompletableFuture::join) - .flatMap(Array::stream) - .collect(toArray(PluginContainer.class)); - - var idToContainer = containers.stream() - .collect(toObjectDictionary(PluginContainer::getId, container -> container)); - - if (state.compareAndSet(current, new State(containers, idToContainer, ObjectDictionary.empty()))) { - LOGGER.debug(containers, arg -> "Pre-loaded: " + arg); - LOGGER.debug("All plugins were pre-loaded."); - return this; - } - - return null; + return null; }, executor); - } + } - @Override - public @NotNull CompletableFuture initialize() { - return initialize(ForkJoinPool.commonPool()); - } + @Override + public CompletableFuture initialize() { + return initialize(ForkJoinPool.commonPool()); + } - @Override - public @NotNull CompletableFuture initialize(@NotNull Executor executor) { + @Override + public CompletableFuture initialize(Executor executor) { - if (!initialized.compareAndSet(false, true)) { - throw new PluginException("This system was already initialized."); - } + if (!initialized.compareAndSet(false, true)) { + throw new PluginException("This system was already initialized."); + } - LOGGER.debug("Start to load all plugins."); + LOGGER.debug("Start to load all plugins."); - return supplyAsync(() -> { + return supplyAsync( + () -> { - var current = state.get(); - var plugins = current.containers - .stream() - .map(pluginContainer -> createPluginClass(pluginContainer, executor)) - .map(future -> future.thenApply(this::initializePlugin)) - .map(CompletableFuture::join) - .collect(toObjectDictionary(Plugin::getId, plugin -> plugin)); + var current = state.get(); + var plugins = current.containers + .stream() + .map(pluginContainer -> createPluginClass(pluginContainer, executor)) + .map(future -> future.thenApply(this::initializePlugin)) + .map(CompletableFuture::join) + .collect(toObjectDictionary(Plugin::getId, plugin -> plugin)); - if (state.compareAndSet(current, new State(current.containers, current.idToContainer, plugins))) { - LOGGER.debug("All plugins were initialized."); - return this; - } + if (state.compareAndSet(current, new State(current.containers, current.idToContainer, plugins))) { + LOGGER.debug("All plugins were initialized."); + return this; + } - return null; + return null; }, executor); - } - - /** - * Create a plugin's class. - * - * @param container the plugin's container. - * @param executor the executor. - * @return the plugin's class. - */ - private @NotNull CompletableFuture createPluginClass( - @NotNull PluginContainer container, - @NotNull Executor executor - ) { + } - return supplyAsync(() -> { + /** + * Create a plugin's class. + * + * @param container the plugin's container. + * @param executor the executor. + * @return the plugin's class. + */ + private CompletableFuture createPluginClass(PluginContainer container, Executor executor) { - var pluginClass = container.getPluginClass(); + return supplyAsync( + () -> { - LOGGER.debug(pluginClass, arg -> "Start to create a plugin " + arg); + var pluginClass = container.getPluginClass(); - var constructor = ClassUtils.tryGetConstructor(pluginClass, PluginContainer.class); + LOGGER.debug(pluginClass, arg -> "Start to create a plugin " + arg); - if (constructor == null) { - throw new InitializePluginException( - "Not found base constructor in the class " + pluginClass, - container.getPath() - ); - } + var constructor = ClassUtils.tryGetConstructor(pluginClass, PluginContainer.class); - Plugin plugin; - try { - plugin = ClassUtils.newInstance(constructor, container); - } catch (Throwable exc) { - throw new InitializePluginException( - "Found a problem with creating a plugin " + pluginClass, - container.getPath(), - exc - ); - } - - return plugin; - - }, executor); - } - - /** - * Initialize the plugin. - * - * @param plugin the plugin. - * @return the initialized plugin. - */ - private @NotNull Plugin initializePlugin(@NotNull Plugin plugin) { + if (constructor == null) { + throw new InitializePluginException( + "Not found base constructor in the class " + pluginClass, + container.getPath()); + } - try { - plugin.initialize(this); - } catch (Throwable exc) { - var container = notNull(getPluginContainer(plugin.getId())); + Plugin plugin; + try { + plugin = ClassUtils.newInstance(constructor, container); + } catch (Throwable exc) { throw new InitializePluginException( - "Found a problem with initializing a plugin " + plugin, + "Found a problem with creating a plugin " + pluginClass, container.getPath(), - exc - ); - } - - return plugin; - } + exc); + } - /** - * Load plugins from the directory. - * - * @param path the path to the directory. - * @param executor the executor. - * @param embedded true if this directory with embedded plugins. - * @return the future of the loading plugins. - */ - protected @NotNull CompletableFuture<@NotNull Array> loadPlugins( - @NotNull Path path, - @NotNull Executor executor, - boolean embedded - ) { + return plugin; - LOGGER.debug(path, arg -> "Try to pre-load plugins from the folder " + arg); + }, executor); + } + + /** + * Initialize the plugin. + * + * @param plugin the plugin. + * @return the initialized plugin. + */ + private Plugin initializePlugin(Plugin plugin) { + + try { + plugin.initialize(this); + } catch (Throwable exc) { + var container = notNull(getPluginContainer(plugin.getId())); + throw new InitializePluginException( + "Found a problem with initializing a plugin " + plugin, + container.getPath(), + exc); + } - return supplyAsync(() -> FileUtils.stream(path) + return plugin; + } + + /** + * Load plugins from the directory. + * + * @param path the path to the directory. + * @param executor the executor. + * @param embedded true if this directory with embedded plugins. + * @return the future of the loading plugins. + */ + protected CompletableFuture> loadPlugins(Path path, Executor executor, boolean embedded) { + LOGGER.debug(path, arg -> "Try to pre-load plugins from the folder " + arg); + return supplyAsync( + () -> FileUtils + .stream(path) .filter(Files::isDirectory) .map(directory -> loadPlugin(directory, baseLoader, executor, embedded)) .map(CompletableFuture::join) .filter(Objects::nonNull) .collect(toArray(PluginContainer.class)), executor); - } - - /** - * Load a plugin from the directory. - * - * @param directory the plugin directory. - * @param parentLoader the parent class loader. - * @param executor the executor. - * @param embedded the embedded flag. - * @return the future of loaded plugin container. - */ - protected @NotNull CompletableFuture<@Nullable PluginContainer> loadPlugin( - @NotNull Path directory, - @NotNull ClassLoader parentLoader, - @NotNull Executor executor, - boolean embedded - ) { - return loadPlugin(directory, parentLoader, null, executor, embedded); - } + } + + /** + * Load a plugin from the directory. + * + * @param directory the plugin directory. + * @param parentLoader the parent class loader. + * @param executor the executor. + * @param embedded the embedded flag. + * @return the future of loaded plugin container. + */ + protected CompletableFuture<@Nullable PluginContainer> loadPlugin( + Path directory, + ClassLoader parentLoader, + Executor executor, + boolean embedded) { + return loadPlugin(directory, parentLoader, null, executor, embedded); + } + + /** + * Load a plugin from the directory. + * + * @param directory the plugin directory. + * @param parentLoader the parent class loader. + * @param parents the parent plugins. + * @param executor the executor. + * @param embedded the embedded flag. + * @return the future of loading plugin container. + */ + protected CompletableFuture<@Nullable PluginContainer> loadPlugin( + Path directory, + ClassLoader parentLoader, + PluginContainer @Nullable [] parents, + Executor executor, + boolean embedded) { + return supplyAsync( + () -> { + + var files = FileUtils.getFiles(directory, ".jar"); + + var urls = files + .stream() + .map(path -> Utils.uncheckedGet(path, Path::toUri)) + .map(uri -> Utils.uncheckedGet(uri, URI::toURL)) + .toArray(URL[]::new); + + var additionalPaths = files + .stream() + .map(Path::toAbsolutePath) + .map(Path::toString) + .toArray(String[]::new); + + var classLoader = new URLClassLoader(urls); + + var scanner = ClassPathScannerFactory.newDefaultScanner(classLoader, additionalPaths); + scanner.setUseSystemClasspath(false); + + try { + scanner.scan(); + } catch (Throwable exc) { + LOGGER.warning(exc); + return null; + } - /** - * Load a plugin from the directory. - * - * @param directory the plugin directory. - * @param parentLoader the parent class loader. - * @param parents the parent plugins. - * @param executor the executor. - * @param embedded the embedded flag. - * @return the future of loading plugin container. - */ - protected @NotNull CompletableFuture<@Nullable PluginContainer> loadPlugin( - @NotNull Path directory, - @NotNull ClassLoader parentLoader, - @Nullable PluginContainer[] parents, - @NotNull Executor executor, - boolean embedded - ) { - return supplyAsync(() -> { - - var files = FileUtils.getFiles(directory, ".jar"); - - var urls = files.stream() - .map(path -> Utils.uncheckedGet(path, Path::toUri)) - .map(uri -> Utils.uncheckedGet(uri, URI::toURL)) - .toArray(URL[]::new); - - var additionalPaths = files.stream() - .map(Path::toAbsolutePath) - .map(Path::toString) - .toArray(String[]::new); - - var classLoader = new URLClassLoader(urls); - - var scanner = ClassPathScannerFactory.newDefaultScanner(classLoader, additionalPaths); - scanner.setUseSystemClasspath(false); - - try { - scanner.scan(); - } catch (Throwable exc) { - LOGGER.warning(exc); - return null; - } + var pluginImplementations = ArrayFactory.>newArray(Class.class); + scanner.findImplements(pluginImplementations, Plugin.class); - var pluginImplementations = ArrayFactory.>newArray(Class.class); - scanner.findImplements(pluginImplementations, Plugin.class); - - if (pluginImplementations.isEmpty()) { - LOGGER.warning(directory, arg -> "Can't load the plugin from the directory" + arg + - " because can't find any implementation of the plugin interface."); - return null; - } else if (pluginImplementations.size() > 1) { - LOGGER.warning(directory, arg -> "Can't load the plugin from the directory" + arg + - " because found more than 1 implementation of the plugin interfaces."); - return null; - } + if (pluginImplementations.isEmpty()) { + LOGGER.warning( + directory, + arg -> "Can't load the plugin from the directory" + arg + + " because can't find any implementation of the plugin interface."); + return null; + } else if (pluginImplementations.size() > 1) { + LOGGER.warning( + directory, + arg -> "Can't load the plugin from the directory" + arg + + " because found more than 1 implementation of the plugin interfaces."); + return null; + } - var pluginClass = notNull(pluginImplementations.first()); - var description = pluginClass.getAnnotation(PluginDescription.class); + var pluginClass = notNull(pluginImplementations.first()); + var description = pluginClass.getAnnotation(PluginDescription.class); - if (description == null) { - LOGGER.warning(directory, arg -> "Can't load the plugin from the directory" + arg + - " because can't find any plugin class with description."); - return null; - } + if (description == null) { + LOGGER.warning( + directory, + arg -> "Can't load the plugin from the directory" + arg + + " because can't find any plugin class with description."); + return null; + } - var appVersion = getAppVersion(); + var appVersion = getAppVersion(); - if (appVersion != null) { + if (appVersion != null) { - var minVersion = new Version(description.minAppVersion()); + var minVersion = new Version(description.minAppVersion()); - if (minVersion.compareTo(appVersion) > 0) { - LOGGER.warning(description, arg -> "Can't load the plugin " + arg.id() + - ", it requires the app version " + arg.minAppVersion() + " or higher."); - return null; - } + if (minVersion.compareTo(appVersion) > 0) { + LOGGER.warning( + description, + arg -> "Can't load the plugin " + arg.id() + ", it requires the app version " + arg.minAppVersion() + + " or higher."); + return null; } + } - return new PluginContainer(pluginClass, classLoader, scanner, directory, embedded); + return new PluginContainer(pluginClass, classLoader, scanner, directory, embedded); }, executor); + } + + /** + * Get the application version. + * + * @return the application version or null. + */ + private @Nullable Version getAppVersion() { + return appVersion; + } + + /** + * Get the path to folder with embedded plugins. + * + * @return the path to folder with embedded plugins. + */ + protected Optional getEmbeddedPluginsPath() { + return Optional.ofNullable(embeddedPluginsPath); + } + + /** + * Get the path to folder with installed plugins. + * + * @return the path to folder with installed plugins. + */ + protected Optional getInstallationPluginsPath() { + return Optional.ofNullable(installationPluginsPath); + } + + @Override + public void configureEmbeddedPluginPath(Path embeddedPluginPath) { + if (isInitialized()) { + throw new RuntimeException("The plugin system is already initialized."); } + this.embeddedPluginsPath = embeddedPluginPath; + } - /** - * Get the application version. - * - * @return the application version or null. - */ - private @Nullable Version getAppVersion() { - return appVersion; + @Override + public void configureInstallationPluginsPath(Path installationPluginsPath) { + if (isInitialized()) { + throw new RuntimeException("The plugin system is already initialized."); } - - /** - * Get the path to folder with embedded plugins. - * - * @return the path to folder with embedded plugins. - */ - protected @NotNull Optional getEmbeddedPluginsPath() { - return Optional.ofNullable(embeddedPluginsPath); + this.installationPluginsPath = installationPluginsPath; + } + + /** + * Return true if this system was pre-loaded. + * + * @return true if this system was pre-loaded. + */ + protected boolean isPreLoaded() { + return preLoaded.get(); + } + + /** + * Return true if this system was initialized. + * + * @return true if this system was initialized. + */ + protected boolean isInitialized() { + return initialized.get(); + } + + @Override + public Array getPluginContainers() { + return state.get().idToContainer.values(PluginContainer.class); + } + + @Override + public @Nullable PluginContainer getPluginContainer(String id) { + return state.get().idToContainer.get(id); + } + + @Override + public Array getPlugins() { + return state.get().idToPlugin.values(Plugin.class); + } + + @Override + public @Nullable Plugin getPlugin(String id) { + return state.get().idToPlugin.get(id); + } + + @Override + public @Nullable Plugin installPlugin(Path file, boolean needInitialize) { + + var installPath = getInstallationPluginsPath() + .filter(path -> Files.exists(path)) + .orElse(null); + + if (installPath == null) { + throw new PluginException("The installation folder " + getInstallationPluginsPath() + " doesn't exists."); } - /** - * Get the path to folder with installed plugins. - * - * @return the path to folder with installed plugins. - */ - protected @NotNull Optional getInstallationPluginsPath() { - return Optional.ofNullable(installationPluginsPath); - } + var current = state.get(); + var folderName = FileUtils.getNameWithoutExtension(file); + var pluginFolder = installPath.resolve(folderName); - @Override - public void configureEmbeddedPluginPath(@NotNull Path embeddedPluginPath) { - if (isInitialized()) throw new RuntimeException("The plugin system is already initialized."); - this.embeddedPluginsPath = embeddedPluginPath; + if (Files.exists(pluginFolder)) { + FileUtils.delete(pluginFolder); } - @Override - public void configureInstallationPluginsPath(@NotNull Path installationPluginsPath) { - if (isInitialized()) throw new RuntimeException("The plugin system is already initialized."); - this.installationPluginsPath = installationPluginsPath; - } + FileUtils.createDirectories(pluginFolder); + FileUtils.unzip(pluginFolder, file); - /** - * Return true if this system was pre-loaded. - * - * @return true if this system was pre-loaded. - */ - protected boolean isPreLoaded() { - return preLoaded.get(); - } + var container = loadPlugin(pluginFolder, baseLoader, ForkJoinPool.commonPool(), false).join(); - /** - * Return true if this system was initialized. - * - * @return true if this system was initialized. - */ - protected boolean isInitialized() { - return initialized.get(); + if (container == null) { + return null; } - @Override - public @NotNull Array getPluginContainers() { - return state.get() - .idToContainer - .values(PluginContainer.class); - } + var existsContainer = getPluginContainer(container.getId()); - @Override - public @Nullable PluginContainer getPluginContainer(@NotNull String id) { - return state.get() - .idToContainer - .get(id); + if (existsContainer != null && !pluginFolder.equals(existsContainer.getPath())) { + FileUtils.delete(existsContainer.getPath()); } - @Override - public @NotNull Array getPlugins() { - return state.get() - .idToPlugin - .values(Plugin.class); - } + var pluginClass = container.getPluginClass(); + var constructor = ClassUtils.tryGetConstructor(pluginClass, PluginContainer.class); - @Override - public @Nullable Plugin getPlugin(@NotNull String id) { - return state.get() - .idToPlugin - .get(id); + if (constructor == null) { + throw new InitializePluginException( + "Not found base constructor in the class " + pluginClass, + container.getPath()); } - @Override - public @Nullable Plugin installPlugin(@NotNull Path file, boolean needInitialize) { - - var installPath = getInstallationPluginsPath() - .filter(path -> Files.exists(path)) - .orElse(null); - - if (installPath == null) { - throw new PluginException("The installation folder " + getInstallationPluginsPath() + " doesn't exists."); - } - - var current = state.get(); - var folderName = FileUtils.getNameWithoutExtension(file); - var pluginFolder = installPath.resolve(folderName); - - if (Files.exists(pluginFolder)) { - FileUtils.delete(pluginFolder); - } - - FileUtils.createDirectories(pluginFolder); - FileUtils.unzip(pluginFolder, file); - - var container = loadPlugin(pluginFolder, baseLoader, ForkJoinPool.commonPool(), false) - .join(); - - if (container == null) { - return null; - } - - var existsContainer = getPluginContainer(container.getId()); - - if (existsContainer != null && !pluginFolder.equals(existsContainer.getPath())) { - FileUtils.delete(existsContainer.getPath()); - } - - var pluginClass = container.getPluginClass(); - var constructor = ClassUtils.tryGetConstructor(pluginClass, PluginContainer.class); - - if (constructor == null) { - throw new InitializePluginException( - "Not found base constructor in the class " + pluginClass, - container.getPath() - ); - } - - Plugin plugin; - try { - plugin = ClassUtils.newInstance(constructor, container); - } catch (Exception exc) { - throw new InitializePluginException( - "Found a problem with creating a plugin " + pluginClass, - container.getPath(), - exc - ); - } - - if (needInitialize) { - try { - plugin.initialize(this); - } catch (Exception exc) { - throw new InitializePluginException( - "Found a problem with initializing a plugin " + plugin, - container.getPath(), - exc - ); - } - } + Plugin plugin; + try { + plugin = ClassUtils.newInstance(constructor, container); + } catch (Exception exc) { + throw new InitializePluginException( + "Found a problem with creating a plugin " + pluginClass, + container.getPath(), + exc); + } - var idToContainer = ObjectDictionary.ofType(String.class, PluginContainer.class); - idToContainer.put(current.idToContainer); - idToContainer.put(existsContainer.getId(), existsContainer); + if (needInitialize) { + try { + plugin.initialize(this); + } catch (Exception exc) { + throw new InitializePluginException( + "Found a problem with initializing a plugin " + plugin, + container.getPath(), + exc); + } + } - var idToPlugin = ObjectDictionary.ofType(String.class, Plugin.class); - idToPlugin.put(current.idToPlugin); - idToPlugin.put(plugin.getId(), plugin); + var idToContainer = ObjectDictionary.ofType(String.class, PluginContainer.class); + idToContainer.put(current.idToContainer); + idToContainer.put(existsContainer.getId(), existsContainer); - var containers = Array.ofType(PluginContainer.class); - containers.addAll(current.containers); - containers.add(existsContainer); + var idToPlugin = ObjectDictionary.ofType(String.class, Plugin.class); + idToPlugin.put(current.idToPlugin); + idToPlugin.put(plugin.getId(), plugin); - if (state.compareAndSet(current, new State(containers, idToContainer, idToPlugin))) { - return plugin; - } + var containers = Array.ofType(PluginContainer.class); + containers.addAll(current.containers); + containers.add(existsContainer); - return installPlugin(file, needInitialize); + if (state.compareAndSet(current, new State(containers, idToContainer, idToPlugin))) { + return plugin; } - @Override - public void removePlugin(@NotNull Plugin plugin) { + return installPlugin(file, needInitialize); + } + + @Override + public void removePlugin(Plugin plugin) { - var current = state.get(); + var current = state.get(); - var pluginId = plugin.getId(); - var pluginContainer = notNull(current.idToContainer.get(pluginId)); + var pluginId = plugin.getId(); + var pluginContainer = notNull(current.idToContainer.get(pluginId)); - var containers = Array.ofType(PluginContainer.class); - containers.addAll(current.containers); - containers.fastRemove(pluginContainer); + var containers = Array.ofType(PluginContainer.class); + containers.addAll(current.containers); + containers.fastRemove(pluginContainer); - var idToContainer = ObjectDictionary.ofType(String.class, PluginContainer.class); - idToContainer.put(current.idToContainer); - idToContainer.remove(pluginId); + var idToContainer = ObjectDictionary.ofType(String.class, PluginContainer.class); + idToContainer.put(current.idToContainer); + idToContainer.remove(pluginId); - var idToPlugin = ObjectDictionary.ofType(String.class, Plugin.class); - idToPlugin.put(current.idToPlugin); - idToPlugin.remove(pluginId); + var idToPlugin = ObjectDictionary.ofType(String.class, Plugin.class); + idToPlugin.put(current.idToPlugin); + idToPlugin.remove(pluginId); - containers.addAll(current.containers); - containers.fastRemove(pluginContainer); + containers.addAll(current.containers); + containers.fastRemove(pluginContainer); - if (state.compareAndSet(current, new State(containers, idToContainer, idToPlugin))) { - FileUtils.delete(pluginContainer.getPath()); - } + if (state.compareAndSet(current, new State(containers, idToContainer, idToPlugin))) { + FileUtils.delete(pluginContainer.getPath()); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/PluginSystemFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/PluginSystemFactory.java index d9ffd30c..8db1a59a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/PluginSystemFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/impl/PluginSystemFactory.java @@ -1,20 +1,21 @@ package javasabr.rlib.common.plugin.impl; import javasabr.rlib.common.plugin.ConfigurablePluginSystem; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory of different plugin systems. * * @author JavaSaBr */ +@NullMarked public class PluginSystemFactory { - public static @NotNull ConfigurablePluginSystem newBasePluginSystem() { - return new BasePluginSystem(); - } + public static ConfigurablePluginSystem newBasePluginSystem() { + return new BasePluginSystem(); + } - public static @NotNull ConfigurablePluginSystem newBasePluginSystem(@NotNull ClassLoader classLoader) { - return new BasePluginSystem(classLoader); - } + public static ConfigurablePluginSystem newBasePluginSystem(ClassLoader classLoader) { + return new BasePluginSystem(classLoader); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java index 799bb234..0cc5e06c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java @@ -22,1807 +22,1913 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.IntegerArray; import javasabr.rlib.common.util.array.LongArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The utility class. * * @author JavaSaBr */ +@NullMarked public final class ArrayUtils { - public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; - public static final String[] EMPTY_STRING_ARRAY = new String[0]; - public static final Enum[] EMPTY_ENUM_ARRAY = new Enum[0]; - public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; - - public static final int[] EMPTY_INT_ARRAY = new int[0]; - public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; - public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; - public static final short[] EMPTY_SHORT_ARRAY = new short[0]; - public static final long[] EMPTY_LONG_ARRAY = new long[0]; - public static final char[] EMPTY_CHAR_ARRAY = new char[0]; - - /** - * Convert an object integer array to primitive int array. - * - * @param array the object integer array. - * @return the primitive int array. - * @since 9.2.1 - */ - public static @NotNull int[] toIntArray(@NotNull Integer[] array) { - - if (array.length < 1) { - return ArrayUtils.EMPTY_INT_ARRAY; - } - - var intArray = new int[array.length]; - - for (int i = 0; i < array.length; i++) { - intArray[i] = array[i]; - } - - return intArray; - } - - /** - * Convert an string to primitive int array by regex. - * - * @param string the string. - * @param regex the regex. - * @return the primitive int array. - * @throws NumberFormatException if some elements in the string are not an integer. - * @since 9.2.1 - */ - public static @NotNull int[] toIntArray(@NotNull String string, @NotNull String regex) { - - if (string.isBlank()) { - return ArrayUtils.EMPTY_INT_ARRAY; - } - - var elements = string.split(regex); - - if (elements.length < 1) { - return ArrayUtils.EMPTY_INT_ARRAY; - } - - var intArray = new int[elements.length]; - - for (int i = 0; i < elements.length; i++) { - intArray[i] = Integer.parseInt(elements[i].trim()); - } - - return intArray; - } - - /** - * Add the element to the array and extend or create the array if need. - * - * @param the type parameter - * @param array the array. - * @param element the element. - * @param type the type of array. - * @return the result array with added element. - */ - public static @NotNull T[] addToArray(@Nullable T[] array, @NotNull T element, @NotNull Class type) { - - if (array == null) { - array = create(type, 1); - array[0] = element; - return array; - } - - int length = array.length; - - array = copyOfAndExtend(array, 1); - array[length] = element; - - return array; - } - - /** - * Clear all elements in the array. - * - * @param array the array. - */ - public static void clear(@NotNull Object[] array) { - Arrays.fill(array, null); - } - - /** - * Fill the array using the factory. - * - * @param array the array. - * @param factory the element's factory. - * @param the element's type. - */ - public static void fill(@NotNull T[] array, @NotNull Supplier factory) { - for (int i = 0; i < array.length; i++) { - array[i] = factory.get(); - } - } - - /** - * Fill the array using the factory. - * - * @param array the array. - * @param factory the element's factory. - * @since 8.1.0 - */ - public static void fill(@NotNull char[] array, @NotNull CharSupplier factory) { - for (int i = 0; i < array.length; i++) { - array[i] = factory.getAsChar(); - } - } - - /** - * Fill the array using the factory which receives array's index. - * - * @param array the array. - * @param factory the element's factory. - * @param the element's type. - */ - public static void fill(@NotNull T[] array, @NotNull IntFunction factory) { - Arrays.setAll(array, factory); - } - - /** - * Fill the array using the factory. - * - * @param the element's type. - * @param the argument's type. - * @param array the array. - * @param argument the additional argument. - * @param factory the element's factory. - */ - public static void fill(@NotNull T[] array, @Nullable F argument, @NotNull Function factory) { - for (int i = 0; i < array.length; i++) { - array[i] = factory.apply(argument); - } - } - - /** - * Combine the two arrays. - * - * @param base the source array. - * @param added the add array. - * @return the combined array. - */ - public static @NotNull int[] combine(@Nullable final int[] base, @Nullable final int[] added) { - - if (base == null) { - return added == null ? new int[0] : added; - } else if (added == null || added.length < 1) { - return base; - } - - final int[] result = new int[base.length + added.length]; - - int index = 0; - - for (int val : base) result[index++] = val; - for (int val : added) result[index++] = val; - - return result; - } - - /** - * Combine two arrays to one single array. - * - * @param the base array's component type. - * @param the added array's component type. - * @param base the base array. - * @param added the additional array. - * @return the combined array. - */ - public static @NotNull T[] combine(@NotNull T[] base, @Nullable E[] added) { - return combine(base, added, getComponentType(base)); - } - - /** - * Combine two arrays to one single array. - * - * @param the base array's component type. - * @param the added array's component type. - * @param base the base array. - * @param added the additional array. - * @param type the base array's component type. - * @return the combined array. - */ - public static @NotNull T[] combine( - @Nullable T[] base, - @Nullable E[] added, - @NotNull Class type - ) { - - if (base == null) { - return added == null ? create(type, 0) : added; - } else if (added == null || added.length < 1) { - return base; - } - - T[] result = create(type, base.length + added.length); - - int index = 0; - - for (T object : base) { - result[index++] = object; - } - - for (E object : added) { - result[index++] = object; - } - - return result; - } - - /** - * Combine two arrays to one single array with uniq elements. - * - * @param the base array's component type. - * @param the added array's component type. - * @param base the base array. - * @param added the additional array. - * @return the combined array with uniq elements. - */ - public static @NotNull T[] combineUniq(@NotNull T[] base, @Nullable E[] added) { - return combineUniq(base, added, getComponentType(base)); - } - - /** - * Combine two arrays to one single array with uniq elements. - * - * @param the base array's component type. - * @param the added array's component type. - * @param base the base array. - * @param added the additional array. - * @param type the base array's component type. - * @return the combined array with uniq elements. - */ - public static @NotNull T[] combineUniq( - @Nullable T[] base, - @Nullable E[] added, - @NotNull Class type - ) { - - if (base == null) { - return added == null ? create(type, 0) : added; - } else if (added == null || added.length < 1) { - return base; - } - - var result = new HashSet(base.length + added.length); - result.addAll(Arrays.asList(base)); - result.addAll(Arrays.asList(added)); - - return result.toArray(create(type, result.size())); - } - - /** - * Check the array on contains the value. - * - * @param array the array. - * @param val the value. - * @return true if the array contains the value. - */ - public static boolean contains(@NotNull int[] array, int val) { - - for (int value : array) { - if (value == val) { - return true; - } - } - - return false; - } - - /** - * Return true if an array contains an object. - * - * @param array the array. - * @param object the object. - * @return true if the array contains the object. - */ - public static boolean contains(@NotNull Object[] array, @NotNull Object object) { - - for (var element : array) { - if (Objects.equals(element, object)) { - return true; - } - } - - return false; - } - - /** - * Copy and extend the array. - * - * @param old the source array. - * @param added the added size. - * @return the new array. - */ - public static @NotNull byte[] copyOf(@NotNull final byte[] old, final int added) { - var copy = new byte[old.length + added]; - System.arraycopy(old, 0, copy, 0, Math.min(old.length, copy.length)); - return copy; - } - - /** - * Copy and extend the array. - * - * @param old the source array. - * @param added the added size. - * @return the new array. - */ - public static @NotNull int[] copyOf(@NotNull final int[] old, final int added) { - var copy = new int[old.length + added]; - System.arraycopy(old, 0, copy, 0, Math.min(old.length, copy.length)); - return copy; - } - - /** - * Copy and extend the array. - * - * @param old the source array. - * @param added the added size. - * @return the new array. - */ - public static @NotNull long[] copyOf(@NotNull final long[] old, final int added) { - var copy = new long[old.length + added]; - System.arraycopy(old, 0, copy, 0, Math.min(old.length, copy.length)); - return copy; - } - - /** - * Copy a native array. - * - * @param the array component's type. - * @param original the original array. - * @return the new copied native array. - */ - public static @NotNull T[] copyOf(@NotNull T[] original) { - return Arrays.copyOf(original, original.length); - } - - /** - * Copy an array and extend if need. - * - * @param the array component's type. - * @param original the original array. - * @param added the additional size. - * @return the new copied array. - */ - @SuppressWarnings("unchecked") - public static @NotNull T[] copyOfAndExtend(@NotNull T[] original, int added) { - return Arrays.copyOf(original, original.length + added); - } - - /** - * Copy and extend the array. - * - * @param the array component's type. - * @param original the source array. - * @param offset the start position to copy in new array. - * @param added the added size. - * @return the new array. - */ - public static @NotNull T[] copyOf(@NotNull T[] original, int offset, int added) { - - Class newType = original.getClass(); - T[] newArray = create(newType.getComponentType(), original.length + added); - - System.arraycopy(original, 0, newArray, offset, Math.min(original.length, newArray.length)); - - return newArray; - } - - /** - * Copy data form the source array to the destination array. - * - * @param source the source array. - * @param target the target array. - */ - public static void copyTo(@NotNull int[] source, int[] target) { - System.arraycopy(source, 0, target, 0, source.length); - } - - /** - * Copy data form the source array to the destination array. - * - * @param source the source array. - * @param target the target array. - * @param sourceOffset the source offset. - * @param targetOffset the target offset. - * @param length the length of data. - */ - public static void copyTo( - @NotNull int[] source, - @NotNull int[] target, - int sourceOffset, - int targetOffset, - int length - ) { - System.arraycopy(source, sourceOffset, target, targetOffset, length); - } - - /** - * Copy a part of the array to a new array. - * - * @param original the source array. - * @param from the start element. - * @param to the last element. - * @return the new array. - */ - public static @NotNull int[] copyOfRange(@NotNull int[] original, int from, int to) { - - var newLength = to - from; - var copy = new int[newLength]; - - System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); - - return copy; - } - - /** - * Copy a part of the array to a new array. - * - * @param original the source array. - * @param from the start element. - * @param to the last element. - * @return the new array. - */ - public static @NotNull long[] copyOfRange(@NotNull long[] original, int from, int to) { - - var newLength = to - from; - var copy = new long[newLength]; - - System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); - - return copy; - } - - /** - * Copy a part of the array to a new array. - * - * @param the type parameter - * @param original the source array. - * @param from the start element. - * @param to the last element. - * @return the new array. - */ - public static @NotNull T[] copyOfRange(@NotNull T[] original, int from, int to) { - return Arrays.copyOfRange(original, from, to); - } - - /** - * Get a component type of an array. - * - * @param the array's component type. - * @param example the array's example. - * @return the component type. - */ - public static @NotNull Class getComponentType(@NotNull T[] example) { - return ClassUtils.unsafeNNCast(example.getClass().getComponentType()); - } - - /** - * Create the array by the type. - * - * @param the type parameter - * @param example the array's example. - * @param size the size. - * @return the new array. - */ - public static @NotNull T[] create(@NotNull T[] example, int size) { - return ClassUtils.unsafeCast(java.lang.reflect.Array.newInstance(example.getClass().getComponentType(), size)); - } - - /** - * Create the array by the type. - * - * @param the type parameter - * @param type the array type. - * @param size the size. - * @return the new array. - */ - public static @NotNull T[] create(@NotNull Class type, int size) { - return ClassUtils.unsafeCast(java.lang.reflect.Array.newInstance(type, size)); - } - - /** - * Find an index of the object in the array. - * - * @param array the array. - * @param object the object. - * @return the object's index or -1. - */ - public static int indexOf(@NotNull Object[] array, @Nullable Object object) { - - int index = 0; - - for (var element : array) { - if (Objects.equals(element, object)) { - return index; - } - index++; - } - - return -1; - } - - /** - * Sort the array. - * - * @param array the array. - */ - public static void sort(@NotNull final Comparable[] array) { - java.util.Arrays.sort(array); - } - - /** - * Sort the array. - * - * @param array the array. - */ - public static void sort(@NotNull final int[] array) { - java.util.Arrays.sort(array); - } - - /** - * Sort the array. - * - * @param array the array. - * @param fromIndex the start index. - * @param toIndex the last index. - */ - public static void sort(@NotNull final int[] array, final int fromIndex, final int toIndex) { - java.util.Arrays.sort(array, fromIndex, toIndex); - } - - /** - * Sort the array. - * - * @param array the array. - * @param fromIndex the start index. - * @param toIndex the last index. - */ - public static void sort(@NotNull final long[] array, final int fromIndex, final int toIndex) { - java.util.Arrays.sort(array, fromIndex, toIndex); - } - - /** - * Sort the array. - * - * @param the type parameter - * @param array the array. - * @param comparator the comparator. - */ - public static void sort(@NotNull final T[] array, @NotNull final Comparator comparator) { - java.util.Arrays.sort(array, comparator); - } - - /** - * Sort the array. - * - * @param the type parameter - * @param array the array. - * @param fromIndex the start index. - * @param toIndex the last index. - * @param comparator the comparator. - */ - public static void sort(@NotNull final T[] array, final int fromIndex, final int toIndex, - @NotNull final Comparator comparator) { - java.util.Arrays.sort(array, fromIndex, toIndex, comparator); - } - - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @return the string presentation. - */ - public static @NotNull String toString(@NotNull Array array) { - return toString(array, Object::toString); - } - - /** - * Convert the array to a string presentation. - * - * @param the element's type. - * @param array the array. - * @param toString the to string function. - * @return the string presentation. - */ - public static @NotNull String toString(@NotNull Array array, @NotNull Function toString) { - - if (array.isEmpty()) { - return "[]"; - } - - var className = array.array() - .getClass() - .getSimpleName(); - - var builder = new StringBuilder(className.substring(0, className.length() - 1)); - - for (int i = 0, length = array.size() - 1; i <= length; i++) { - - builder.append(toString.apply(array.get(i))); + public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; + public static final String[] EMPTY_STRING_ARRAY = new String[0]; + public static final Enum[] EMPTY_ENUM_ARRAY = new Enum[0]; + public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; - if (i == length) { - break; - } + public static final int[] EMPTY_INT_ARRAY = new int[0]; + public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; + public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; + public static final short[] EMPTY_SHORT_ARRAY = new short[0]; + public static final long[] EMPTY_LONG_ARRAY = new long[0]; + public static final char[] EMPTY_CHAR_ARRAY = new char[0]; - builder.append(", "); - } - - builder.append("]"); - - return builder.toString(); + /** + * Convert an object integer array to primitive int array. + * + * @param array the object integer array. + * @return the primitive int array. + * @since 9.2.1 + */ + public static int[] toIntArray(Integer[] array) { + + if (array.length < 1) { + return ArrayUtils.EMPTY_INT_ARRAY; } - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @return the string presentation. - */ - public static @NotNull String toString(@NotNull final IntegerArray array) { - - final String className = array.array().getClass().getSimpleName(); - final StringBuilder builder = new StringBuilder(className.substring(0, className.length() - 1)); - - for (int i = 0, length = array.size() - 1; i <= length; i++) { - builder.append(String.valueOf(array.get(i))); - if (i == length) break; - builder.append(", "); - } + var intArray = new int[array.length]; + + for (int i = 0; i < array.length; i++) { + intArray[i] = array[i]; + } + + return intArray; + } + + /** + * Convert an string to primitive int array by regex. + * + * @param string the string. + * @param regex the regex. + * @return the primitive int array. + * @throws NumberFormatException if some elements in the string are not an integer. + * @since 9.2.1 + */ + public static int[] toIntArray(String string, String regex) { + + if (string.isBlank()) { + return ArrayUtils.EMPTY_INT_ARRAY; + } + + var elements = string.split(regex); + + if (elements.length < 1) { + return ArrayUtils.EMPTY_INT_ARRAY; + } + + var intArray = new int[elements.length]; + + for (int i = 0; i < elements.length; i++) { + intArray[i] = Integer.parseInt(elements[i].trim()); + } + + return intArray; + } + + /** + * Add the element to the array and extend or create the array if need. + * + * @param the type parameter + * @param array the array. + * @param element the element. + * @param type the type of array. + * @return the result array with added element. + */ + public static T[] addToArray(T @Nullable [] array, T element, Class type) { + + if (array == null) { + array = create(type, 1); + array[0] = element; + return array; + } + + int length = array.length; + + array = copyOfAndExtend(array, 1); + array[length] = element; + + return array; + } + + /** + * Clear all elements in the array. + * + * @param array the array. + */ + public static void clear(Object[] array) { + Arrays.fill(array, null); + } + + /** + * Fill the array using the factory. + * + * @param array the array. + * @param factory the element's factory. + * @param the element's type. + */ + public static void fill(T[] array, Supplier factory) { + for (int i = 0; i < array.length; i++) { + array[i] = factory.get(); + } + } + + /** + * Fill the array using the factory. + * + * @param array the array. + * @param factory the element's factory. + * @since 8.1.0 + */ + public static void fill(char[] array, CharSupplier factory) { + for (int i = 0; i < array.length; i++) { + array[i] = factory.getAsChar(); + } + } + + /** + * Fill the array using the factory which receives array's index. + * + * @param array the array. + * @param factory the element's factory. + * @param the element's type. + */ + public static void fill(T[] array, IntFunction factory) { + Arrays.setAll(array, factory); + } + + /** + * Fill the array using the factory. + * + * @param the element's type. + * @param the argument's type. + * @param array the array. + * @param argument the additional argument. + * @param factory the element's factory. + */ + public static void fill(T[] array, @Nullable F argument, Function factory) { + for (int i = 0; i < array.length; i++) { + array[i] = factory.apply(argument); + } + } + + /** + * Combine the two arrays. + * + * @param base the source array. + * @param added the add array. + * @return the combined array. + */ + public static int[] combine(int @Nullable [] base, int @Nullable [] added) { + + if (base == null) { + return added == null ? new int[0] : added; + } else if (added == null || added.length < 1) { + return base; + } + + final int[] result = new int[base.length + added.length]; + + int index = 0; + + for (int val : base) + result[index++] = val; + for (int val : added) + result[index++] = val; + + return result; + } + + /** + * Combine two arrays to one single array. + * + * @param the base array's component type. + * @param the added array's component type. + * @param base the base array. + * @param added the additional array. + * @return the combined array. + */ + public static T[] combine(T[] base, E @Nullable [] added) { + return combine(base, added, getComponentType(base)); + } + + /** + * Combine two arrays to one single array. + * + * @param the base array's component type. + * @param the added array's component type. + * @param base the base array. + * @param added the additional array. + * @param type the base array's component type. + * @return the combined array. + */ + public static T[] combine(T @Nullable [] base, E @Nullable [] added, Class type) { + + if (base == null) { + return added == null ? create(type, 0) : added; + } else if (added == null || added.length < 1) { + return base; + } + + T[] result = create(type, base.length + added.length); + + int index = 0; + + for (T object : base) { + result[index++] = object; + } + + for (E object : added) { + result[index++] = object; + } + + return result; + } + + /** + * Combine two arrays to one single array with uniq elements. + * + * @param the base array's component type. + * @param the added array's component type. + * @param base the base array. + * @param added the additional array. + * @return the combined array with uniq elements. + */ + public static T[] combineUniq(T[] base, E @Nullable [] added) { + return combineUniq(base, added, getComponentType(base)); + } + + /** + * Combine two arrays to one single array with uniq elements. + * + * @param the base array's component type. + * @param the added array's component type. + * @param base the base array. + * @param added the additional array. + * @param type the base array's component type. + * @return the combined array with uniq elements. + */ + public static T[] combineUniq( + T @Nullable [] base, + E @Nullable [] added, + Class type) { + + if (base == null) { + return added == null ? create(type, 0) : added; + } else if (added == null || added.length < 1) { + return base; + } + + var result = new HashSet(base.length + added.length); + result.addAll(Arrays.asList(base)); + result.addAll(Arrays.asList(added)); + + return result.toArray(create(type, result.size())); + } + + /** + * Check the array on contains the value. + * + * @param array the array. + * @param val the value. + * @return true if the array contains the value. + */ + public static boolean contains(int[] array, int val) { + + for (int value : array) { + if (value == val) { + return true; + } + } + + return false; + } + + /** + * Return true if an array contains an object. + * + * @param array the array. + * @param object the object. + * @return true if the array contains the object. + */ + public static boolean contains(Object[] array, Object object) { + + for (var element : array) { + if (Objects.equals(element, object)) { + return true; + } + } + + return false; + } + + /** + * Copy and extend the array. + * + * @param old the source array. + * @param added the added size. + * @return the new array. + */ + public static byte[] copyOf(byte[] old, int added) { + var copy = new byte[old.length + added]; + System.arraycopy(old, 0, copy, 0, Math.min(old.length, copy.length)); + return copy; + } + + /** + * Copy and extend the array. + * + * @param old the source array. + * @param added the added size. + * @return the new array. + */ + public static int[] copyOf(int[] old, int added) { + var copy = new int[old.length + added]; + System.arraycopy(old, 0, copy, 0, Math.min(old.length, copy.length)); + return copy; + } + + /** + * Copy and extend the array. + * + * @param old the source array. + * @param added the added size. + * @return the new array. + */ + public static long[] copyOf(long[] old, int added) { + var copy = new long[old.length + added]; + System.arraycopy(old, 0, copy, 0, Math.min(old.length, copy.length)); + return copy; + } + + /** + * Copy a native array. + * + * @param the array component's type. + * @param original the original array. + * @return the new copied native array. + */ + public static T[] copyOf(T[] original) { + return Arrays.copyOf(original, original.length); + } + + /** + * Copy an array and extend if need. + * + * @param the array component's type. + * @param original the original array. + * @param added the additional size. + * @return the new copied array. + */ + public static T[] copyOfAndExtend(T[] original, int added) { + return Arrays.copyOf(original, original.length + added); + } + + /** + * Copy and extend the array. + * + * @param the array component's type. + * @param original the source array. + * @param offset the start position to copy in new array. + * @param added the added size. + * @return the new array. + */ + public static T[] copyOf(T[] original, int offset, int added) { + + Class newType = original.getClass(); + T[] newArray = create(newType.getComponentType(), original.length + added); + + System.arraycopy(original, 0, newArray, offset, Math.min(original.length, newArray.length)); + + return newArray; + } + + /** + * Copy data form the source array to the destination array. + * + * @param source the source array. + * @param target the target array. + */ + public static void copyTo(int[] source, int[] target) { + System.arraycopy(source, 0, target, 0, source.length); + } + + /** + * Copy data form the source array to the destination array. + * + * @param source the source array. + * @param target the target array. + * @param sourceOffset the source offset. + * @param targetOffset the target offset. + * @param length the length of data. + */ + public static void copyTo( + int[] source, + int[] target, + int sourceOffset, + int targetOffset, + int length) { + System.arraycopy(source, sourceOffset, target, targetOffset, length); + } + + /** + * Copy a part of the array to a new array. + * + * @param original the source array. + * @param from the start element. + * @param to the last element. + * @return the new array. + */ + public static int[] copyOfRange(int[] original, int from, int to) { + + var newLength = to - from; + var copy = new int[newLength]; + + System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); + + return copy; + } + + /** + * Copy a part of the array to a new array. + * + * @param original the source array. + * @param from the start element. + * @param to the last element. + * @return the new array. + */ + public static long[] copyOfRange(long[] original, int from, int to) { + + var newLength = to - from; + var copy = new long[newLength]; + + System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); + + return copy; + } + + /** + * Copy a part of the array to a new array. + * + * @param the type parameter + * @param original the source array. + * @param from the start element. + * @param to the last element. + * @return the new array. + */ + public static T[] copyOfRange(T[] original, int from, int to) { + return Arrays.copyOfRange(original, from, to); + } + + /** + * Get a component type of an array. + * + * @param the array's component type. + * @param example the array's example. + * @return the component type. + */ + public static Class getComponentType(T[] example) { + return ClassUtils.unsafeNNCast(example + .getClass() + .getComponentType()); + } + + /** + * Create the array by the type. + * + * @param the type parameter + * @param example the array's example. + * @param size the size. + * @return the new array. + */ + public static T[] create(T[] example, int size) { + return ClassUtils.unsafeCast(java.lang.reflect.Array.newInstance( + example + .getClass() + .getComponentType(), size)); + } + + /** + * Create the array by the type. + * + * @param the type parameter + * @param type the array type. + * @param size the size. + * @return the new array. + */ + public static T[] create(Class type, int size) { + return ClassUtils.unsafeCast(java.lang.reflect.Array.newInstance(type, size)); + } + + /** + * Find an index of the object in the array. + * + * @param array the array. + * @param object the object. + * @return the object's index or -1. + */ + public static int indexOf(Object[] array, @Nullable Object object) { + + int index = 0; + + for (var element : array) { + if (Objects.equals(element, object)) { + return index; + } + index++; + } + + return -1; + } + + /** + * Sort the array. + * + * @param array the array. + */ + public static void sort(final Comparable[] array) { + java.util.Arrays.sort(array); + } + + /** + * Sort the array. + * + * @param array the array. + */ + public static void sort(int[] array) { + java.util.Arrays.sort(array); + } + + /** + * Sort the array. + * + * @param array the array. + * @param fromIndex the start index. + * @param toIndex the last index. + */ + public static void sort(int[] array, int fromIndex, int toIndex) { + java.util.Arrays.sort(array, fromIndex, toIndex); + } + + /** + * Sort the array. + * + * @param array the array. + * @param fromIndex the start index. + * @param toIndex the last index. + */ + public static void sort(long[] array, int fromIndex, int toIndex) { + java.util.Arrays.sort(array, fromIndex, toIndex); + } + + /** + * Sort the array. + * + * @param the type parameter + * @param array the array. + * @param comparator the comparator. + */ + public static void sort(T[] array, Comparator comparator) { + java.util.Arrays.sort(array, comparator); + } + + /** + * Sort the array. + * + * @param the type parameter + * @param array the array. + * @param fromIndex the start index. + * @param toIndex the last index. + * @param comparator the comparator. + */ + public static void sort( + T[] array, + int fromIndex, + int toIndex, + Comparator comparator) { + java.util.Arrays.sort(array, fromIndex, toIndex, comparator); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @return the string presentation. + */ + public static String toString(Array array) { + return toString(array, Object::toString); + } + + /** + * Convert the array to a string presentation. + * + * @param the element's type. + * @param array the array. + * @param toString the to string function. + * @return the string presentation. + */ + public static String toString(Array array, Function toString) { + + if (array.isEmpty()) { + return "[]"; + } + + var className = array + .array() + .getClass() + .getSimpleName(); + + var builder = new StringBuilder(className.substring(0, className.length() - 1)); + + for (int i = 0, length = array.size() - 1; i <= length; i++) { + + builder.append(toString.apply(array.get(i))); + + if (i == length) { + break; + } + + builder.append(", "); + } + + builder.append("]"); + + return builder.toString(); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @return the string presentation. + */ + public static String toString(IntegerArray array) { + + final String className = array + .array() + .getClass() + .getSimpleName(); + final StringBuilder builder = new StringBuilder(className.substring(0, className.length() - 1)); + + for (int i = 0, length = array.size() - 1; i <= length; i++) { + builder.append(String.valueOf(array.get(i))); + if (i == length) { + break; + } + builder.append(", "); + } + + builder.append("]"); + return builder.toString(); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @return the string presentation. + */ + public static String toString(LongArray array) { + + final String className = array + .array() + .getClass() + .getSimpleName(); + final StringBuilder builder = new StringBuilder(className.substring(0, className.length() - 1)); + + for (int i = 0, length = array.size() - 1; i <= length; i++) { + builder.append(String.valueOf(array.get(i))); + if (i == length) { + break; + } + builder.append(", "); + } + + builder.append("]"); + return builder.toString(); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @return the string presentation. + */ + public static String toString(int @Nullable [] array) { + return toString(array, ", ", true, true); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @param separator the separator. + * @param needType true if need adding type of array. + * @param needBrackets true if need adding brackets. + * @return the string presentation of the array. + */ + public static String toString( + int @Nullable [] array, + final String separator, + final boolean needType, + final boolean needBrackets) { + + if (array == null) { + array = EMPTY_INT_ARRAY; + } + + final StringBuilder builder = new StringBuilder(); + + if (needType) { + builder.append("int"); + } + if (needBrackets) { + builder.append('['); + } + + for (int i = 0, length = array.length - 1; i <= length; i++) { + builder.append(String.valueOf(array[i])); + if (i == length) { + break; + } + builder.append(separator); + } + + if (needBrackets) { + builder.append(']'); + } + + return builder.toString(); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @return the string presentation. + */ + public static String toString(float @Nullable [] array) { + return toString(array, ", ", true, true); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @param separator the separator. + * @param needType true if need adding type of array. + * @param needBrackets true if need adding brackets. + * @return the string presentation of the array. + */ + public static String toString( + float @Nullable [] array, + final String separator, + final boolean needType, + final boolean needBrackets) { + + if (array == null) { + array = EMPTY_FLOAT_ARRAY; + } + + final StringBuilder builder = new StringBuilder(); + + if (needType) { + builder.append("float"); + } + if (needBrackets) { + builder.append('['); + } + + for (int i = 0, length = array.length - 1; i <= length; i++) { + builder.append(String.valueOf(array[i])); + if (i == length) { + break; + } + builder.append(separator); + } + + if (needBrackets) { + builder.append(']'); + } + + return builder.toString(); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @return the string presentation of the array. + */ + public static String toString(Object @Nullable [] array) { + return toString(array, ", ", true, true); + } + + /** + * Convert the array to a string presentation. + * + * @param array the array. + * @param separator the separator. + * @param needType true if need adding type of array. + * @param needBrackets true if need adding brackets. + * @return the string presentation of the array. + */ + public static String toString( + Object @Nullable [] array, + String separator, + boolean needType, + boolean needBrackets) { + + if (array == null) { + array = EMPTY_OBJECT_ARRAY; + } + + final StringBuilder builder = new StringBuilder(); + + if (needType) { + builder.append(array + .getClass() + .getSimpleName()); + } + if (needBrackets) { + builder.append('['); + } + + for (int i = 0, length = array.length - 1; i <= length; i++) { + builder.append(String.valueOf(array[i])); + if (i == length) { + break; + } + builder.append(separator); + } + + if (needBrackets) { + builder.append(']'); + } + + return builder.toString(); + } + + /** + * Move all elements from the source array to the destination array. + * + * @param the type parameter + * @param the type parameter + * @param source the source array. + * @param destination the destination array. + * @param clearSource need clears the source array after moving. + */ + public static void move(Array source, Array destination, boolean clearSource) { + + if (source.isEmpty()) { + return; + } + + destination.addAll(source); + + if (clearSource) { + source.clear(); + } + } + + /** + * Move all elements from the source array to the destination array. + * + * @param the type parameter + * @param the type parameter + * @param source the source array. + * @param destination the destination array. + */ + public static void move(Array source, Array destination) { + move(source, destination, true); + } + + /** + * Add the object to the array in a synchronize block. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param object the object. + */ + public static void addInSynchronizeTo(Array array, V object) { + synchronized (array) { + array.add(object); + } + } + + /** + * Fast remove the object from the array in a synchronize block. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param object the object. + */ + public static void fastRemoveInSynchronizeTo( + Array array, + V object) { + synchronized (array) { + array.fastRemove(object); + } + } + + /** + * Apply the function to each element of the array. + * + * @param the type parameter + * @param array the array. + * @param function the function. + */ + public static void forEach(T @Nullable [] array, Consumer function) { + if (array == null || array.length < 1) { + return; + } + for (T element : array) { + function.accept(element); + } + } + + /** + * Apply the function to each filtered element of the array. + * + * @param the type parameter + * @param array the array. + * @param condition the condition. + * @param function the function. + */ + public static void forEach( + T @Nullable [] array, + Predicate condition, + Consumer function) { + if (array == null || array.length < 1) { + return; + } + for (T element : array) { + if (condition.test(element)) { + function.accept(element); + } + } + } + + /** + * Apply the consumer for each element of the array. + * + * @param the type parameter + * @param array the array. + * @param argument the additional argument. + * @param consumer the consumer. + */ + public static void forEach( + int @Nullable [] array, + @Nullable F argument, + IntObjectConsumer consumer) { + if (array == null || array.length < 1) { + return; + } + for (int element : array) { + consumer.accept(element, argument); + } + } + + /** + * Apply the consumer for each element of the array. + * + * @param the type parameter + * @param array the array. + * @param argument the additional argument. + * @param consumer the consumer. + */ + public static void forEach( + double @Nullable[] array, + @Nullable F argument, + DoubleObjectConsumer consumer) { + if (array == null || array.length < 1) { + return; + } + for (double element : array) { + consumer.accept(element, argument); + } + } + + /** + * Apply the consumer for each element of the array. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the additional argument. + * @param consumer the consumer. + */ + public static void forEach( + T @Nullable [] array, + @Nullable F argument, + BiConsumer consumer) { + if (array == null || array.length < 1) { + return; + } + for (T element : array) { + consumer.accept(element, argument); + } + } + + /** + * Handle elements of the array. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the additional argument. + * @param getElement the function to get sub element. + * @param finalFunction the final function. + */ + public static void forEach( + T @Nullable [] array, + @Nullable F argument, + Function getElement, + BiConsumer finalFunction) { + if (array == null || array.length < 1) { + return; + } + for (T element : array) { + R subElement = getElement.apply(element); + if (subElement != null) { + finalFunction.accept(subElement, argument); + } + } + } + + /** + * Apply the function to each filtered element of the array. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the additional argument. + * @param condition the condition. + * @param function the function. + */ + public static void forEach( + T @Nullable [] array, + @Nullable F argument, + Predicate condition, + BiConsumer function) { + if (array == null || array.length < 1) { + return; + } + for (T element : array) { + if (condition.test(element)) { + function.accept(element, argument); + } + } + } + + /** + * Apply the function to each filtered element of the array. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the additional argument. + * @param condition the condition. + * @param getElement the function to get sub element. + * @param finalFunction the final function. + */ + public static void forEach( + T @Nullable [] array, + @Nullable F argument, + Predicate condition, + Function getElement, + BiConsumer finalFunction) { + if (array == null || array.length < 1) { + return; + } + for (T element : array) { + if (!condition.test(element)) { + continue; + } + R subElement = getElement.apply(element); + finalFunction.accept(subElement, argument); + } + } + + /** + * Apply the function to each element of the array. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param first the first argument. + * @param second the second argument. + * @param function the function. + */ + public static void forEach( + T @Nullable [] array, + @Nullable F first, + @Nullable S second, + TripleConsumer function) { + if (array == null || array.length < 1) { + return; + } + for (final T element : array) { + function.accept(element, first, second); + } + } + + /** + * Apply the function to each sub-element of the array. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param first the first argument. + * @param second the second argument. + * @param getElement the function to get sub element. + * @param function the function. + */ + public static void forEach( + T @Nullable [] array, + @Nullable F first, + @Nullable S second, + TripleFunction getElement, + TripleConsumer function) { + if (array == null || array.length < 1) { + return; + } + for (T element : array) { + R subElement = getElement.apply(element, first, second); + function.accept(subElement, first, second); + } + } + + /** + * Find an index of the element in the array using condition. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @return the index of the element or -1. + */ + public static int indexOf( + T @Nullable [] array, + @Nullable F argument, + BiPredicate condition) { + return indexOf(array, argument, condition, 0, array == null ? 0 : array.length); + } + + /** + * Find an index of the element in an array using condition in the range. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @param startIndex the start index. + * @param endIndex the end index. + * @return the index of the element or -1. + */ + public static int indexOf( + T @Nullable [] array, + @Nullable F argument, + BiPredicate condition, + int startIndex, + int endIndex) { + if (array == null || array.length < 1) { + return -1; + } + for (int i = startIndex; i < endIndex; i++) { + if (condition.test(array[i], argument)) { + return i; + } + } + return -1; + } + + /** + * Calculate a count of interesting elements of the array. + * + * @param the type parameter + * @param array the array. + * @param condition the condition. + * @return the count of elements. + */ + public static int count(T @Nullable [] array, Predicate condition) { + if (array == null || array.length < 1) { + return 0; + } + + int count = 0; + + for (T element : array) { + if (condition.test(element)) { + count++; + } + } + + return count; + } + + /** + * Find an element in the array using the condition. + * + * @param the array's element type. + * @param array the array. + * @param condition the condition. + * @return the element or null. + */ + public static @Nullable T findAny(T @Nullable [] array, Predicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + if (condition.test(element)) { + return element; + } + } + + return null; + } + + /** + * Return true if there is at least an element for the condition. + * + * @param the array's element type. + * @param array the array. + * @param condition the condition. + * @return true if there is at least an element for the condition. + */ + public static boolean anyMatch(T @Nullable [] array, Predicate condition) { + return findAny(array, condition) != null; + } + + /** + * Find an element in the array using the condition. + * + * @param the array's element type. + * @param the argument's type. + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @return the element or null. + */ + public static @Nullable T findAny( + T @Nullable [] array, + @Nullable F argument, + BiPredicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + if (condition.test(element, argument)) { + return element; + } + } + + return null; + } + + /** + * Find an element in the array using the condition. + * + * @param the array's element type. + * @param the argument's type. + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @return the element or null. + */ + public static @Nullable T findAnyR( + T @Nullable [] array, + @Nullable F argument, + BiPredicate<@Nullable F, ? super T> condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + if (condition.test(argument, element)) { + return element; + } + } + + return null; + } + + /** + * Return true if there is at least an element for the condition. + * + * @param the array's element type. + * @param the argument's type. + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @return true if there is at least an element for the condition. + */ + public static boolean anyMatchR( + T @Nullable [] array, + @Nullable F argument, + BiPredicate<@Nullable F, ? super T> condition) { + return findAnyR(array, argument, condition) != null; + } + + /** + * Find a sub-element in the array using the function to get a sub-element + the condition. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param getElement the function to get a sub-element. + * @param condition the condition. + * @return the element or null. + */ + public static @Nullable R findAny( + T @Nullable [] array, + @Nullable F argument, + Function getElement, + BiPredicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + R subElement = getElement.apply(element); + if (condition.test(subElement, argument)) { + return subElement; + } + } + + return null; + } + + /** + * Find a sub-element in the array using the function to get a sub-element + conditions. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @param getElement the function to get a sub-element. + * @param secondCond the second cond + * @return the element or null. + */ + public static @Nullable R findAny( + T @Nullable [] array, + @Nullable F argument, + Predicate condition, + Function getElement, + BiPredicate secondCond) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + + if (!condition.test(element)) { + continue; + } + + R subElement = getElement.apply(element); + if (secondCond.test(subElement, argument)) { + return subElement; + } + } + + return null; + } + + /** + * Find an element in the array using the condition. + * + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @return the element or null. + */ + + public static @Nullable T findAny(T @Nullable [] array, int argument, ObjectIntPredicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + if (condition.test(element, argument)) { + return element; + } + } + + return null; + } + + /** + * Find a sub-element in the array using the function to get a sub-element + the condition. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param getElement the function to get a sub-element. + * @param condition the condition. + * @return the element or null. + */ + + public static @Nullable R findAny( + T @Nullable [] array, + int argument, + Function getElement, + ObjectIntPredicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + R subElement = getElement.apply(element); + if (condition.test(subElement, argument)) { + return subElement; + } + } + + return null; + } + + /** + * Find a sub-element in the array using the function to get a sub-element + conditions. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param firstCond the first condition. + * @param getElement the function to get a sub-element. + * @param secondCond the second condition. + * @return the element or null. + */ + + public static @Nullable R findAny( + T @Nullable [] array, + int argument, + Predicate firstCond, + Function getElement, + ObjectIntPredicate secondCond) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + + if (!firstCond.test(element)) { + continue; + } + + R subElement = getElement.apply(element); + + if (secondCond.test(subElement, argument)) { + return subElement; + } + } + + return null; + } + + /** + * Find a sub-element in the array using the function to get a sub-element + conditions. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param firstCond the first condition. + * @param getElement the function to get a sub-element. + * @param secondCond the second condition. + * @return the element or null. + */ + public static @Nullable R findL( + T @Nullable [] array, + long argument, + Predicate firstCond, + Function getElement, + ObjectLongPredicate secondCond) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + + if (!firstCond.test(element)) { + continue; + } + + R subElement = getElement.apply(element); + + if (secondCond.test(subElement, argument)) { + return subElement; + } + } + + return null; + } + + /** + * Find an element in the array using the condition. + * + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param condition the condition. + * @return the element or null. + */ + public static @Nullable T findL( + T @Nullable [] array, + long argument, + ObjectLongPredicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (final T element : array) { + if (condition.test(element, argument)) { + return element; + } + } + + return null; + } + + /** + * Find an element in the array using the condition. + * + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param argument the argument. + * @param getElement the get element + * @param condition the condition. + * @return the element or null. + */ + public static @Nullable R findL( + T @Nullable [] array, + long argument, + Function getElement, + ObjectLongPredicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + R subElement = getElement.apply(element); + if (condition.test(subElement, argument)) { + return subElement; + } + } + + return null; + } + + /** + * Find an element in the array using the condition. + * + * @param the type parameter + * @param the type parameter + * @param the type parameter + * @param array the array. + * @param first the first argument. + * @param second the second argument. + * @param condition the condition. + * @return the element or null. + */ + public static @Nullable T findAny( + T @Nullable [] array, + @Nullable F first, + @Nullable S second, + TriplePredicate condition) { + + if (array == null || array.length < 1) { + return null; + } + + for (T element : array) { + if (condition.test(element, first, second)) { + return element; + } + } + + return null; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(byte @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(byte @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(short @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(short @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(char @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(char @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(int @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(int @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(long @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(long @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(float @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(float @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(double @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(double @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Return true if the array is not null or empty. + * + * @param array the array. + * @return true if the array is not null or empty. + */ + public static boolean isNotEmpty(Object @Nullable [] array) { + return array != null && array.length > 0; + } + + /** + * Return true if the array is null or empty. + * + * @param array the array. + * @return true if the array is null or empty. + */ + public static boolean isEmpty(Object @Nullable [] array) { + return array == null || array.length == 0; + } + + /** + * Convert T array to R array. + * + * @param the source component type. + * @param the mapped element's type. + * @param the result element's type. + * @param source the source array. + * @param mapper the mapper. + * @param resultType the result component type. + * @return the mapped array. + * @since 9.5.0 + */ + public static R @Nullable [] map( + T [] source, + Function mapper, + Class resultType) { + + if (source.length == 0) { + return create(resultType, 0); + } + + R[] resultArray = create(resultType, source.length); + + for (int i = 0; i < source.length; i++) { + resultArray[i] = mapper.apply(source[i]); + } + + return resultArray; + } + + /** + * Convert T array to R array. + * + * @param the source component type. + * @param the mapped element's type. + * @param the result element's type. + * @param source the source array. + * @param mapper the mapper. + * @param def the default result if source array is null. + * @return the mapped array. + * @since 9.5.0 + */ + public static R [] map( + T @Nullable [] source, + Function mapper, + R[] def) { + + if (source == null || source.length == 0) { + return def; + } + + R[] resultArray = create( + def + .getClass() + .getComponentType(), source.length); - builder.append("]"); - return builder.toString(); + for (int i = 0; i < source.length; i++) { + resultArray[i] = mapper.apply(source[i]); } - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @return the string presentation. - */ - public static @NotNull String toString(@NotNull final LongArray array) { + return resultArray; + } - final String className = array.array().getClass().getSimpleName(); - final StringBuilder builder = new StringBuilder(className.substring(0, className.length() - 1)); + /** + * Convert T array to R array if a source array is not null. + * + * @param the source component type. + * @param the mapped element's type. + * @param the result element's type. + * @param source the source array. + * @param mapper the mapper. + * @param resultType the result component type. + * @return the mapped array or null. + * @since 9.3.0 + */ + public static R @Nullable [] mapNullable( + T @Nullable [] source, + Function mapper, + Class resultType) { - for (int i = 0, length = array.size() - 1; i <= length; i++) { - builder.append(String.valueOf(array.get(i))); - if (i == length) break; - builder.append(", "); - } - - builder.append("]"); - return builder.toString(); + if (source == null) { + return null; + } else if (source.length == 0) { + return create(resultType, 0); } - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @return the string presentation. - */ - public static @NotNull String toString(@Nullable int[] array) { - return toString(array, ", ", true, true); + R[] resultArray = create(resultType, source.length); + + for (int i = 0; i < source.length; i++) { + resultArray[i] = mapper.apply(source[i]); } - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @param separator the separator. - * @param needType true if need adding type of array. - * @param needBrackets true if need adding brackets. - * @return the string presentation of the array. - */ - public static @NotNull String toString(@Nullable int[] array, @NotNull final String separator, - final boolean needType, final boolean needBrackets) { + return resultArray; + } - if (array == null) { - array = EMPTY_INT_ARRAY; - } + /** + * Convert long array to int array. + * + * @param source the source array. + * @return the int array. + * @since 9.3.0 + */ + public static int [] longsToInts(long[] source) { - final StringBuilder builder = new StringBuilder(); + if (source.length == 0) { + return ArrayUtils.EMPTY_INT_ARRAY; + } - if (needType) builder.append("int"); - if (needBrackets) builder.append('['); + var resultArray = new int[source.length]; - for (int i = 0, length = array.length - 1; i <= length; i++) { - builder.append(String.valueOf(array[i])); - if (i == length) break; - builder.append(separator); - } + for (int i = 0; i < source.length; i++) { + resultArray[i] = (int) source[i]; + } - if (needBrackets) builder.append(']'); - - return builder.toString(); - } + return resultArray; + } - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @return the string presentation. - */ - public static @NotNull String toString(@Nullable float[] array) { - return toString(array, ", ", true, true); - } - - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @param separator the separator. - * @param needType true if need adding type of array. - * @param needBrackets true if need adding brackets. - * @return the string presentation of the array. - */ - public static @NotNull String toString(@Nullable float[] array, @NotNull final String separator, - final boolean needType, final boolean needBrackets) { - - if (array == null) { - array = EMPTY_FLOAT_ARRAY; - } - - final StringBuilder builder = new StringBuilder(); - - if (needType) builder.append("float"); - if (needBrackets) builder.append('['); - - for (int i = 0, length = array.length - 1; i <= length; i++) { - builder.append(String.valueOf(array[i])); - if (i == length) break; - builder.append(separator); - } - - if (needBrackets) builder.append(']'); - - return builder.toString(); - } - - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @return the string presentation of the array. - */ - public static @NotNull String toString(@Nullable final Object[] array) { - return toString(array, ", ", true, true); - } - - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @param separator the separator. - * @param needType true if need adding type of array. - * @param needBrackets true if need adding brackets. - * @return the string presentation of the array. - */ - public static @NotNull String toString(@Nullable Object[] array, @NotNull final String separator, - final boolean needType, final boolean needBrackets) { - - if (array == null) { - array = EMPTY_OBJECT_ARRAY; - } - - final StringBuilder builder = new StringBuilder(); - - if (needType) builder.append(array.getClass().getSimpleName()); - if (needBrackets) builder.append('['); - - for (int i = 0, length = array.length - 1; i <= length; i++) { - builder.append(String.valueOf(array[i])); - if (i == length) break; - builder.append(separator); - } - - if (needBrackets) builder.append(']'); - - return builder.toString(); - } - - /** - * Move all elements from the source array to the destination array. - * - * @param the type parameter - * @param the type parameter - * @param source the source array. - * @param destination the destination array. - * @param clearSource need clears the source array after moving. - */ - public static void move(@NotNull final Array source, @NotNull final Array destination, - final boolean clearSource) { - if (source.isEmpty()) return; - destination.addAll(source); - if (clearSource) source.clear(); - } - - /** - * Move all elements from the source array to the destination array. - * - * @param the type parameter - * @param the type parameter - * @param source the source array. - * @param destination the destination array. - */ - public static void move(@NotNull final Array source, @NotNull final Array destination) { - move(source, destination, true); - } - - /** - * Add the object to the array in a synchronize block. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param object the object. - */ - public static void addInSynchronizeTo(@NotNull final Array array, @NotNull final V object) { - synchronized (array) { - array.add(object); - } - } - - /** - * Fast remove the object from the array in a synchronize block. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param object the object. - */ - public static void fastRemoveInSynchronizeTo(@NotNull final Array array, - @NotNull final V object) { - synchronized (array) { - array.fastRemove(object); - } - } - - /** - * Apply the function to each element of the array. - * - * @param the type parameter - * @param array the array. - * @param function the function. - */ - public static void forEach(@Nullable final T[] array, @NotNull final Consumer function) { - if (array == null || array.length < 1) return; - for (final T element : array) { - function.accept(element); - } - } - - /** - * Apply the function to each filtered element of the array. - * - * @param the type parameter - * @param array the array. - * @param condition the condition. - * @param function the function. - */ - public static void forEach(@Nullable final T[] array, @NotNull final Predicate condition, - @NotNull final Consumer function) { - if (array == null || array.length < 1) return; - for (final T element : array) { - if (condition.test(element)) { - function.accept(element); - } - } - } - - /** - * Apply the consumer for each element of the array. - * - * @param the type parameter - * @param array the array. - * @param argument the additional argument. - * @param consumer the consumer. - */ - public static void forEach(@Nullable final int[] array, @Nullable final F argument, - @NotNull final IntObjectConsumer consumer) { - if (array == null || array.length < 1) return; - for (final int element : array) { - consumer.accept(element, argument); - } - } - - /** - * Apply the consumer for each element of the array. - * - * @param the type parameter - * @param array the array. - * @param argument the additional argument. - * @param consumer the consumer. - */ - public static void forEach(@Nullable final double[] array, @Nullable final F argument, - @NotNull final DoubleObjectConsumer consumer) { - if (array == null || array.length < 1) return; - for (final double element : array) { - consumer.accept(element, argument); - } - } - - /** - * Apply the consumer for each element of the array. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the additional argument. - * @param consumer the consumer. - */ - public static void forEach(@Nullable final T[] array, @Nullable final F argument, - @NotNull final BiConsumer consumer) { - if (array == null || array.length < 1) return; - for (final T element : array) { - consumer.accept(element, argument); - } - } - - /** - * Handle elements of the array. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the additional argument. - * @param getElement the function to get sub element. - * @param finalFunction the final function. - */ - public static void forEach(@Nullable final T[] array, @Nullable final F argument, - @NotNull final Function getElement, - @NotNull final BiConsumer finalFunction) { - if (array == null || array.length < 1) return; - for (final T element : array) { - final R subElement = getElement.apply(element); - if (subElement != null) finalFunction.accept(subElement, argument); - } - } - - /** - * Apply the function to each filtered element of the array. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the additional argument. - * @param condition the condition. - * @param function the function. - */ - public static void forEach(@Nullable final T[] array, @Nullable final F argument, - @NotNull final Predicate condition, @NotNull final BiConsumer function) { - if (array == null || array.length < 1) return; - for (final T element : array) { - if (condition.test(element)) { - function.accept(element, argument); - } - } - } - - /** - * Apply the function to each filtered element of the array. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the additional argument. - * @param condition the condition. - * @param getElement the function to get sub element. - * @param finalFunction the final function. - */ - public static void forEach(@Nullable final T[] array, @Nullable final F argument, - @NotNull final Predicate condition, - @NotNull final Function getElement, - @NotNull final BiConsumer finalFunction) { - if (array == null || array.length < 1) return; - for (final T element : array) { - if (!condition.test(element)) continue; - final R subElement = getElement.apply(element); - finalFunction.accept(subElement, argument); - } - } - - /** - * Apply the function to each element of the array. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param first the first argument. - * @param second the second argument. - * @param function the function. - */ - public static void forEach(@Nullable final T[] array, @Nullable final F first, @Nullable final S second, - @NotNull final TripleConsumer function) { - if (array == null || array.length < 1) return; - for (final T element : array) { - function.accept(element, first, second); - } - } - - /** - * Apply the function to each sub-element of the array. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param first the first argument. - * @param second the second argument. - * @param getElement the function to get sub element. - * @param function the function. - */ - public static void forEach(@Nullable final T[] array, @Nullable final F first, - @Nullable final S second, - @NotNull final TripleFunction getElement, - @NotNull final TripleConsumer function) { - if (array == null || array.length < 1) return; - for (final T element : array) { - final R subElement = getElement.apply(element, first, second); - function.accept(subElement, first, second); - } - } - - /** - * Find an index of the element in the array using condition. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @return the index of the element or -1. - */ - public static int indexOf(@Nullable final T[] array, @Nullable final F argument, - @NotNull final BiPredicate condition) { - return indexOf(array, argument, condition, 0, array == null ? 0 : array.length); - } - - /** - * Find an index of the element in an array using condition in the range. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @param startIndex the start index. - * @param endIndex the end index. - * @return the index of the element or -1. - */ - public static int indexOf(@Nullable final T[] array, @Nullable final F argument, - @NotNull final BiPredicate condition, final int startIndex, - final int endIndex) { - if (array == null || array.length < 1) return -1; - for (int i = startIndex; i < endIndex; i++) { - if (condition.test(array[i], argument)) return i; - } - return -1; - } - - /** - * Calculate a count of interesting elements of the array. - * - * @param the type parameter - * @param array the array. - * @param condition the condition. - * @return the count of elements. - */ - public static int count(@Nullable final T[] array, @NotNull final Predicate condition) { - if (array == null || array.length < 1) return 0; - - int count = 0; - - for (final T element : array) { - if (condition.test(element)) { - count++; - } - } - - return count; - } - - /** - * Find an element in the array using the condition. - * - * @param the array's element type. - * @param array the array. - * @param condition the condition. - * @return the element or null. - */ - public static @Nullable T findAny(@Nullable T[] array, @NotNull Predicate condition) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - if (condition.test(element)) { - return element; - } - } - - return null; - } - - /** - * Return true if there is at least an element for the condition. - * - * @param the array's element type. - * @param array the array. - * @param condition the condition. - * @return true if there is at least an element for the condition. - */ - public static boolean anyMatch(@Nullable T[] array, @NotNull Predicate condition) { - return findAny(array, condition) != null; - } - - /** - * Find an element in the array using the condition. - * - * @param the array's element type. - * @param the argument's type. - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @return the element or null. - */ - public static @Nullable T findAny( - @Nullable T[] array, - @Nullable F argument, - @NotNull BiPredicate condition - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - if (condition.test(element, argument)) { - return element; - } - } - - return null; - } - - /** - * Find an element in the array using the condition. - * - * @param the array's element type. - * @param the argument's type. - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @return the element or null. - */ - public static @Nullable T findAnyR( - @Nullable T[] array, - @Nullable F argument, - @NotNull BiPredicate condition - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - if (condition.test(argument, element)) { - return element; - } - } - - return null; - } - - /** - * Return true if there is at least an element for the condition. - * - * @param the array's element type. - * @param the argument's type. - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @return true if there is at least an element for the condition. - */ - public static boolean anyMatchR( - @Nullable T[] array, - @Nullable F argument, - @NotNull BiPredicate condition - ) { - return findAnyR(array, argument, condition) != null; - } - - /** - * Find a sub-element in the array using the function to get a sub-element + the condition. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param getElement the function to get a sub-element. - * @param condition the condition. - * @return the element or null. - */ - public static @Nullable R findAny( - @Nullable T[] array, - @Nullable F argument, - @NotNull Function getElement, - @NotNull BiPredicate condition - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - - R subElement = getElement.apply(element); - - if (condition.test(subElement, argument)) { - return subElement; - } - } - - return null; - } - - /** - * Find a sub-element in the array using the function to get a sub-element + conditions. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @param getElement the function to get a sub-element. - * @param secondCond the second cond - * @return the element or null. - */ - public static @Nullable R findAny( - @Nullable T[] array, - @Nullable F argument, - @NotNull Predicate condition, - @NotNull Function getElement, - @NotNull BiPredicate secondCond - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - - if (!condition.test(element)) { - continue; - } - - R subElement = getElement.apply(element); - - if (secondCond.test(subElement, argument)) { - return subElement; - } - } - - return null; - } - - /** - * Find an element in the array using the condition. - * - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @return the element or null. - */ - - public static @Nullable T findAny(@Nullable T[] array, int argument, @NotNull ObjectIntPredicate condition) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - if (condition.test(element, argument)) { - return element; - } - } - - return null; - } - - /** - * Find a sub-element in the array using the function to get a sub-element + the condition. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param getElement the function to get a sub-element. - * @param condition the condition. - * @return the element or null. - */ - - public static @Nullable R findAny( - @Nullable T[] array, - int argument, - @NotNull Function getElement, - @NotNull ObjectIntPredicate condition - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - R subElement = getElement.apply(element); - if (condition.test(subElement, argument)) { - return subElement; - } - } - - return null; - } - - /** - * Find a sub-element in the array using the function to get a sub-element + conditions. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param firstCond the first condition. - * @param getElement the function to get a sub-element. - * @param secondCond the second condition. - * @return the element or null. - */ - - public static @Nullable R findAny( - @Nullable T[] array, - int argument, - @NotNull Predicate firstCond, - @NotNull Function getElement, - @NotNull ObjectIntPredicate secondCond - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - - if (!firstCond.test(element)) { - continue; - } - - R subElement = getElement.apply(element); - - if (secondCond.test(subElement, argument)) { - return subElement; - } - } - - return null; - } - - /** - * Find a sub-element in the array using the function to get a sub-element + conditions. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param firstCond the first condition. - * @param getElement the function to get a sub-element. - * @param secondCond the second condition. - * @return the element or null. - */ - public static @Nullable R findL( - @Nullable T[] array, - long argument, - @NotNull Predicate firstCond, - @NotNull Function getElement, - @NotNull ObjectLongPredicate secondCond - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - - if (!firstCond.test(element)) { - continue; - } - - R subElement = getElement.apply(element); - - if (secondCond.test(subElement, argument)) { - return subElement; - } - } - - return null; - } - - /** - * Find an element in the array using the condition. - * - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param condition the condition. - * @return the element or null. - */ - public static @Nullable T findL(@Nullable final T[] array, final long argument, - @NotNull final ObjectLongPredicate condition) { - - if (array == null || array.length < 1) { - return null; - } - - for (final T element : array) { - if (condition.test(element, argument)) return element; - } - - return null; - } - - /** - * Find an element in the array using the condition. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param argument the argument. - * @param getElement the get element - * @param condition the condition. - * @return the element or null. - */ - public static @Nullable R findL(@Nullable final T[] array, final long argument, - @NotNull final Function getElement, - @NotNull final ObjectLongPredicate condition) { - - if (array == null || array.length < 1) { - return null; - } - - for (final T element : array) { - final R subElement = getElement.apply(element); - if (condition.test(subElement, argument)) { - return subElement; - } - } - - return null; - } - - /** - * Find an element in the array using the condition. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param first the first argument. - * @param second the second argument. - * @param condition the condition. - * @return the element or null. - */ - public static @Nullable T findAny( - @Nullable T[] array, - @Nullable F first, - @Nullable S second, - @NotNull TriplePredicate condition - ) { - - if (array == null || array.length < 1) { - return null; - } - - for (T element : array) { - if (condition.test(element, first, second)) { - return element; - } - } - - return null; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable byte[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable byte[] array) { - return array == null || array.length == 0; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable short[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable short[] array) { - return array == null || array.length == 0; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable char[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable char[] array) { - return array == null || array.length == 0; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable int[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable int[] array) { - return array == null || array.length == 0; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable long[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable long[] array) { - return array == null || array.length == 0; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable float[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable float[] array) { - return array == null || array.length == 0; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable double[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable double[] array) { - return array == null || array.length == 0; - } - - /** - * Return true if the array is not null or empty. - * - * @param array the array. - * @return true if the array is not null or empty. - */ - public static boolean isNotEmpty(@Nullable Object[] array) { - return array != null && array.length > 0; - } - - /** - * Return true if the array is null or empty. - * - * @param array the array. - * @return true if the array is null or empty. - */ - public static boolean isEmpty(@Nullable Object[] array) { - return array == null || array.length == 0; - } - - /** - * Convert T array to R array. - * - * @param the source component type. - * @param the mapped element's type. - * @param the result element's type. - * @param source the source array. - * @param mapper the mapper. - * @param resultType the result component type. - * @return the mapped array. - * @since 9.5.0 - */ - public static R @Nullable [] map( - T @NotNull [] source, - @NotNull Function<@NotNull T, @NotNull M> mapper, - @NotNull Class resultType - ) { - - if (source.length == 0) { - return create(resultType, 0); - } - - R[] resultArray = create(resultType, source.length); - - for (int i = 0; i < source.length; i++) { - resultArray[i] = mapper.apply(source[i]); - } - - return resultArray; - } - - /** - * Convert T array to R array. - * - * @param the source component type. - * @param the mapped element's type. - * @param the result element's type. - * @param source the source array. - * @param mapper the mapper. - * @param def the default result if source array is null. - * @return the mapped array. - * @since 9.5.0 - */ - public static R @NotNull [] map( - T @Nullable [] source, - @NotNull Function<@NotNull T, @NotNull M> mapper, - @NotNull R[] def - ) { - - if (source == null || source.length == 0) { - return def; - } - - R[] resultArray = create(def.getClass().getComponentType(), source.length); - - for (int i = 0; i < source.length; i++) { - resultArray[i] = mapper.apply(source[i]); - } - - return resultArray; - } - - /** - * Convert T array to R array if a source array is not null. - * - * @param the source component type. - * @param the mapped element's type. - * @param the result element's type. - * @param source the source array. - * @param mapper the mapper. - * @param resultType the result component type. - * @return the mapped array or null. - * @since 9.3.0 - */ - public static R @Nullable [] mapNullable( - T @Nullable [] source, - @NotNull Function<@NotNull T, @NotNull M> mapper, - @NotNull Class resultType - ) { - - if (source == null) { - return null; - } else if (source.length == 0) { - return create(resultType, 0); - } - - R[] resultArray = create(resultType, source.length); - - for (int i = 0; i < source.length; i++) { - resultArray[i] = mapper.apply(source[i]); - } - - return resultArray; - } - - /** - * Convert long array to int array. - * - * @param source the source array. - * @return the int array. - * @since 9.3.0 - */ - public static int @NotNull [] longsToInts(long @NotNull [] source) { - - if (source.length == 0) { - return ArrayUtils.EMPTY_INT_ARRAY; - } - - var resultArray = new int[source.length]; - - for (int i = 0; i < source.length; i++) { - resultArray[i] = (int) source[i]; - } - - return resultArray; - } - - private ArrayUtils() { - throw new RuntimeException(); - } + private ArrayUtils() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/AsyncUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/AsyncUtils.java index f7cee55c..31d4a15b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/AsyncUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/AsyncUtils.java @@ -1,25 +1,26 @@ package javasabr.rlib.common.util; import java.util.concurrent.CompletionException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr */ +@NullMarked public class AsyncUtils { - public static @Nullable T skip(@NotNull Throwable throwable) { - return null; - } + public static @Nullable T skip(Throwable throwable) { + return null; + } - public static @Nullable T continueCompletableStage(@Nullable T result, @Nullable Throwable throwable) { - if (throwable instanceof RuntimeException) { - throw (RuntimeException) throwable; - } else if (throwable != null) { - throw new CompletionException(throwable); - } else { - return result; - } + public static @Nullable T continueCompletableStage(@Nullable T result, @Nullable Throwable throwable) { + if (throwable instanceof RuntimeException) { + throw (RuntimeException) throwable; + } else if (throwable != null) { + throw new CompletionException(throwable); + } else { + return result; } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/BufferUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/BufferUtils.java index 6c3a1af1..4b278589 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/BufferUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/BufferUtils.java @@ -10,90 +10,90 @@ import java.util.EnumSet; import java.util.function.Consumer; import lombok.experimental.UtilityClass; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The utility class. * * @author JavaSaBr */ +@NullMarked @UtilityClass public class BufferUtils { - private static final EnumSet FILE_CHANNEL_OPTS = EnumSet.of( - StandardOpenOption.READ, - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.DELETE_ON_CLOSE - ); + private static final EnumSet FILE_CHANNEL_OPTS = EnumSet.of( + StandardOpenOption.READ, + StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.DELETE_ON_CLOSE); - /** - * Load a part of data from a source buffer to a target buffer which can be to get into the target buffer's size. - * - * @param target the target buffer. - * @param source the source buffer - * @return the target buffer. - */ - public @NotNull ByteBuffer loadFrom(@NotNull ByteBuffer source, @NotNull ByteBuffer target) { + /** + * Load a part of data from a source buffer to a target buffer which can be to get into the target buffer's size. + * + * @param target the target buffer. + * @param source the source buffer + * @return the target buffer. + */ + public ByteBuffer loadFrom(ByteBuffer source, ByteBuffer target) { - var prevLimit = source.limit(); - try { + var prevLimit = source.limit(); + try { - target.clear(); + target.clear(); - var skip = source.remaining() - target.remaining(); + var skip = source.remaining() - target.remaining(); - if (skip > 0) { - source.limit(prevLimit - skip); - } + if (skip > 0) { + source.limit(prevLimit - skip); + } - target.put(source); - target.flip(); + target.put(source); + target.flip(); - } finally { - source.limit(prevLimit); - } - - return target; + } finally { + source.limit(prevLimit); } - /** - * Allocate a new read/write mapped byte buffer. - * - * @param size the byte buffer's size. - * @return the new mapped byte buffer. - */ - public @NotNull MappedByteBuffer allocateRWMappedByteBuffer(int size) { - try { - - var tempFile = Files.createTempFile("rlib_common_util_", "_buffer_utils.bin"); + return target; + } - try (var fileChannel = (FileChannel) Files.newByteChannel(tempFile, FILE_CHANNEL_OPTS)) { - return fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, size); - } + /** + * Allocate a new read/write mapped byte buffer. + * + * @param size the byte buffer's size. + * @return the new mapped byte buffer. + */ + public MappedByteBuffer allocateRWMappedByteBuffer(int size) { + try { - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } + var tempFile = Files.createTempFile("rlib_common_util_", "_buffer_utils.bin"); - public @NotNull ByteBuffer putToAndFlip(@NotNull ByteBuffer buffer, @NotNull ByteBuffer additional) { - return buffer - .limit(buffer.capacity()) - .put(additional) - .flip(); - } + try (var fileChannel = (FileChannel) Files.newByteChannel(tempFile, FILE_CHANNEL_OPTS)) { + return fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, size); + } - /** - * Create a new byte buffer with with writing some data inside the consumer and to flip in the result. - * - * @param size the buffer's size. - * @param consumer the consumer to write data. - * @return the flipped buffer. - */ - public @NotNull ByteBuffer prepareBuffer(int size, @NotNull Consumer<@NotNull ByteBuffer> consumer) { - var buffer = ByteBuffer.allocate(size); - consumer.accept(buffer); - return buffer.flip(); + } catch (IOException e) { + throw new UncheckedIOException(e); } + } + + public ByteBuffer putToAndFlip(ByteBuffer buffer, ByteBuffer additional) { + return buffer + .limit(buffer.capacity()) + .put(additional) + .flip(); + } + + /** + * Create a new byte buffer with with writing some data inside the consumer and to flip in the result. + * + * @param size the buffer's size. + * @param consumer the consumer to write data. + * @return the flipped buffer. + */ + public ByteBuffer prepareBuffer(int size, Consumer consumer) { + var buffer = ByteBuffer.allocate(size); + consumer.accept(buffer); + return buffer.flip(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ClassUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ClassUtils.java index abf7b72c..54763194 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ClassUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ClassUtils.java @@ -6,247 +6,252 @@ import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class with utility methods. * * @author JavaSaBr */ +@NullMarked public final class ClassUtils { - /** - * Try to find a class by name. - * - * @param name the name of a class. - * @param the type of a class. - * @return the class or null. - * @since 9.8.0 - */ - public static @Nullable Class tryGetClass(@NotNull String name) { - try { - return unsafeCast(forName(name)); - } catch (ClassNotFoundException e) { - LoggerManager.getDefaultLogger().warning(e); - return null; - } + /** + * Try to find a class by name. + * + * @param name the name of a class. + * @param the type of a class. + * @return the class or null. + * @since 9.8.0 + */ + public static @Nullable Class tryGetClass(String name) { + try { + return unsafeCast(forName(name)); + } catch (ClassNotFoundException e) { + LoggerManager + .getDefaultLogger() + .warning(e); + return null; } + } - /** - * Find a class by name. - * - * @param name the name of a class. - * @param the type of a class. - * @return the class. - * @throws RuntimeException if the class is not found. - */ - public static @NotNull Class getClass(@NotNull String name) { - try { - return unsafeNNCast(forName(name)); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } + /** + * Find a class by name. + * + * @param name the name of a class. + * @param the type of a class. + * @return the class. + * @throws RuntimeException if the class is not found. + */ + public static Class getClass(String name) { + try { + return unsafeNNCast(forName(name)); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); } + } - /** - * Try to find a constructor of a class by types of arguments. - * - * @param cs the class. - * @param classes the types of arguments. - * @param the type of a class. - * @return the constructor or null. - * @since 9.8.0 - */ - public static @Nullable Constructor tryGetConstructor(@NotNull Class cs, @Nullable Class... classes) { - try { - return unsafeCast(cs.getConstructor(classes)); - } catch (NoSuchMethodException | SecurityException e) { - LoggerManager.getDefaultLogger().warning(e); - return null; - } + /** + * Try to find a constructor of a class by types of arguments. + * + * @param cs the class. + * @param classes the types of arguments. + * @param the type of a class. + * @return the constructor or null. + * @since 9.8.0 + */ + public static @Nullable Constructor tryGetConstructor(Class cs, @Nullable Class... classes) { + try { + return unsafeCast(cs.getConstructor(classes)); + } catch (NoSuchMethodException | SecurityException e) { + LoggerManager + .getDefaultLogger() + .warning(e); + return null; } + } - /** - * Try to find a constructor of a class by types of arguments. - * - * @param className the class name. - * @param classes the types of arguments. - * @param the type of a class. - * @return the constructor or null. - * @since 9.8.0 - */ - public static @Nullable Constructor tryGetConstructor( - @NotNull String className, - @NotNull Class... classes - ) { - try { - return unsafeCast(forName(className).getConstructor(classes)); - } catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) { - LoggerManager.getDefaultLogger().warning(e); - return null; - } + /** + * Try to find a constructor of a class by types of arguments. + * + * @param className the class name. + * @param classes the types of arguments. + * @param the type of a class. + * @return the constructor or null. + * @since 9.8.0 + */ + public static @Nullable Constructor tryGetConstructor(String className, Class... classes) { + try { + return unsafeCast(forName(className).getConstructor(classes)); + } catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) { + LoggerManager + .getDefaultLogger() + .warning(e); + return null; } + } - /** - * Get a constructor of the class by types of arguments. - * - * @param cs the class. - * @param classes the types of arguments. - * @param the type of a class. - * @return the constructor. - * @throws RuntimeException if the constructor is not available. - */ - public static @NotNull Constructor getConstructor(@NotNull Class cs, @Nullable Class... classes) { - try { - return unsafeNNCast(cs.getConstructor(classes)); - } catch (NoSuchMethodException | SecurityException e) { - throw new RuntimeException(e); - } + /** + * Get a constructor of the class by types of arguments. + * + * @param cs the class. + * @param classes the types of arguments. + * @param the type of a class. + * @return the constructor. + * @throws RuntimeException if the constructor is not available. + */ + public static Constructor getConstructor(Class cs, @Nullable Class... classes) { + try { + return unsafeNNCast(cs.getConstructor(classes)); + } catch (NoSuchMethodException | SecurityException e) { + throw new RuntimeException(e); } + } - /** - * Check of existing a constructor in a class. - * - * @param cs the class. - * @param classes the types of arguments. - * @return true if this class has constructor wth the arguments. - */ - public static boolean hasConstructor(@NotNull Class cs, @NotNull Class... classes) { - - for (var constructor : cs.getConstructors()) { - if (Arrays.equals(constructor.getParameterTypes(), classes)) { - return true; - } - } - - return false; - } + /** + * Check of existing a constructor in a class. + * + * @param cs the class. + * @param classes the types of arguments. + * @return true if this class has constructor wth the arguments. + */ + public static boolean hasConstructor(Class cs, Class... classes) { - /** - * Check of existing an empty constructor in the class. - * - * @param cs the class. - * @return true if this class has empty constructor. - */ - public static boolean hasConstructor(@NotNull Class cs) { - - for (var constructor : cs.getConstructors()) { - if (constructor.getParameterCount() == 0) { - return true; - } - } - - return false; + for (var constructor : cs.getConstructors()) { + if (Arrays.equals(constructor.getParameterTypes(), classes)) { + return true; + } } - /** - * Create a new instance of a class. - * - * @param cs the class. - * @param the type of a class. - * @return the new instance. - */ - public static @NotNull T newInstance(@NotNull Class cs) { - try { - return unsafeNNCast(cs.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } + return false; + } - /** - * Create a new instance of a class using a constructor. - * - * @param constructor the constructor. - * @param objects the arguments. - * @param the type of a class. - * @return the new instance. - */ - public static @NotNull T newInstance(@NotNull Constructor constructor, @NotNull Object... objects) { - try { - return unsafeNNCast(constructor.newInstance(objects)); - } catch (InvocationTargetException e) { - throw new RuntimeException(e.getTargetException()); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { - throw new RuntimeException(e); - } - } + /** + * Check of existing an empty constructor in the class. + * + * @param cs the class. + * @return true if this class has empty constructor. + */ + public static boolean hasConstructor(Class cs) { - /** - * Create a new instance of a class. - * - * @param className the class name. - * @param the type of a class. - * @return the new instance. - */ - public static @NotNull T newInstance(@NotNull String className) { - try { - return unsafeNNCast(forName(className).newInstance()); - } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { - throw new RuntimeException(e); - } + for (var constructor : cs.getConstructors()) { + if (constructor.getParameterCount() == 0) { + return true; + } } - /** - * Unsafe cast of an object to expected type. - * - * @param object the object. - * @param the expected type. - * @return the casted object. - */ - public static @Nullable T unsafeCast(@Nullable Object object) { - return (T) object; - } + return false; + } - /** - * Unsafe cast of an object to expected type. - * - * @param object the object. - * @param the expected type. - * @return the casted object. - */ - public static @NotNull T unsafeNNCast(@NotNull Object object) { - return (T) object; + /** + * Create a new instance of a class. + * + * @param cs the class. + * @param the type of a class. + * @return the new instance. + */ + public static T newInstance(Class cs) { + try { + return unsafeNNCast(cs.getDeclaredConstructor().newInstance()); + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + throw new RuntimeException(e); } + } - /** - * Unsafe cast of an object to some type. - * - * @param type the target type. - * @param object the object. - * @param the target type. - * @return the casted object. - */ - public static @Nullable T unsafeCast(@NotNull Class type, @Nullable Object object) { - return type.cast(object); + /** + * Create a new instance of a class using a constructor. + * + * @param constructor the constructor. + * @param objects the arguments. + * @param the type of a class. + * @return the new instance. + */ + public static T newInstance(Constructor constructor, Object... objects) { + try { + return unsafeNNCast(constructor.newInstance(objects)); + } catch (InvocationTargetException e) { + throw new RuntimeException(e.getTargetException()); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { + throw new RuntimeException(e); } + } - /** - * Safe cast of an object to a type. - * - * @param type the target type. - * @param object the object. - * @param the target type. - * @return the casted object or null. - */ - public static @Nullable T cast(@NotNull Class type, @Nullable Object object) { - return type.isInstance(object) ? type.cast(object) : null; + /** + * Create a new instance of a class. + * + * @param className the class name. + * @param the type of a class. + * @return the new instance. + */ + public static T newInstance(String className) { + try { + return unsafeNNCast(forName(className).getDeclaredConstructor().newInstance()); + } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | + InvocationTargetException e) { + throw new RuntimeException(e); } + } - /** - * Safe cast of a not null object to some type. - * - * @param type the target type. - * @param object the object. - * @param the target type. - * @return the casted object. - */ - public static @NotNull T nnCast(@NotNull Class type, @NotNull Object object) { - return type.cast(object); - } + /** + * Unsafe cast of an object to expected type. + * + * @param object the object. + * @param the expected type. + * @return the casted object. + */ + public static @Nullable T unsafeCast(@Nullable Object object) { + return (T) object; + } - private ClassUtils() { - throw new RuntimeException(); - } + /** + * Unsafe cast of an object to expected type. + * + * @param object the object. + * @param the expected type. + * @return the casted object. + */ + public static T unsafeNNCast(Object object) { + return (T) object; + } + + /** + * Unsafe cast of an object to some type. + * + * @param type the target type. + * @param object the object. + * @param the target type. + * @return the casted object. + */ + public static @Nullable T unsafeCast(Class type, @Nullable Object object) { + return type.cast(object); + } + + /** + * Safe cast of an object to a type. + * + * @param type the target type. + * @param object the object. + * @param the target type. + * @return the casted object or null. + */ + public static @Nullable T cast(Class type, @Nullable Object object) { + return type.isInstance(object) ? type.cast(object) : null; + } + + /** + * Safe cast of a not null object to some type. + * + * @param type the target type. + * @param object the object. + * @param the target type. + * @return the casted object. + */ + public static T nnCast(Class type, Object object) { + return type.cast(object); + } + + private ClassUtils() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/Copyable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/Copyable.java index 0817426d..e60fef60 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/Copyable.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/Copyable.java @@ -8,10 +8,10 @@ */ public interface Copyable { - /** - * Create a new copy of this object. - * - * @return the new copy of this object. - */ - T copy(); + /** + * Create a new copy of this object. + * + * @return the new copy of this object. + */ + T copy(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/CycleBuffer.java b/rlib-common/src/main/java/javasabr/rlib/common/util/CycleBuffer.java index 979f464a..a14333e0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/CycleBuffer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/CycleBuffer.java @@ -2,8 +2,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of cycle buffer of some objects. @@ -11,67 +11,75 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public final class CycleBuffer { - /** - * The array with buffered objects. - */ - @NotNull - private final T[] buffer; + /** + * The array with buffered objects. + */ + private final T[] buffer; - /** - * The handler of getting object from buffer. - */ - @Nullable - private final Consumer handler; + /** + * The handler of getting object from buffer. + */ + private final @Nullable Consumer handler; - /** - * The index of next object. - */ - private int order; + /** + * The index of next object. + */ + private int order; - /** - * Instantiates a new Cycle buffer. - * - * @param type the type - * @param size the size - * @param factory the factory - */ - public CycleBuffer(@NotNull final Class type, final int size, @NotNull final Supplier factory) { - this(type, size, factory, null); - } - - /** - * Instantiates a new Cycle buffer. - * - * @param type the type - * @param size the size - * @param factory the factory - * @param handler the handler - */ - public CycleBuffer(@NotNull final Class type, final int size, @NotNull final Supplier factory, - @Nullable final Consumer handler) { + /** + * Instantiates a new Cycle buffer. + * + * @param type the type + * @param size the size + * @param factory the factory + */ + public CycleBuffer(final Class type, final int size, final Supplier factory) { + this(type, size, factory, null); + } - if (size < 2) throw new RuntimeException("size is less to 2."); + /** + * Instantiates a new Cycle buffer. + * + * @param type the type + * @param size the size + * @param factory the factory + * @param handler the handler + */ + public CycleBuffer( + Class type, + int size, + Supplier factory, + @Nullable Consumer handler) { - this.buffer = ArrayUtils.create(type, size); + if (size < 2) { + throw new RuntimeException("size is less to 2."); + } - for (int i = 0; i < buffer.length; i++) { - buffer[i] = factory.get(); - } + this.buffer = ArrayUtils.create(type, size); - this.handler = handler; + for (int i = 0; i < buffer.length; i++) { + buffer[i] = factory.get(); } - /** - * Get a next free object. - * - * @return the next free object. - */ - public T next() { - if (order >= buffer.length) order = 0; - final T result = buffer[order++]; - if (handler != null) handler.accept(result); - return result; + this.handler = handler; + } + + /** + * Get a next free object. + * + * @return the next free object. + */ + public T next() { + if (order >= buffer.length) { + order = 0; + } + final T result = buffer[order++]; + if (handler != null) { + handler.accept(result); } + return result; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/DateUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/DateUtils.java index 0a5c8ec1..b96f3a7f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/DateUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/DateUtils.java @@ -8,90 +8,86 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class with utility methods to work with dates and times. * * @author JavaSaBr */ +@NullMarked public class DateUtils { - private static final DateTimeFormatter TIMESTAMP_FORMATTER = - DateTimeFormatter.ofPattern("HH:mm:ss:SSS"); + private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss:SSS"); - /** - * Format a time to a string by pattern HH:mm:ss:SSS - * - * @param timestamp the timestamp. - * @return the string presentation. - * @since 9.3.0 - */ - public static @NotNull String formatShortTimestamp(long timestamp) { - return TIMESTAMP_FORMATTER.format(LocalDateTime.ofInstant( - Instant.ofEpochMilli(timestamp), - ZoneOffset.UTC - )); - } + /** + * Format a time to a string by pattern HH:mm:ss:SSS + * + * @param timestamp the timestamp. + * @return the string presentation. + * @since 9.3.0 + */ + public static String formatShortTimestamp(long timestamp) { + return TIMESTAMP_FORMATTER.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC)); + } - /** - * Format some temporal accessor to a string by pattern HH:mm:ss:SSS - * - * @param temporal the timestamp. - * @return the string presentation. - * @since 9.3.0 - */ - public static @NotNull String formatShortTimestamp(@NotNull TemporalAccessor temporal) { - return TIMESTAMP_FORMATTER.format(temporal); - } + /** + * Format some temporal accessor to a string by pattern HH:mm:ss:SSS + * + * @param temporal the timestamp. + * @return the string presentation. + * @since 9.3.0 + */ + public static String formatShortTimestamp(TemporalAccessor temporal) { + return TIMESTAMP_FORMATTER.format(temporal); + } - /** - * Convert a date string to a {@link LocalDate}. - * - * @param string the string to convert. - * @return the local date or null if this string cannot be converted. - * @since 9.3.0 - */ - public static @Nullable LocalDate toLocalDate(@Nullable String string) { - if (StringUtils.isEmpty(string)) { - return null; - } else { - return Utils.tryGetAndConvert(string, ISO_LOCAL_DATE::parse, LocalDate::from); - } + /** + * Convert a date string to a {@link LocalDate}. + * + * @param string the string to convert. + * @return the local date or null if this string cannot be converted. + * @since 9.3.0 + */ + public static @Nullable LocalDate toLocalDate(@Nullable String string) { + if (StringUtils.isEmpty(string)) { + return null; + } else { + return Utils.tryGetAndConvert(string, ISO_LOCAL_DATE::parse, LocalDate::from); } + } - /** - * Convert a local date to a string by ISO_LOCAL_DATE formatter. - * - * @param localDate the local date. - * @return the string presentation of the local date or null. - * @since 9.3.0 - */ - public static @Nullable String toString(@Nullable LocalDate localDate) { - if (localDate == null) { - return null; - } else { - return ISO_LOCAL_DATE.format(localDate); - } + /** + * Convert a local date to a string by ISO_LOCAL_DATE formatter. + * + * @param localDate the local date. + * @return the string presentation of the local date or null. + * @since 9.3.0 + */ + public static @Nullable String toString(@Nullable LocalDate localDate) { + if (localDate == null) { + return null; + } else { + return ISO_LOCAL_DATE.format(localDate); } + } - /** - * Convert a temporal accessor to a string by passed formatter. - * - * @param temporalAccessor the temporal accessor. - * @param formatter the formatter. - * @return the string presentation or null. - * @since 9.3.0 - */ - public static @Nullable String toString( - @Nullable TemporalAccessor temporalAccessor, - @NotNull DateTimeFormatter formatter - ) { - if (temporalAccessor == null) { - return null; - } else { - return formatter.format(temporalAccessor); - } + /** + * Convert a temporal accessor to a string by passed formatter. + * + * @param temporalAccessor the temporal accessor. + * @param formatter the formatter. + * @return the string presentation or null. + * @since 9.3.0 + */ + public static @Nullable String toString( + @Nullable TemporalAccessor temporalAccessor, + DateTimeFormatter formatter) { + if (temporalAccessor == null) { + return null; + } else { + return formatter.format(temporalAccessor); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ExtMath.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ExtMath.java index 18d00505..628849b2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ExtMath.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ExtMath.java @@ -1,367 +1,368 @@ package javasabr.rlib.common.util; import javasabr.rlib.common.geom.Vector3f; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The utility class. * * @author JavaSaBr */ +@NullMarked public final class ExtMath { - public static final Float ZERO_FLOAT = 0F; - public static final Double ZERO_DOUBLE = 0D; - public static final Integer ZERO_INTEGER = 0; - public static final Long ZERO_LONG = 0L; - - /** - * The value PI as a float. (180 degrees). - */ - public static final float PI = (float) Math.PI; - - /** - * The value PI/2 as a float. (90 degrees) - */ - public static final float HALF_PI = 0.5f * PI; - - public static final double EPSILON = 1.40129846432482E-45; - - /** - * Return the arc cosine of a value.
Special cases:
  • If value is smaller than -1, then the result is PI. - *
  • If the argument is greater than 1, then the result is 0.
- * - * @param value The value to arc cosine. - * @return The angle, in radians. - * @see java.lang.Math#acos(double) java.lang.Math#acos(double) - */ - public static float acos(float value) { - - if (-1.0F < value) { - if (value < 1.0f) { - return (float) Math.acos(value); - } - return 0.0F; - } - - return PI; + public static final Float ZERO_FLOAT = 0F; + public static final Double ZERO_DOUBLE = 0D; + public static final Integer ZERO_INTEGER = 0; + public static final Long ZERO_LONG = 0L; + + /** + * The value PI as a float. (180 degrees). + */ + public static final float PI = (float) Math.PI; + + /** + * The value PI/2 as a float. (90 degrees) + */ + public static final float HALF_PI = 0.5f * PI; + + public static final double EPSILON = 1.40129846432482E-45; + + /** + * Return the arc cosine of a value.
Special cases:
  • If value is smaller than -1, then the result is PI. + *
  • If the argument is greater than 1, then the result is 0.
+ * + * @param value The value to arc cosine. + * @return The angle, in radians. + * @see java.lang.Math#acos(double) java.lang.Math#acos(double) + */ + public static float acos(float value) { + + if (-1.0F < value) { + if (value < 1.0f) { + return (float) Math.acos(value); + } + return 0.0F; } - /** - * Return the arc sine of a value.
Special cases:
  • If value is smaller than -1, then the result is - * -HALF_PI.
  • If the argument is greater than 1, then the result is HALF_PI.
- * - * @param value The value to arc sine. - * @return the angle in radians. - * @see java.lang.Math#asin(double) java.lang.Math#asin(double) - */ - public static float asin(float value) { - - if (-1.0F < value) { - if (value < 1.0F) { - return (float) Math.asin(value); - } - - return HALF_PI; - } - - return -HALF_PI; + return PI; + } + + /** + * Return the arc sine of a value.
Special cases:
  • If value is smaller than -1, then the result is + * -HALF_PI.
  • If the argument is greater than 1, then the result is HALF_PI.
+ * + * @param value The value to arc sine. + * @return the angle in radians. + * @see java.lang.Math#asin(double) java.lang.Math#asin(double) + */ + public static float asin(float value) { + + if (-1.0F < value) { + if (value < 1.0F) { + return (float) Math.asin(value); + } + + return HALF_PI; } - /** - * A direct call to Math.atan2. - * - * @param y the y - * @param x the x - * @return Math.atan2(y, x) float - * @see java.lang.Math#atan2(double, double) java.lang.Math#atan2(double, double) - */ - public static float atan2(float y, float x) { - return (float) Math.atan2(y, x); + return -HALF_PI; + } + + /** + * A direct call to Math.atan2. + * + * @param y the y + * @param x the x + * @return Math.atan2(y, x) float + * @see java.lang.Math#atan2(double, double) java.lang.Math#atan2(double, double) + */ + public static float atan2(float y, float x) { + return (float) Math.atan2(y, x); + } + + /** + * Return cosine of an angle. Direct call to java.lang.Math + * + * @param value The angle to cosine. + * @return the cosine of the angle. + * @see Math#cos(double) Math#cos(double) + */ + public static float cos(float value) { + return (float) Math.cos(value); + } + + /** + * Return 1/sqrt(value) + * + * @param value The value to process. + * @return 1 /sqrt(value) + * @see java.lang.Math#sqrt(double) java.lang.Math#sqrt(double) + */ + public static float invSqrt(float value) { + return (float) (1.0f / Math.sqrt(value)); + } + + /** + * Return the sine of an angle. Direct call to java.lang.Math + * + * @param value The angle to sine. + * @return the sine of the angle. + * @see Math#sin(double) Math#sin(double) + */ + public static float sin(float value) { + return (float) Math.sin(value); + } + + /** + * Returns the square root of a given value. + * + * @param value The value to sqrt. + * @return The square root of the given value. + * @see java.lang.Math#sqrt(double) java.lang.Math#sqrt(double) + */ + public static float sqrt(float value) { + return (float) Math.sqrt(value); + } + + /** + * Return true of the value is zero. + * + * @param value the value. + * @return true if the values are equals. + */ + public static boolean isZero(float value) { + return Float.compare(value, 0F) == 0; + } + + /** + * Return true of the value is zero. + * + * @param value the value. + * @return true if the values are equals. + */ + public static boolean isZero(double value) { + return Double.compare(value, 0D) == 0; + } + + /** + * Compare the two float values. + * + * @param first the first. + * @param second the second. + * @return true if the values are equals. + */ + public static boolean equals(float first, float second) { + return Float.compare(first, second) == 0; + } + + /** + * Compare the two float values. + * + * @param first the first. + * @param second the second. + * @return true if the values are equals. + */ + public static boolean equals(double first, double second) { + return Double.compare(first, second) == 0; + } + + /** + * Compare the two float values by the epsilon. + * + * @param first the first. + * @param second the second. + * @param epsilon the epsilon. + * @return true if the values are equals. + */ + public static boolean equals(float first, float second, float epsilon) { + return first == second || Math.abs(first - second) < epsilon; + } + + /** + * Compare the two float values by the epsilon. + * + * @param first the first. + * @param second the second. + * @param epsilon the epsilon. + * @return true if the values are equals. + */ + public static boolean equals(double first, double second, double epsilon) { + return first == second || Math.abs(first - second) < epsilon; + } + + /** + * Compare the two float values by the epsilon. + * + * @param first the first. + * @param second the second. + * @param epsilon the epsilon. + * @return true if the first value is less than the second value. + */ + public static boolean lessThan(float first, float second, float epsilon) { + return second - first > epsilon; + } + + /** + * Compare the two float values by the epsilon. + * + * @param first the first. + * @param second the second. + * @param epsilon the epsilon. + * @return true if the first value is less than the second value. + */ + public static boolean lessThan(double first, double second, double epsilon) { + return second - first > epsilon; + } + + /** + * Compare the two float values by the epsilon. + * + * @param first the first. + * @param second the second. + * @param epsilon the epsilon. + * @return true if the first value is greater than the second value. + */ + public static boolean greaterThan(float first, float second, float epsilon) { + return first - second > epsilon; + } + + /** + * Compare the two float values by the epsilon. + * + * @param first the first. + * @param second the second. + * @param epsilon the epsilon. + * @return true if the first value is greater than the second value. + */ + public static boolean greaterThan(double first, double second, double epsilon) { + return first - second > epsilon; + } + + /** + * Cut the second part of the float value by the mod. For example: cut(1.123456F, 3) returns 1.123F. + * + * @param value the value. + * @param mod the mod. + * @return the cut value. + */ + public static float cut(float value, float mod) { + return (int) (value * mod) / mod; + } + + /** + * Return zero if the value is null. + * + * @param value the value. + * @return zero if the value is null. + */ + public static Float zeroIfNull(@Nullable Float value) { + return value == null ? ZERO_FLOAT : value; + } + + /** + * Return zero if the value is null. + * + * @param value the value. + * @return zero if the value is null. + */ + public static Double zeroIfNull(@Nullable Double value) { + return value == null ? ZERO_DOUBLE : value; + } + + /** + * Return zero if the value is null. + * + * @param value the value. + * @return zero if the value is null. + */ + public static Integer zeroIfNull(@Nullable Integer value) { + return value == null ? ZERO_INTEGER : value; + } + + /** + * Returns zero if the value is null. + * + * @param value the value. + * @return zero if the value is null. + */ + public static Long zeroIfNull(@Nullable Long value) { + return value == null ? ZERO_LONG : value; + } + + /** + * Clamp the value between the min and the max. + * + * @param value the source value. + * @param min the minimal value. + * @param max the maximal value. + * @return the clamped value. + */ + public static float clamp(float value, float min, float max) { + return value > max ? max : value < min ? min : value; + } + + /** + * Clamp the value between 0 and 1. + * + * @param value the source value. + * @return the clamped value. + */ + public static float clamp(float value) { + return clamp(value, 0f, 1f); + } + + /** + * Linear time-based interpolation. + * + * @param min the minimal value. + * @param max the maximal value. + * @param time the time. + * @return the interpolated value or maximal value if the time is greater than 1.0. + */ + public static float lerp(float min, float max, float time) { + + if (time > 1.0f) { + return max; } - /** - * Return cosine of an angle. Direct call to java.lang.Math - * - * @param value The angle to cosine. - * @return the cosine of the angle. - * @see Math#cos(double) Math#cos(double) - */ - public static float cos(float value) { - return (float) Math.cos(value); + if (time < 0.0f) { + return min; } - /** - * Return 1/sqrt(value) - * - * @param value The value to process. - * @return 1 /sqrt(value) - * @see java.lang.Math#sqrt(double) java.lang.Math#sqrt(double) - */ - public static float invSqrt(float value) { - return (float) (1.0f / Math.sqrt(value)); + return lerpUnnormal(min, max, time); + } + + /** + * Linear time-based interpolation. + * + * @param min the minimal value. + * @param max the maximal value. + * @param time the time. + * @return the interpolated value. + */ + public static float lerpUnnormal(float min, float max, float time) { + return (1.f - time) * min + time * max; + } + + /** + * Return true if these vectors are equals. + * + * @param first the first vector. + * @param second the second vector. + * @param epsilon the epsilon. + * @return true if these vectors are equals. + */ + public boolean isEquals(@Nullable Vector3f first, @Nullable Vector3f second, float epsilon) { + if (first == null || second == null) { + return false; + } else { + return first.equals(second, epsilon); } + } - /** - * Return the sine of an angle. Direct call to java.lang.Math - * - * @param value The angle to sine. - * @return the sine of the angle. - * @see Math#sin(double) Math#sin(double) - */ - public static float sin(float value) { - return (float) Math.sin(value); - } - - /** - * Returns the square root of a given value. - * - * @param value The value to sqrt. - * @return The square root of the given value. - * @see java.lang.Math#sqrt(double) java.lang.Math#sqrt(double) - */ - public static float sqrt(float value) { - return (float) Math.sqrt(value); - } - - /** - * Return true of the value is zero. - * - * @param value the value. - * @return true if the values are equals. - */ - public static boolean isZero(float value) { - return Float.compare(value, 0F) == 0; - } - - /** - * Return true of the value is zero. - * - * @param value the value. - * @return true if the values are equals. - */ - public static boolean isZero(double value) { - return Double.compare(value, 0D) == 0; - } - - /** - * Compare the two float values. - * - * @param first the first. - * @param second the second. - * @return true if the values are equals. - */ - public static boolean equals(float first, float second) { - return Float.compare(first, second) == 0; - } - - /** - * Compare the two float values. - * - * @param first the first. - * @param second the second. - * @return true if the values are equals. - */ - public static boolean equals(double first, double second) { - return Double.compare(first, second) == 0; - } - - /** - * Compare the two float values by the epsilon. - * - * @param first the first. - * @param second the second. - * @param epsilon the epsilon. - * @return true if the values are equals. - */ - public static boolean equals(float first, float second, float epsilon) { - return first == second || Math.abs(first - second) < epsilon; - } - - /** - * Compare the two float values by the epsilon. - * - * @param first the first. - * @param second the second. - * @param epsilon the epsilon. - * @return true if the values are equals. - */ - public static boolean equals(double first, double second, double epsilon) { - return first == second || Math.abs(first - second) < epsilon; - } - - /** - * Compare the two float values by the epsilon. - * - * @param first the first. - * @param second the second. - * @param epsilon the epsilon. - * @return true if the first value is less than the second value. - */ - public static boolean lessThan(float first, float second, float epsilon) { - return second - first > epsilon; - } - - /** - * Compare the two float values by the epsilon. - * - * @param first the first. - * @param second the second. - * @param epsilon the epsilon. - * @return true if the first value is less than the second value. - */ - public static boolean lessThan(double first, double second, double epsilon) { - return second - first > epsilon; - } - - /** - * Compare the two float values by the epsilon. - * - * @param first the first. - * @param second the second. - * @param epsilon the epsilon. - * @return true if the first value is greater than the second value. - */ - public static boolean greaterThan(float first, float second, float epsilon) { - return first - second > epsilon; - } - - /** - * Compare the two float values by the epsilon. - * - * @param first the first. - * @param second the second. - * @param epsilon the epsilon. - * @return true if the first value is greater than the second value. - */ - public static boolean greaterThan(double first, double second, double epsilon) { - return first - second > epsilon; - } - - /** - * Cut the second part of the float value by the mod. For example: cut(1.123456F, 3) returns 1.123F. - * - * @param value the value. - * @param mod the mod. - * @return the cut value. - */ - public static float cut(float value, float mod) { - return (int) (value * mod) / mod; - } - - /** - * Return zero if the value is null. - * - * @param value the value. - * @return zero if the value is null. - */ - public static @NotNull Float zeroIfNull(@Nullable Float value) { - return value == null ? ZERO_FLOAT : value; - } - - /** - * Return zero if the value is null. - * - * @param value the value. - * @return zero if the value is null. - */ - public static @NotNull Double zeroIfNull(@Nullable Double value) { - return value == null ? ZERO_DOUBLE : value; - } - - /** - * Return zero if the value is null. - * - * @param value the value. - * @return zero if the value is null. - */ - public static @NotNull Integer zeroIfNull(@Nullable Integer value) { - return value == null ? ZERO_INTEGER : value; - } - - /** - * Returns zero if the value is null. - * - * @param value the value. - * @return zero if the value is null. - */ - public static @NotNull Long zeroIfNull(@Nullable Long value) { - return value == null ? ZERO_LONG : value; - } - - /** - * Clamp the value between the min and the max. - * - * @param value the source value. - * @param min the minimal value. - * @param max the maximal value. - * @return the clamped value. - */ - public static float clamp(float value, float min, float max) { - return value > max ? max : value < min ? min : value; - } - - /** - * Clamp the value between 0 and 1. - * - * @param value the source value. - * @return the clamped value. - */ - public static float clamp(float value) { - return clamp(value, 0f, 1f); - } - - /** - * Linear time-based interpolation. - * - * @param min the minimal value. - * @param max the maximal value. - * @param time the time. - * @return the interpolated value or maximal value if the time is greater than 1.0. - */ - public static float lerp(float min, float max, float time) { - - if (time > 1.0f) { - return max; - } - - if (time < 0.0f) { - return min; - } - - return lerpUnnormal(min, max, time); - } - - /** - * Linear time-based interpolation. - * - * @param min the minimal value. - * @param max the maximal value. - * @param time the time. - * @return the interpolated value. - */ - public static float lerpUnnormal(float min, float max, float time) { - return (1.f - time) * min + time * max; - } - - /** - * Return true if these vectors are equals. - * - * @param first the first vector. - * @param second the second vector. - * @param epsilon the epsilon. - * @return true if these vectors are equals. - */ - public boolean isEquals(@Nullable Vector3f first, @Nullable Vector3f second, float epsilon) { - if (first == null || second == null) { - return false; - } else { - return first.equals(second, epsilon); - } - } - - private ExtMath() { - throw new RuntimeException(); - } + private ExtMath() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java index 58882268..1bed088a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java @@ -37,866 +37,876 @@ import javasabr.rlib.common.util.array.ArrayFactory; import javasabr.rlib.common.util.array.UnsafeArray; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The utility class. * * @author JavaSaBr */ +@NullMarked public class FileUtils { - public static final ArrayComparator FILE_PATH_LENGTH_COMPARATOR = (first, second) -> { + public static final ArrayComparator FILE_PATH_LENGTH_COMPARATOR = (first, second) -> { - int firstLength = first.getNameCount(); - int secondLength = second.getNameCount(); - - if (firstLength == secondLength) { - int firstLevel = Files.isDirectory(first) ? 2 : 1; - int secondLevel = Files.isDirectory(first) ? 2 : 1; - return firstLevel - secondLevel; - } - - return firstLength - secondLength; - }; - - private static final Pattern FILE_NAME_PATTERN = Pattern.compile( - "# Match a valid Windows filename (unspecified file system). \n" + - "^ # Anchor to start of string. \n" + - "(?! # Assert filename is not: CON, PRN, \n" + - " (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" + - " CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" + - " COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" + - " ) # LPT6, LPT7, LPT8, and LPT9... \n" + - " (?:\\.[^.]*)? # followed by optional extension \n" + - " $ # and end of string \n" + - ") # End negative lookahead assertion. \n" + - "[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" + - "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" + - "$ # Anchor to end of string. ", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS); - - private static final Pattern NORMALIZE_FILE_NAME_PATTERN = Pattern.compile("[\\\\/:*?\"<>|]"); - - private static final SimpleFileVisitor DELETE_FOLDER_VISITOR = new SimpleFileVisitor<>() { - - @Override - public FileVisitResult postVisitDirectory(@NotNull Path dir, @Nullable IOException exc) throws IOException { - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(@NotNull Path file, @NotNull BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - }; - - private static final Path[] EMPTY_PATHS = new Path[0]; - - /** - * Check a string on valid file name. - * - * @param filename the file name. - * @return true if the file name is valid. - */ - public static boolean isValidName(@Nullable String filename) { - - if (StringUtils.isEmpty(filename)) { - return false; - } - - return FILE_NAME_PATTERN.matcher(filename) - .matches(); + int firstLength = first.getNameCount(); + int secondLength = second.getNameCount(); + + if (firstLength == secondLength) { + int firstLevel = Files.isDirectory(first) ? 2 : 1; + int secondLevel = Files.isDirectory(first) ? 2 : 1; + return firstLevel - secondLevel; + } + + return firstLength - secondLength; + }; + + private static final Pattern FILE_NAME_PATTERN = Pattern.compile( + "# Match a valid Windows filename (unspecified file system). \n" + + "^ # Anchor to start of string. \n" + + "(?! # Assert filename is not: CON, PRN, \n" + + " (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" + + " CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" + + " COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" + + " ) # LPT6, LPT7, LPT8, and LPT9... \n" + + " (?:\\.[^.]*)? # followed by optional extension \n" + + " $ # and end of string \n" + + ") # End negative lookahead assertion. \n" + + "[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" + + "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" + + "$ # Anchor to end of string. ", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS); + + private static final Pattern NORMALIZE_FILE_NAME_PATTERN = Pattern.compile("[\\\\/:*?\"<>|]"); + + private static final SimpleFileVisitor DELETE_FOLDER_VISITOR = new SimpleFileVisitor<>() { + + @Override + public FileVisitResult postVisitDirectory(Path dir, @Nullable IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + }; + + private static final Path[] EMPTY_PATHS = new Path[0]; + + /** + * Check a string on valid file name. + * + * @param filename the file name. + * @return true if the file name is valid. + */ + public static boolean isValidName(@Nullable String filename) { + + if (StringUtils.isEmpty(filename)) { + return false; + } + + return FILE_NAME_PATTERN + .matcher(filename) + .matches(); + } + + /** + * Normalize the file name to a valid file name. + * + * @param filename the string with file name. + * @return normalized file name. + */ + public static String normalizeName(@Nullable String filename) { + + if (StringUtils.isEmpty(filename)) { + return "_"; + } + + return NORMALIZE_FILE_NAME_PATTERN + .matcher(filename) + .replaceAll("_"); + } + + /** + * Add recursive all files to the container from the folder. + * + * @param container the file container. + * @param dir the folder. + * @param withFolders need to add folders. + * @param extensions extensions filter. + */ + public static void addFilesTo( + Array container, + Path dir, + boolean withFolders, + String @Nullable ... extensions) { + + if (Files.isDirectory(dir) && withFolders) { + container.add(dir); + } + + if (!Files.exists(dir)) { + LoggerManager + .getDefaultLogger() + .warning(dir, arg -> "Folder " + arg + " not found"); + return; + } + + try (var stream = Files.newDirectoryStream(dir)) { + for (var path : stream) { + if (Files.isDirectory(path)) { + addFilesTo(container, path, withFolders, extensions); + } else if (extensions == null || extensions.length < 1 || containsExtensions(extensions, path.getFileName())) { + container.add(path); + } + } + + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Check the extensions of the file. + * + * @param extensions the checked extensions. + * @param path the file. + * @return true if the file has a checked extension. + */ + public static boolean containsExtensions(String @Nullable [] extensions, Path path) { + return containsExtensions(extensions, path.toString()); + } + + /** + * Check the extensions of the path. + * + * @param extensions the checked extensions. + * @param path the path. + * @return true if the path has a checked extension. + */ + public static boolean containsExtensions(String @Nullable [] extensions, String path) { + return ArrayUtils.anyMatchR(extensions, path, String::endsWith); + } + + /** + * Check the extensions of the file. + * + * @param extensions the checked extensions. + * @param path the file. + * @return true if the file has a checked extension. + */ + public static boolean containsExtensions(@Nullable Array extensions, Path path) { + return containsExtensions(extensions, path.toString()); + } + + /** + * Check the extensions of the path. + * + * @param extensions the checked extensions. + * @param path the path. + * @return true if the path has a checked extension. + */ + public static boolean containsExtensions(@Nullable Array extensions, String path) { + return extensions != null && extensions.anyMatchR(path, String::endsWith); + } + + /** + * Check the extensions of the file. + * + * @param extensions the checked extensions. + * @param path the file. + * @return true if the file has a checked extension. + */ + public static boolean containsExtensions(@Nullable Collection extensions, Path path) { + return containsExtensions(extensions, path.toString()); + } + + /** + * Check the extensions of the path. + * + * @param extensions the checked extensions. + * @param path the path. + * @return true if the path has a checked extension. + */ + public static boolean containsExtensions(@Nullable Collection extensions, String path) { + return extensions != null && extensions + .stream() + .anyMatch(path::endsWith); + } + + /** + * Delete the file. + * + * @param path the file to delete. + */ + public static void delete(Path path) { + try { + deleteImpl(path); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Delete the file or the folder. + * + * @param path the file or folder. + */ + private static void deleteImpl(Path path) throws IOException { + if (!Files.isDirectory(path)) { + Files.delete(path); + } else { + Files.walkFileTree(path, DELETE_FOLDER_VISITOR); + } + } + + /** + * Get an extension of the path. + * + * @param path the path. + * @return the extension or the path if the path doesn't have an extension. + */ + public static String getExtension(@Nullable String path) { + return getExtension(path, false); + } + + /** + * Check the path about existing an extension. + * + * @param path the path. + * @return true if the path contains any extension. + */ + public static boolean hasExtension(@Nullable String path) { + + if (StringUtils.isEmpty(path)) { + return false; + } + + var index = path.lastIndexOf('.'); + + if (index == -1) { + return false; + } + + var separatorIndex = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + + return separatorIndex < index; + } + + /** + * Get an extension of the path. + * + * @param path the path. + * @param toLowerCase true if need that extension was only in lower case. + * @return the extension or empty string. + */ + public static String getExtension(@Nullable String path, boolean toLowerCase) { + + if (StringUtils.isEmpty(path)) { + return StringUtils.EMPTY; + } + + var index = path.lastIndexOf('.'); + + if (index == -1) { + return StringUtils.EMPTY; + } + + var separatorIndex = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + + if (separatorIndex > index) { + return StringUtils.EMPTY; + } + + var result = path.substring(index + 1); + + if (toLowerCase) { + return result.toLowerCase(); } - /** - * Normalize the file name to a valid file name. - * - * @param filename the string with file name. - * @return normalized file name. - */ - public static @NotNull String normalizeName(@Nullable String filename) { - - if (StringUtils.isEmpty(filename)) { - return "_"; - } - - return NORMALIZE_FILE_NAME_PATTERN.matcher(filename) - .replaceAll("_"); - } - - /** - * Add recursive all files to the container from the folder. - * - * @param container the file container. - * @param dir the folder. - * @param withFolders need to add folders. - * @param extensions extensions filter. - */ - public static void addFilesTo( - @NotNull Array container, - @NotNull Path dir, - boolean withFolders, - @Nullable String... extensions - ) { - - if (Files.isDirectory(dir) && withFolders) { - container.add(dir); - } + return result; + } - if (!Files.exists(dir)) { - LoggerManager.getDefaultLogger().warning(dir, arg -> "Folder " + arg + " not found"); - return; - } + /** + * Get an extension of the file. + * + * @param file the file. + * @return the extension or empty string. + */ + public static String getExtension(Path file) { - try (var stream = Files.newDirectoryStream(dir)) { - for (var path : stream) { - if (Files.isDirectory(path)) { - addFilesTo(container, path, withFolders, extensions); - } else if (extensions == null || extensions.length < 1 || containsExtensions(extensions, path.getFileName())) { - container.add(path); - } - } - - } catch (IOException e) { - throw new UncheckedIOException(e); - } + if (Files.isDirectory(file)) { + return StringUtils.EMPTY; } - /** - * Check the extensions of the file. - * - * @param extensions the checked extensions. - * @param path the file. - * @return true if the file has a checked extension. - */ - public static boolean containsExtensions(@Nullable String[] extensions, @NotNull Path path) { - return containsExtensions(extensions, path.toString()); - } - - /** - * Check the extensions of the path. - * - * @param extensions the checked extensions. - * @param path the path. - * @return true if the path has a checked extension. - */ - public static boolean containsExtensions(@Nullable String[] extensions, @NotNull String path) { - return ArrayUtils.anyMatchR(extensions, path, String::endsWith); - } - - /** - * Check the extensions of the file. - * - * @param extensions the checked extensions. - * @param path the file. - * @return true if the file has a checked extension. - */ - public static boolean containsExtensions(@Nullable Array extensions, @NotNull Path path) { - return containsExtensions(extensions, path.toString()); - } - - /** - * Check the extensions of the path. - * - * @param extensions the checked extensions. - * @param path the path. - * @return true if the path has a checked extension. - */ - public static boolean containsExtensions(@Nullable Array extensions, @NotNull String path) { - return extensions != null && extensions.anyMatchR(path, String::endsWith); - } - - /** - * Check the extensions of the file. - * - * @param extensions the checked extensions. - * @param path the file. - * @return true if the file has a checked extension. - */ - public static boolean containsExtensions(@Nullable Collection extensions, @NotNull Path path) { - return containsExtensions(extensions, path.toString()); - } - - /** - * Check the extensions of the path. - * - * @param extensions the checked extensions. - * @param path the path. - * @return true if the path has a checked extension. - */ - public static boolean containsExtensions(@Nullable Collection extensions, @NotNull String path) { - return extensions != null && extensions.stream().anyMatch(path::endsWith); - } - - /** - * Delete the file. - * - * @param path the file to delete. - */ - public static void delete(@NotNull Path path) { - try { - deleteImpl(path); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } + return getExtension(Objects.toString(file.getFileName())); + } - /** - * Delete the file or the folder. - * - * @param path the file or folder. - */ - private static void deleteImpl(@NotNull Path path) throws IOException { - if (!Files.isDirectory(path)) { - Files.delete(path); - } else { - Files.walkFileTree(path, DELETE_FOLDER_VISITOR); - } - } + /** + * Get an extension of the file. + * + * @param file the file. + * @param toLowerCase true if need that extension was only in lower case. + * @return the extension or empty string. + */ + public static String getExtension(Path file, boolean toLowerCase) { - /** - * Get an extension of the path. - * - * @param path the path. - * @return the extension or the path if the path doesn't have an extension. - */ - public static @NotNull String getExtension(@Nullable String path) { - return getExtension(path, false); + if (Files.isDirectory(file)) { + return StringUtils.EMPTY; } - /** - * Check the path about existing an extension. - * - * @param path the path. - * @return true if the path contains any extension. - */ - public static boolean hasExtension(@Nullable String path) { - - if (StringUtils.isEmpty(path)) { - return false; - } - - var index = path.lastIndexOf('.'); - - if (index == -1) { - return false; - } - - var separatorIndex = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); - - return separatorIndex < index; - } + return getExtension(Objects.toString(file.getFileName()), toLowerCase); + } - /** - * Get an extension of the path. - * - * @param path the path. - * @param toLowerCase true if need that extension was only in lower case. - * @return the extension or empty string. - */ - public static @NotNull String getExtension(@Nullable String path, boolean toLowerCase) { + /** + * Recursive get all files of the folder. + * + * @param dir the folder. + * @param extensions the extension filter. + * @return the list of all files. + */ + public static Array getFiles(Path dir, String @Nullable ... extensions) { + return getFiles(dir, false, extensions); + } - if (StringUtils.isEmpty(path)) { - return StringUtils.EMPTY; - } + /** + * Recursive get all files of the folder. + * + * @param dir the folder. + * @param withFolders need include folders. + * @param extensions the extension filter. + * @return the list of all files. + */ + public static Array getFiles(Path dir, boolean withFolders, String @Nullable ... extensions) { - var index = path.lastIndexOf('.'); + Array result = ArrayFactory.newArray(Path.class); - if (index == -1) { - return StringUtils.EMPTY; - } + addFilesTo(result, dir, withFolders, extensions); - var separatorIndex = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + UnsafeArray unsafeArray = result.asUnsafe(); + unsafeArray.trimToSize(); - if (separatorIndex > index) { - return StringUtils.EMPTY; - } + return result; + } - var result = path.substring(index + 1); + /** + * Get all files in the package. + * + * @param pckg the package. + * @param extensions the extensions filter. + * @return the array of files. + */ + public static Path[] getFiles(Package pckg, String @Nullable ... extensions) { - if (toLowerCase) { - return result.toLowerCase(); - } + ClassLoader classLoader = Thread + .currentThread() + .getContextClassLoader(); - return result; + Enumeration urls = null; + try { + urls = classLoader.getResources(pckg + .getName() + .replace('.', '/')); + } catch (IOException exc) { + LoggerManager + .getDefaultLogger() + .warning(exc); } - /** - * Get an extension of the file. - * - * @param file the file. - * @return the extension or empty string. - */ - public static @NotNull String getExtension(@NotNull Path file) { - - if (Files.isDirectory(file)) { - return StringUtils.EMPTY; - } - - return getExtension(Objects.toString(file.getFileName())); + if (urls == null) { + return EMPTY_PATHS; } - /** - * Get an extension of the file. - * - * @param file the file. - * @param toLowerCase true if need that extension was only in lower case. - * @return the extension or empty string. - */ - public static @NotNull String getExtension(@NotNull Path file, boolean toLowerCase) { + var files = Array.ofType(Path.class); - if (Files.isDirectory(file)) { - return StringUtils.EMPTY; - } + while (urls.hasMoreElements()) { - return getExtension(Objects.toString(file.getFileName()), toLowerCase); + var next = urls.nextElement(); + var path = next.getFile(); + + if (path.contains("%20")) { + path = path.replaceAll("%20", " "); + } + + var file = Paths.get(path); + + if (Files.isDirectory(file)) { + files.addAll(getFiles(file, extensions)); + } else if (extensions == null || extensions.length < 1 || containsExtensions(extensions, path)) { + files.add(file); + } } - /** - * Recursive get all files of the folder. - * - * @param dir the folder. - * @param extensions the extension filter. - * @return the list of all files. - */ - public static @NotNull Array getFiles(@NotNull Path dir, @Nullable String... extensions) { - return getFiles(dir, false, extensions); - } - - /** - * Recursive get all files of the folder. - * - * @param dir the folder. - * @param withFolders need include folders. - * @param extensions the extension filter. - * @return the list of all files. - */ - public static @NotNull Array getFiles(@NotNull Path dir, boolean withFolders, @Nullable String... extensions) { - - Array result = ArrayFactory.newArray(Path.class); - - addFilesTo(result, dir, withFolders, extensions); + return files.toArray(Path.class); + } + + /** + * Get a file name without extension. + * + * @param filename the file name. + * @return the file name without extension. + */ + public static String getNameWithoutExtension(String filename) { - UnsafeArray unsafeArray = result.asUnsafe(); - unsafeArray.trimToSize(); - - return result; + if (StringUtils.isEmpty(filename)) { + return filename; } - /** - * Get all files in the package. - * - * @param pckg the package. - * @param extensions the extensions filter. - * @return the array of files. - */ - public static @NotNull Path[] getFiles(@NotNull Package pckg, @Nullable String... extensions) { - - ClassLoader classLoader = Thread - .currentThread() - .getContextClassLoader(); - - Enumeration urls = null; - try { - urls = classLoader.getResources(pckg.getName().replace('.', '/')); - } catch (IOException exc) { - LoggerManager.getDefaultLogger().warning(exc); - } - - if (urls == null) { - return EMPTY_PATHS; - } - - var files = Array.ofType(Path.class); - - while (urls.hasMoreElements()) { - - var next = urls.nextElement(); - var path = next.getFile(); - - if (path.contains("%20")) { - path = path.replaceAll("%20", " "); - } - - var file = Paths.get(path); + int index = filename.lastIndexOf('.'); - if (Files.isDirectory(file)) { - files.addAll(getFiles(file, extensions)); - } else if (extensions == null || extensions.length < 1 || containsExtensions(extensions, path)) { - files.add(file); - } - } - - return files.toArray(Path.class); + if (index == -1) { + return filename; } - /** - * Get a file name without extension. - * - * @param filename the file name. - * @return the file name without extension. - */ - public static @NotNull String getNameWithoutExtension(@NotNull String filename) { - - if (StringUtils.isEmpty(filename)) { - return filename; - } + return filename.substring(0, index); + } + + /** + * Get a file name without extension. + * + * @param file the file. + * @return the file name without extension. + */ + public static String getNameWithoutExtension(Path file) { - int index = filename.lastIndexOf('.'); + String filename = file + .getFileName() + .toString(); - if (index == -1) { - return filename; - } - - return filename.substring(0, index); + if (StringUtils.isEmpty(filename)) { + return filename; } - /** - * Get a file name without extension. - * - * @param file the file. - * @return the file name without extension. - */ - public static @NotNull String getNameWithoutExtension(@NotNull Path file) { - - String filename = file.getFileName().toString(); + int index = filename.lastIndexOf('.'); - if (StringUtils.isEmpty(filename)) { - return filename; - } - - int index = filename.lastIndexOf('.'); - - if (index == -1) { - return filename; - } - - return filename.substring(0, index); - } - - /** - * Read the file as a string from classpath. - * - * @param path the path to file. - * @return the string content of the file. - */ - public static @NotNull String readFromClasspath(@NotNull String path) { - return read(FileUtils.class.getResourceAsStream(path)); - } - - /** - * Read the file as a string from classpath. - * - * @param cs the class to get a classloader. - * @param path the path to file. - * @return the string content of the file. - */ - public static @NotNull String readFromClasspath(@NotNull Class cs, @NotNull String path) { - return read(cs.getResourceAsStream(path)); - } - - /** - * Read the file as a string. - * - * @param path the path to file. - * @return the string content of the file. - */ - public static @NotNull String read(@NotNull String path) { - try { - return read(Files.newInputStream(Paths.get(path))); - } catch (IOException e) { - throw new UncheckedIOException(e); - } + if (index == -1) { + return filename; } - /** - * Read the input stream as a string. - * - * @param in the input stream. - * @return the string content of the input stream. - */ - public static @NotNull String read(@NotNull InputStream in) { - - var content = new StringBuilder(); - - try (var reader = new BufferedReader(new InputStreamReader(in))) { + return filename.substring(0, index); + } - var buffer = CharBuffer.allocate(512); + /** + * Read the file as a string from classpath. + * + * @param path the path to file. + * @return the string content of the file. + */ + public static String readFromClasspath(String path) { + return read(FileUtils.class.getResourceAsStream(path)); + } - while (reader.ready()) { + /** + * Read the file as a string from classpath. + * + * @param cs the class to get a classloader. + * @param path the path to file. + * @return the string content of the file. + */ + public static String readFromClasspath(Class cs, String path) { + return read(cs.getResourceAsStream(path)); + } - buffer.clear(); - reader.read(buffer); - buffer.flip(); - - content.append(buffer.array(), 0, buffer.limit()); - } - - } catch (IOException e) { - throw new UncheckedIOException(e); - } - - return content.toString(); - } - - /** - * Read the file as a string. - * - * @param file the file. - * @return the string content of the file. - */ - public static @NotNull String read(@NotNull Path file) { - try { - return read(Files.newInputStream(file)); - } catch (IOException e) { - throw new UncheckedIOException(e); - } + /** + * Read the file as a string. + * + * @param path the path to file. + * @return the string content of the file. + */ + public static String read(String path) { + try { + return read(Files.newInputStream(Paths.get(path))); + } catch (IOException e) { + throw new UncheckedIOException(e); } + } - /** - * Find a first free file name in the directory. - * - * @param directory the directory. - * @param file the checked file. - * @return the first free name. - */ - public static @NotNull String getFirstFreeName(@NotNull Path directory, @NotNull Path file) { + /** + * Read the input stream as a string. + * + * @param in the input stream. + * @return the string content of the input stream. + */ + public static String read(InputStream in) { - var initFileName = file - .getFileName() - .toString(); + var content = new StringBuilder(); - if (!Files.exists(directory.resolve(initFileName))) { - return initFileName; - } - - var extension = getExtension(initFileName); - var nameWithoutExtension = getNameWithoutExtension(initFileName); - var result = nameWithoutExtension + "_1." + extension; - - for (int i = 2; Files.exists(directory.resolve(result)); i++) { - result = nameWithoutExtension + "_" + i + "." + extension; - } + try (var reader = new BufferedReader(new InputStreamReader(in))) { - return result; - } - - /** - * Unzip the zip file to the destination folder. - * - * @param destination the destination folder. - * @param zipFile the zip file. - */ - public static void unzip(@NotNull Path destination, @NotNull Path zipFile) { - - if (!Files.exists(destination)) { - throw new IllegalArgumentException("The folder " + destination + " doesn't exist."); - } + var buffer = CharBuffer.allocate(512); - try (var zin = new ZipInputStream(Files.newInputStream(zipFile))) { - for (var entry = zin.getNextEntry(); entry != null; entry = zin.getNextEntry()) { + while (reader.ready()) { - var file = destination.resolve(entry.getName()); + buffer.clear(); + reader.read(buffer); + buffer.flip(); - if (entry.isDirectory()) { - Files.createDirectories(file); - } else { - Files.copy(zin, file, StandardCopyOption.REPLACE_EXISTING); - } - } + content.append(buffer.array(), 0, buffer.limit()); + } - } catch (IOException e) { - throw new UncheckedIOException(e); - } + } catch (IOException e) { + throw new UncheckedIOException(e); } - /** - * Get a name of the file by the path and the separator. - * - * @param path the path. - * @param separator the separator. - * @return the name. - */ - public static @NotNull String getName(@NotNull String path, char separator) { - - if (path.length() < 2) { - return path; - } - - int index = path.lastIndexOf(separator); + return content.toString(); + } - if (index == -1) { - return path; - } - - return path.substring(index + 1, path.length()); + /** + * Read the file as a string. + * + * @param file the file. + * @return the string content of the file. + */ + public static String read(Path file) { + try { + return read(Files.newInputStream(file)); + } catch (IOException e) { + throw new UncheckedIOException(e); } + } - /** - * Get a parent path of the path using the separator. - * - * @param path the path. - * @param separator the separator. - * @return the parent path. - */ - public static @NotNull String getParent(@NotNull String path, char separator) { + /** + * Find a first free file name in the directory. + * + * @param directory the directory. + * @param file the checked file. + * @return the first free name. + */ + public static String getFirstFreeName(Path directory, Path file) { - if (path.length() < 2) { - return path; - } + var initFileName = file + .getFileName() + .toString(); - int index = path.lastIndexOf(separator); + if (!Files.exists(directory.resolve(initFileName))) { + return initFileName; + } - if (index == -1) { - return path; - } + var extension = getExtension(initFileName); + var nameWithoutExtension = getNameWithoutExtension(initFileName); + var result = nameWithoutExtension + "_1." + extension; + + for (int i = 2; Files.exists(directory.resolve(result)); i++) { + result = nameWithoutExtension + "_" + i + "." + extension; + } + + return result; + } + + /** + * Unzip the zip file to the destination folder. + * + * @param destination the destination folder. + * @param zipFile the zip file. + */ + public static void unzip(Path destination, Path zipFile) { - return path.substring(0, index); - } - - /** - * @param directory the directory. - * @param attrs the directory attributes. - * @see Files#createDirectories(Path, FileAttribute[]) - */ - public static void createDirectories(@NotNull Path directory, @NotNull FileAttribute... attrs) { - Utils.unchecked(directory, attrs, Files::createDirectories); - } - - /** - * @param file the file. - * @param options the link options. - * @return the last modified time. - * @see Files#getLastModifiedTime(Path, LinkOption...) - */ - public static @NotNull FileTime getLastModifiedTime(@NotNull Path file, @NotNull LinkOption... options) { - return notNull(Utils.uncheckedGet(file, options, Files::getLastModifiedTime)); - } - - /** - * Get a {@link URI} of the file. - * - * @param file the file. - * @return the {@link URI}. - */ - public static @NotNull URI getUri(@NotNull Path file) { - return Utils.uncheckedGet(file, Path::toUri); - } - - /** - * Get a {@link URI} of the {@link URL}. - * - * @param url the url. - * @return the {@link URI}. - */ - public static @NotNull URI getUri(@NotNull URL url) { - return Utils.uncheckedGet(url, URL::toURI); - } - - /** - * Get a {@link URL} of the file. - * - * @param file the file. - * @return the {@link URL}. - */ - public static @NotNull URL getUrl(@NotNull Path file) { - return Utils.uncheckedGet(getUri(file), URI::toURL); - } - - /** - * @param base the base file path. - * @param other the other file path. - * @return the resulting relative path, or an empty path if both paths are equal. - * @see Path#relativize(Path) - */ - public static @NotNull Path relativize(@NotNull Path base, @NotNull Path other) { - return Utils.uncheckedGet(base, other, Path::relativize); - } - - /** - * @param base the base file path. - * @param other the other filepath. - * @return the resulting relative path, or an empty path if both paths are equal or null. - * @see Path#relativize(Path) - */ - public static @Nullable Path safeRelativize(@Nullable Path base, @Nullable Path other) { - if (base == null || other == null) { - return null; - } else { - return Utils.uncheckedGet(base, other, Path::relativize); - } + if (!Files.exists(destination)) { + throw new IllegalArgumentException("The folder " + destination + " doesn't exist."); } - /** - * Create a new default watch service. - * - * @return the new default watch service. - * @see FileSystems#getDefault() - */ - public static @NotNull WatchService newDefaultWatchService() { - try { - return FileSystems.getDefault().newWatchService(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } + try (var zin = new ZipInputStream(Files.newInputStream(zipFile))) { + for (var entry = zin.getNextEntry(); entry != null; entry = zin.getNextEntry()) { - /** - * @param start the start folder. - * @param visitor the visitor. - * @return the start folder. - * @see Files#walkFileTree(Path, FileVisitor) - */ - public static @NotNull Path walkFileTree(@NotNull Path start, @NotNull FileVisitor visitor) { - try { - return Files.walkFileTree(start, visitor); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } + var file = destination.resolve(entry.getName()); - /** - * @param prefix the prefix of a temp file. - * @param suffix the suffix of a temp file. - * @param attrs the additional attributes. - * @return the created temp file. - * @see Files#createTempFile(String, String, FileAttribute[]) - */ - public static @NotNull Path createTempFile( - @NotNull String prefix, - @NotNull String suffix, - @NotNull FileAttribute... attrs - ) { - try { - return Files.createTempFile(prefix, suffix, attrs); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - /** - * Apply each sub-file of the directory to the consumer. - * - * @param directory the directory. - * @param consumer the consumer. - */ - public static void forEach(@NotNull Path directory, @NotNull Consumer<@NotNull Path> consumer) { - validateDirectory(directory); - - try (var stream = Files.newDirectoryStream(directory)) { - for (var path : stream) { - consumer.accept(path); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - private static void validateDirectory(@NotNull Path directory) { - if (!Files.isDirectory(directory)) { - throw new IllegalArgumentException("The file " + directory + " isn't a directory."); - } else if (!Files.exists(directory)) { - throw new IllegalArgumentException("The file " + directory + " isn't exists."); - } - } - - /** - * Apply each sub-file of the directory to the consumer. - * - * @param directory the directory. - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - public static void forEach( - @NotNull Path directory, - @NotNull T argument, - @NotNull BiConsumer<@NotNull Path, @NotNull T> consumer - ) { - validateDirectory(directory); - - try (var stream = Files.newDirectoryStream(directory)) { - for (var path : stream) { - consumer.accept(path, argument); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - /** - * Get children's stream of the directory. - * - * @param directory the directory. - * @return children's stream of the directory. - */ - public static @NotNull Stream stream(@NotNull Path directory) { - validateDirectory(directory); - - var files = Array.ofType(Path.class); - - try (var stream = Files.newDirectoryStream(directory)) { - stream.forEach(files::add); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - - return files.stream(); - } - - /** - * Apply each sub-file of the directory to the consumer. - * - * @param directory the directory. - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - public static void forEachR( - @NotNull Path directory, - @NotNull T argument, - @NotNull BiConsumer<@NotNull T, @NotNull Path> consumer - ) { - validateDirectory(directory); - - try (var stream = Files.newDirectoryStream(directory)) { - for (var path : stream) { - consumer.accept(argument, path); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - /** - * Apply each sub-file of the directory to the consumer. - * - * @param directory the directory. - * @param argument the argument. - * @param condition the condition. - * @param consumer the consumer. - * @param the argument's type. - */ - public static void forEachR( - @NotNull Path directory, - @NotNull T argument, - @NotNull Predicate<@NotNull Path> condition, - @NotNull BiConsumer<@NotNull T, @NotNull Path> consumer - ) { - validateDirectory(directory); - - try (var stream = Files.newDirectoryStream(directory)) { - for (var path : stream) { - if (condition.test(path)) { - consumer.accept(argument, path); - } - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } + if (entry.isDirectory()) { + Files.createDirectories(file); + } else { + Files.copy(zin, file, StandardCopyOption.REPLACE_EXISTING); + } + } + + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Get a name of the file by the path and the separator. + * + * @param path the path. + * @param separator the separator. + * @return the name. + */ + public static String getName(String path, char separator) { + + if (path.length() < 2) { + return path; + } + + int index = path.lastIndexOf(separator); + + if (index == -1) { + return path; + } + + return path.substring(index + 1, path.length()); + } + + /** + * Get a parent path of the path using the separator. + * + * @param path the path. + * @param separator the separator. + * @return the parent path. + */ + public static String getParent(String path, char separator) { + + if (path.length() < 2) { + return path; + } + + int index = path.lastIndexOf(separator); + + if (index == -1) { + return path; + } + + return path.substring(0, index); + } + + /** + * @param directory the directory. + * @param attrs the directory attributes. + * @see Files#createDirectories(Path, FileAttribute[]) + */ + public static void createDirectories(Path directory, FileAttribute... attrs) { + Utils.unchecked(directory, attrs, Files::createDirectories); + } + + /** + * @param file the file. + * @param options the link options. + * @return the last modified time. + * @see Files#getLastModifiedTime(Path, LinkOption...) + */ + public static FileTime getLastModifiedTime(Path file, LinkOption... options) { + return notNull(Utils.uncheckedGet(file, options, Files::getLastModifiedTime)); + } + + /** + * Get a {@link URI} of the file. + * + * @param file the file. + * @return the {@link URI}. + */ + public static URI getUri(Path file) { + return Utils.uncheckedGet(file, Path::toUri); + } + + /** + * Get a {@link URI} of the {@link URL}. + * + * @param url the url. + * @return the {@link URI}. + */ + public static URI getUri(URL url) { + return Utils.uncheckedGet(url, URL::toURI); + } + + /** + * Get a {@link URL} of the file. + * + * @param file the file. + * @return the {@link URL}. + */ + public static URL getUrl(Path file) { + return Utils.uncheckedGet(getUri(file), URI::toURL); + } + + /** + * @param base the base file path. + * @param other the other file path. + * @return the resulting relative path, or an empty path if both paths are equal. + * @see Path#relativize(Path) + */ + public static Path relativize(Path base, Path other) { + return Utils.uncheckedGet(base, other, Path::relativize); + } + + /** + * @param base the base file path. + * @param other the other filepath. + * @return the resulting relative path, or an empty path if both paths are equal or null. + * @see Path#relativize(Path) + */ + public static @Nullable Path safeRelativize(@Nullable Path base, @Nullable Path other) { + if (base == null || other == null) { + return null; + } else { + return Utils.uncheckedGet(base, other, Path::relativize); + } + } + + /** + * Create a new default watch service. + * + * @return the new default watch service. + * @see FileSystems#getDefault() + */ + public static WatchService newDefaultWatchService() { + try { + return FileSystems + .getDefault() + .newWatchService(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * @param start the start folder. + * @param visitor the visitor. + * @return the start folder. + * @see Files#walkFileTree(Path, FileVisitor) + */ + public static Path walkFileTree(Path start, FileVisitor visitor) { + try { + return Files.walkFileTree(start, visitor); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * @param prefix the prefix of a temp file. + * @param suffix the suffix of a temp file. + * @param attrs the additional attributes. + * @return the created temp file. + * @see Files#createTempFile(String, String, FileAttribute[]) + */ + public static Path createTempFile( + String prefix, + String suffix, + FileAttribute... attrs) { + try { + return Files.createTempFile(prefix, suffix, attrs); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Apply each sub-file of the directory to the consumer. + * + * @param directory the directory. + * @param consumer the consumer. + */ + public static void forEach(Path directory, Consumer consumer) { + validateDirectory(directory); + + try (var stream = Files.newDirectoryStream(directory)) { + for (var path : stream) { + consumer.accept(path); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void validateDirectory(Path directory) { + if (!Files.isDirectory(directory)) { + throw new IllegalArgumentException("The file " + directory + " isn't a directory."); + } else if (!Files.exists(directory)) { + throw new IllegalArgumentException("The file " + directory + " isn't exists."); + } + } + + /** + * Apply each sub-file of the directory to the consumer. + * + * @param directory the directory. + * @param argument the argument. + * @param consumer the consumer. + * @param the argument's type. + */ + public static void forEach( + Path directory, + T argument, + BiConsumer consumer) { + validateDirectory(directory); + + try (var stream = Files.newDirectoryStream(directory)) { + for (var path : stream) { + consumer.accept(path, argument); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Get children's stream of the directory. + * + * @param directory the directory. + * @return children's stream of the directory. + */ + public static Stream stream(Path directory) { + validateDirectory(directory); + + var files = Array.ofType(Path.class); + + try (var stream = Files.newDirectoryStream(directory)) { + stream.forEach(files::add); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + return files.stream(); + } + + /** + * Apply each sub-file of the directory to the consumer. + * + * @param directory the directory. + * @param argument the argument. + * @param consumer the consumer. + * @param the argument's type. + */ + public static void forEachR( + Path directory, + T argument, + BiConsumer consumer) { + validateDirectory(directory); + + try (var stream = Files.newDirectoryStream(directory)) { + for (var path : stream) { + consumer.accept(argument, path); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Apply each sub-file of the directory to the consumer. + * + * @param directory the directory. + * @param argument the argument. + * @param condition the condition. + * @param consumer the consumer. + * @param the argument's type. + */ + public static void forEachR( + Path directory, + T argument, + Predicate condition, + BiConsumer consumer) { + validateDirectory(directory); + + try (var stream = Files.newDirectoryStream(directory)) { + for (var path : stream) { + if (condition.test(path)) { + consumer.accept(argument, path); + } + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/HasName.java b/rlib-common/src/main/java/javasabr/rlib/common/util/HasName.java index 936f977d..c54884a2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/HasName.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/HasName.java @@ -1,19 +1,19 @@ package javasabr.rlib.common.util; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to mark an object that it has a name. * * @author JavaSaBr */ +@NullMarked public interface HasName { - /** - * Gets name. - * - * @return the name of this object. - */ - @NotNull - String getName(); + /** + * Gets name. + * + * @return the name of this object. + */ + String getName(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/IOUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/IOUtils.java index e069538a..ce6c4f79 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/IOUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/IOUtils.java @@ -12,140 +12,137 @@ import java.nio.CharBuffer; import java.nio.charset.StandardCharsets; import javasabr.rlib.common.function.SafeSupplier; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class with utility methods. * * @author JavaSaBr */ +@NullMarked public final class IOUtils { - private static final ThreadLocal LOCAL_CHAR_BUFFER = withInitial(() -> new char[1024]); + private static final ThreadLocal LOCAL_CHAR_BUFFER = withInitial(() -> new char[1024]); - /** - * Close a closeable object. - * - * @param closeable the closeable object. - */ - public static void close(@Nullable Closeable closeable) { + /** + * Close a closeable object. + * + * @param closeable the closeable object. + */ + public static void close(@Nullable Closeable closeable) { - if (closeable == null) { - return; - } - - try { - closeable.close(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } + if (closeable == null) { + return; } - /** - * Convert the input stream to a string using UTF-8 encoding. - * - * @param in the input stream. - * @return the result string. - * @throws UncheckedIOException if input stream thrown an io exception. - */ - public static @NotNull String toString(@NotNull InputStream in) { - - var result = new StringBuilder(); - - try (var reader = new InputStreamReader(in, StandardCharsets.UTF_8)) { - toString(result, reader); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - - return result.toString(); + try { + closeable.close(); + } catch (IOException e) { + throw new UncheckedIOException(e); } - - /** - * Convert the input stream to a string using UTF-8 encoding. - * - * @param inFactory the input stream. - * @return the result string. - * @throws UncheckedIOException if input stream thrown an io exception. - * @throws RuntimeException if happened something wrong with the supplier. - */ - public static @NotNull String toString(@NotNull SafeSupplier inFactory) { - - var result = new StringBuilder(); - - try (var reader = new InputStreamReader(inFactory.get(), StandardCharsets.UTF_8)) { - toString(result, reader); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return result.toString(); + } + + /** + * Convert the input stream to a string using UTF-8 encoding. + * + * @param in the input stream. + * @return the result string. + * @throws UncheckedIOException if input stream thrown an io exception. + */ + public static String toString(InputStream in) { + + var result = new StringBuilder(); + + try (var reader = new InputStreamReader(in, StandardCharsets.UTF_8)) { + toString(result, reader); + } catch (IOException e) { + throw new UncheckedIOException(e); } - private static void toString(@NotNull StringBuilder result, @NotNull InputStreamReader reader) throws IOException { - for (var buffer = CharBuffer.allocate(100); reader.read(buffer) != -1; ) { - buffer.flip(); - result.append(buffer.array(), 0, buffer.limit()); - } + return result.toString(); + } + + /** + * Convert the input stream to a string using UTF-8 encoding. + * + * @param inFactory the input stream. + * @return the result string. + * @throws UncheckedIOException if input stream thrown an io exception. + * @throws RuntimeException if happened something wrong with the supplier. + */ + public static String toString(SafeSupplier inFactory) { + + var result = new StringBuilder(); + + try (var reader = new InputStreamReader(inFactory.get(), StandardCharsets.UTF_8)) { + toString(result, reader); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - /** - * Copy data from a source stream to a destination stream. - * - * @param in the source stream. - * @param out the destination stream. - * @param buffer the buffer. - * @param needClose true if need to close streams. - * @throws IOException the io exception - */ - public static void copy( - @NotNull InputStream in, - @NotNull OutputStream out, - @NotNull byte[] buffer, - boolean needClose - ) throws IOException { - - for (int i = in.read(buffer); i != -1; i = in.read(buffer)) { - out.write(buffer, 0, i); - } - - if (needClose) { - close(in); - close(out); - } - } + return result.toString(); + } - /** - * Read the reader to the result string. - * - * @param reader the reader. - * @return the result string. - * @throws UncheckedIOException if reader thrown an io exception. - */ - public static @NotNull String toStringUsingTLB(@NotNull Reader reader) { - return toString(reader, LOCAL_CHAR_BUFFER.get()); + private static void toString(StringBuilder result, InputStreamReader reader) throws IOException { + for (var buffer = CharBuffer.allocate(100); reader.read(buffer) != -1; ) { + buffer.flip(); + result.append(buffer.array(), 0, buffer.limit()); } - - private static @NotNull String toString(@NotNull Reader reader, @NotNull char[] buffer) { - - var builder = new StringBuilder(); - try { - - for (int read = reader.read(buffer); read != -1; read = reader.read(buffer)) { - builder.append(buffer, 0, read); - } - - } catch (IOException e) { - throw new UncheckedIOException(e); - } - - return builder.toString(); + } + + /** + * Copy data from a source stream to a destination stream. + * + * @param in the source stream. + * @param out the destination stream. + * @param buffer the buffer. + * @param needClose true if need to close streams. + * @throws IOException the io exception + */ + public static void copy(InputStream in, OutputStream out, byte[] buffer, boolean needClose) + throws IOException { + + for (int i = in.read(buffer); i != -1; i = in.read(buffer)) { + out.write(buffer, 0, i); } - private IOUtils() { - throw new RuntimeException(); + if (needClose) { + close(in); + close(out); } + } + + /** + * Read the reader to the result string. + * + * @param reader the reader. + * @return the result string. + * @throws UncheckedIOException if reader thrown an io exception. + */ + public static String toStringUsingTLB(Reader reader) { + return toString(reader, LOCAL_CHAR_BUFFER.get()); + } + + private static String toString(Reader reader, char[] buffer) { + + var builder = new StringBuilder(); + try { + + for (int read = reader.read(buffer); read != -1; read = reader.read(buffer)) { + builder.append(buffer, 0, read); + } + + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + return builder.toString(); + } + + private IOUtils() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/NumberUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/NumberUtils.java index 335bbfb2..7df5b60e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/NumberUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/NumberUtils.java @@ -2,407 +2,398 @@ import java.util.Optional; import java.util.function.Function; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The utility class. * * @author JavaSaBr */ +@NullMarked public final class NumberUtils { - /** - * Get a short value from a byte array. - * - * @param bytes the byte array. - * @param offset the offset. - * @return the short value. - */ - public static short getShort(@NotNull byte[] bytes, int offset) { - return (short) (bytes[offset + 1] << 8 | bytes[offset] & 0xff); + /** + * Get a short value from a byte array. + * + * @param bytes the byte array. + * @param offset the offset. + * @return the short value. + */ + public static short getShort(byte[] bytes, int offset) { + return (short) (bytes[offset + 1] << 8 | bytes[offset] & 0xff); + } + + /** + * Return true if a string is not null and can be converted to a long. + * + * @param string the string to convert. + * @return if the string is not null and can be converted to a long. + * @since 9.3.0 + */ + public static boolean isLong(@Nullable String string) { + + if (string == null) { + return false; + } else { + try { + Long.parseLong(string); + return true; + } catch (NumberFormatException e) { + return false; + } } - - /** - * Return true if a string is not null and can be converted to a long. - * - * @param string the string to convert. - * @return if the string is not null and can be converted to a long. - * @since 9.3.0 - */ - public static boolean isLong(@Nullable String string) { - - if (string == null) { - return false; - } else { - try { - Long.parseLong(string); - return true; - } catch (NumberFormatException e) { - return false; - } - } - } - - /** - * Convert a string to int object or null if this string is null or not a number. - * - * @param string the string to convert. - * @return the int object or null. - * @since 9.4.0 - */ - public static @Nullable Integer safeToInt(@Nullable String string) { - - if (string == null) { - return null; - } else { - try { - return Integer.valueOf(string); - } catch (NumberFormatException e) { - return null; - } - } - } - - /** - * Convert a string to long object or null if this string is null or not a number. - * - * @param string the string to convert. - * @return the long object or null. - * @since 9.3.0 - */ - public static @Nullable Long safeToLong(@Nullable String string) { - - if (string == null) { - return null; - } else { - try { - return Long.valueOf(string); - } catch (NumberFormatException e) { - return null; - } - } - } - - /** - * Convert a string to long object. - * - * @param string the string to convert. - * @return the optional of long object. - * @since 9.3.0 - */ - public static @NotNull Optional toOptionalLong(@Nullable String string) { - - if (string == null) { - return Optional.empty(); - } else { - try { - return Optional.of(Long.valueOf(string)); - } catch (NumberFormatException e) { - return Optional.empty(); - } - } - } - - /** - * Set a bit in a number by a pos to 1. - * - * @param value the byte. - * @param pos the bit position. - * @return the update number. - * @since 9.4.0 - */ - public static int setBit(int value, int pos) { - return value | (1 << pos); - } - - /** - * Set a bit in a number by a pos to 0. - * - * @param value the byte. - * @param pos the bit position. - * @return the update number. - * @since 9.4.0 - */ - public static int unsetBit(int value, int pos) { - return value & ~(1 << pos); - } - - /** - * Return true if bit by pos in a byte is 1. - * - * @param value the byte. - * @param pos the bit position. - * @return true if the bit is 1. - * @since 9.4.0 - */ - public static boolean isSetBit(int value, int pos) { - return (value & (1L << pos)) != 0; - } - - /** - * Return true if bit by pos in a byte is 0. - * - * @param value the byte. - * @param pos the bit position. - * @return true if the bit is 0. - * @since 9.4.0 - */ - public static boolean isNotSetBit(int value, int pos) { - return (value & (1L << pos)) == 0; - } - - /** - * Set last high 4 bits to a byte. - * - * @param value the byte value. - * @return the result value with updating last high 4 bits. - * @since 9.4.0 - */ - public static int setHighByteBits(int value, int highBits) { - return value | highBits << 4; - } - - /** - * Get last high 4 bits from a byte. - * - * @param value the byte value. - * @return the value of last 4 high bits. - * @since 9.4.0 - */ - public static byte getHighByteBits(int value) { - return (byte) (value >> 4); + } + + /** + * Convert a string to int object or null if this string is null or not a number. + * + * @param string the string to convert. + * @return the int object or null. + * @since 9.4.0 + */ + public static @Nullable Integer safeToInt(@Nullable String string) { + + if (string == null) { + return null; + } else { + try { + return Integer.valueOf(string); + } catch (NumberFormatException e) { + return null; + } } - - /** - * Set first low 4 bits to a byte. - * - * @param value the byte value. - * @return the result value with updating first low 4 bits. - * @since 9.4.0 - */ - public static int setLowByteBits(int value, int lowBits) { - return value | lowBits & 0x0F; + } + + /** + * Convert a string to long object or null if this string is null or not a number. + * + * @param string the string to convert. + * @return the long object or null. + * @since 9.3.0 + */ + public static @Nullable Long safeToLong(@Nullable String string) { + + if (string == null) { + return null; + } else { + try { + return Long.valueOf(string); + } catch (NumberFormatException e) { + return null; + } } - - /** - * Get first low 4 bits from a byte. - * - * @param value the byte value. - * @return the value of last 4 low bits. - * @since 9.4.0 - */ - public static byte getLowByteBits(int value) { - return (byte) (value & 0x0F); + } + + /** + * Convert a string to long object. + * + * @param string the string to convert. + * @return the optional of long object. + * @since 9.3.0 + */ + public static Optional toOptionalLong(@Nullable String string) { + + if (string == null) { + return Optional.empty(); + } else { + try { + return Optional.of(Long.valueOf(string)); + } catch (NumberFormatException e) { + return Optional.empty(); + } } - - /** - * Validate a number and throw an exception when the number is not valid. - * - * @param value the value. - * @param min the min number. - * @param max the max number. - * @return the passed number. - * @since 9.5.0 - */ - public static int validate(int value, int min, int max) { - return validate(value, min, max, IllegalArgumentException::new); + } + + /** + * Set a bit in a number by a pos to 1. + * + * @param value the byte. + * @param pos the bit position. + * @return the update number. + * @since 9.4.0 + */ + public static int setBit(int value, int pos) { + return value | (1 << pos); + } + + /** + * Set a bit in a number by a pos to 0. + * + * @param value the byte. + * @param pos the bit position. + * @return the update number. + * @since 9.4.0 + */ + public static int unsetBit(int value, int pos) { + return value & ~(1 << pos); + } + + /** + * Return true if bit by pos in a byte is 1. + * + * @param value the byte. + * @param pos the bit position. + * @return true if the bit is 1. + * @since 9.4.0 + */ + public static boolean isSetBit(int value, int pos) { + return (value & (1L << pos)) != 0; + } + + /** + * Return true if bit by pos in a byte is 0. + * + * @param value the byte. + * @param pos the bit position. + * @return true if the bit is 0. + * @since 9.4.0 + */ + public static boolean isNotSetBit(int value, int pos) { + return (value & (1L << pos)) == 0; + } + + /** + * Set last high 4 bits to a byte. + * + * @param value the byte value. + * @return the result value with updating last high 4 bits. + * @since 9.4.0 + */ + public static int setHighByteBits(int value, int highBits) { + return value | highBits << 4; + } + + /** + * Get last high 4 bits from a byte. + * + * @param value the byte value. + * @return the value of last 4 high bits. + * @since 9.4.0 + */ + public static byte getHighByteBits(int value) { + return (byte) (value >> 4); + } + + /** + * Set first low 4 bits to a byte. + * + * @param value the byte value. + * @return the result value with updating first low 4 bits. + * @since 9.4.0 + */ + public static int setLowByteBits(int value, int lowBits) { + return value | lowBits & 0x0F; + } + + /** + * Get first low 4 bits from a byte. + * + * @param value the byte value. + * @return the value of last 4 low bits. + * @since 9.4.0 + */ + public static byte getLowByteBits(int value) { + return (byte) (value & 0x0F); + } + + /** + * Validate a number and throw an exception when the number is not valid. + * + * @param value the value. + * @param min the min number. + * @param max the max number. + * @return the passed number. + * @since 9.5.0 + */ + public static int validate(int value, int min, int max) { + return validate(value, min, max, IllegalArgumentException::new); + } + + /** + * Validate a number and throw an exception when the number is not valid. + * + * @param value the value. + * @param min the min number. + * @param max the max number. + * @param exceptionFactory the exception factory. + * @return the passed number. + * @since 9.5.0 + */ + public static int validate( + int value, + int min, + int max, + Function exceptionFactory) { + if (value < min || value > max) { + throw exceptionFactory.apply("Invalid value: " + value + " when should be " + min + " < v < " + max); + } else { + return value; } - - /** - * Validate a number and throw an exception when the number is not valid. - * - * @param value the value. - * @param min the min number. - * @param max the max number. - * @param exceptionFactory the exception factory. - * @return the passed number. - * @since 9.5.0 - */ - public static int validate( - int value, - int min, - int max, - @NotNull Function<@NotNull String, @NotNull RuntimeException> exceptionFactory - ) { - if (value < min || value > max) { - throw exceptionFactory.apply("Invalid value: " + value + " when should be " + min + " < v < " + max); - } else { - return value; - } + } + + /** + * Validate a number and throw an exception when the number is not valid. + * + * @param value the validated value. + * @param min the min number. + * @param max the max number. + * @return the passed number. + * @since 9.5.0 + */ + public static long validate(long value, long min, long max) { + return validate(value, min, max, IllegalArgumentException::new); + } + + /** + * Validate a number and throw an exception when the number is not valid. + * + * @param value the validated value. + * @param min the min number. + * @param max the max number. + * @param exceptionFactory the exception factory. + * @return the passed number. + * @since 9.5.0 + */ + public static long validate( + long value, + long min, + long max, + Function exceptionFactory) { + if (value < min || value > max) { + throw exceptionFactory.apply("Invalid value: " + value + " when should be " + min + " < v < " + max); + } else { + return value; } - - /** - * Validate a number and throw an exception when the number is not valid. - * - * @param value the validated value. - * @param min the min number. - * @param max the max number. - * @return the passed number. - * @since 9.5.0 - */ - public static long validate(long value, long min, long max) { - return validate(value, min, max, IllegalArgumentException::new); + } + + /** + * Convert a number to boolean which should be only 0 or 1 or throw an exception. + * + * @param value the validated value. + * @return the validated value. + */ + public static boolean toBoolean(int value) { + return toBoolean(value, IllegalArgumentException::new); + } + + /** + * Convert a number to boolean which should be only 0 or 1 or throw an exception. + * + * @param value the validated value. + * @return the validated value. + */ + public static boolean toBoolean(long value) { + return toBoolean(value, IllegalArgumentException::new); + } + + /** + * Convert a number to boolean which should be only 0 or 1 or throw an exception. + * + * @param value the validated value. + * @param exceptionFactory the exception factory. + * @return the validated value. + */ + public static boolean toBoolean( + int value, + Function exceptionFactory) { + if (value == 0 || value == 1) { + return value == 1; + } else { + throw exceptionFactory.apply("Invalid value: " + value + " when should be only 0 or 1"); } - - /** - * Validate a number and throw an exception when the number is not valid. - * - * @param value the validated value. - * @param min the min number. - * @param max the max number. - * @param exceptionFactory the exception factory. - * @return the passed number. - * @since 9.5.0 - */ - public static long validate( - long value, - long min, - long max, - @NotNull Function<@NotNull String, @NotNull RuntimeException> exceptionFactory - ) { - if (value < min || value > max) { - throw exceptionFactory.apply("Invalid value: " + value + " when should be " + min + " < v < " + max); - } else { - return value; - } - } - - /** - * Convert a number to boolean which should be only 0 or 1 or throw an exception. - * - * @param value the validated value. - * @return the validated value. - */ - public static boolean toBoolean(int value) { - return toBoolean(value, IllegalArgumentException::new); - } - - /** - * Convert a number to boolean which should be only 0 or 1 or throw an exception. - * - * @param value the validated value. - * @return the validated value. - */ - public static boolean toBoolean(long value) { - return toBoolean(value, IllegalArgumentException::new); - } - - /** - * Convert a number to boolean which should be only 0 or 1 or throw an exception. - * - * @param value the validated value. - * @param exceptionFactory the exception factory. - * @return the validated value. - */ - public static boolean toBoolean( - int value, - @NotNull Function<@NotNull String, @NotNull RuntimeException> exceptionFactory - ) { - if (value == 0 || value == 1) { - return value == 1; - } else { - throw exceptionFactory.apply("Invalid value: " + value + " when should be only 0 or 1"); - } - } - - /** - * Convert a number to boolean which should be only 0 or 1 or throw an exception. - * - * @param value the validated value. - * @param exceptionFactory the exception factory. - * @return the validated value. - */ - public static boolean toBoolean( - long value, - @NotNull Function<@NotNull String, @NotNull RuntimeException> exceptionFactory - ) { - if (value == 0 || value == 1) { - return value == 1; - } else { - throw exceptionFactory.apply("Invalid value: " + value + " when should be only 0 or 1"); - } - } - - /** - * Returns {@code true} if the numbers are equal to each other - * and {@code false} otherwise. - * - * @param first the first number. - * @param second the second number to be compared with {@code first} for equality. - * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. - * @since 9.7.0 - */ - public static boolean equals(byte first, byte second) { - return first == second; - } - - /** - * Returns {@code true} if the numbers are equal to each other - * and {@code false} otherwise. - * - * @param first the first number. - * @param second the second number to be compared with {@code first} for equality. - * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. - * @since 9.7.0 - */ - public static boolean equals(short first, short second) { - return first == second; - } - - /** - * Returns {@code true} if the numbers are equal to each other - * and {@code false} otherwise. - * - * @param first the first number. - * @param second the second number to be compared with {@code first} for equality. - * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. - * @since 9.7.0 - */ - public static boolean equals(int first, int second) { - return first == second; - } - - /** - * Returns {@code true} if the numbers are equal to each other - * and {@code false} otherwise. - * - * @param first the first number. - * @param second the second number to be compared with {@code first} for equality. - * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. - * @since 9.7.0 - */ - public static boolean equals(long first, long second) { - return first == second; - } - - /** - * Returns {@code true} if the numbers are equal to each other - * and {@code false} otherwise. - * - * @param first the first number. - * @param second the second number to be compared with {@code first} for equality. - * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. - * @since 9.7.0 - */ - public static boolean equals(float first, float second) { - return first == second; - } - - /** - * Returns {@code true} if the numbers are equal to each other - * and {@code false} otherwise. - * - * @param first the first number. - * @param second the second number to be compared with {@code first} for equality. - * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. - * @since 9.7.0 - */ - public static boolean equals(double first, double second) { - return first == second; - } - - private NumberUtils() { - throw new IllegalArgumentException(); + } + + /** + * Convert a number to boolean which should be only 0 or 1 or throw an exception. + * + * @param value the validated value. + * @param exceptionFactory the exception factory. + * @return the validated value. + */ + public static boolean toBoolean( + long value, + Function exceptionFactory) { + if (value == 0 || value == 1) { + return value == 1; + } else { + throw exceptionFactory.apply("Invalid value: " + value + " when should be only 0 or 1"); } + } + + /** + * Returns {@code true} if the numbers are equal to each other and {@code false} otherwise. + * + * @param first the first number. + * @param second the second number to be compared with {@code first} for equality. + * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. + * @since 9.7.0 + */ + public static boolean equals(byte first, byte second) { + return first == second; + } + + /** + * Returns {@code true} if the numbers are equal to each other and {@code false} otherwise. + * + * @param first the first number. + * @param second the second number to be compared with {@code first} for equality. + * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. + * @since 9.7.0 + */ + public static boolean equals(short first, short second) { + return first == second; + } + + /** + * Returns {@code true} if the numbers are equal to each other and {@code false} otherwise. + * + * @param first the first number. + * @param second the second number to be compared with {@code first} for equality. + * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. + * @since 9.7.0 + */ + public static boolean equals(int first, int second) { + return first == second; + } + + /** + * Returns {@code true} if the numbers are equal to each other and {@code false} otherwise. + * + * @param first the first number. + * @param second the second number to be compared with {@code first} for equality. + * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. + * @since 9.7.0 + */ + public static boolean equals(long first, long second) { + return first == second; + } + + /** + * Returns {@code true} if the numbers are equal to each other and {@code false} otherwise. + * + * @param first the first number. + * @param second the second number to be compared with {@code first} for equality. + * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. + * @since 9.7.0 + */ + public static boolean equals(float first, float second) { + return first == second; + } + + /** + * Returns {@code true} if the numbers are equal to each other and {@code false} otherwise. + * + * @param first the first number. + * @param second the second number to be compared with {@code first} for equality. + * @return {@code true} if the arguments are equal to each other and {@code false} otherwise. + * @since 9.7.0 + */ + public static boolean equals(double first, double second) { + return first == second; + } + + private NumberUtils() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ObjectUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ObjectUtils.java index 042a9c00..d65a46d4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ObjectUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ObjectUtils.java @@ -5,164 +5,163 @@ import java.util.function.LongFunction; import java.util.function.Supplier; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class with utility methods. * * @author JavaSaBr */ +@NullMarked public final class ObjectUtils { - /** - * @param the object's type. - * @param obj the object to check on not null. - * @param message the message for exception if the object is null. - * @return the passed object if it is not null. - * @see Objects#requireNonNull(Object, String) - */ - public static @NotNull T notNull(@Nullable T obj, @NotNull String message) { - return Objects.requireNonNull(obj, message); + /** + * @param the object's type. + * @param obj the object to check on not null. + * @param message the message for exception if the object is null. + * @return the passed object if it is not null. + * @see Objects#requireNonNull(Object, String) + */ + public static T notNull(@Nullable T obj, String message) { + return Objects.requireNonNull(obj, message); + } + + /** + * @param the object's type. + * @param obj the object to check on not null. + * @return the passed object if it is not null. + * @see Objects#requireNonNull(Object) + */ + public static T notNull(@Nullable T obj) { + return Objects.requireNonNull(obj); + } + + /** + * Check the object to be not null. If the object is null this method throws an exception from the supplier. + * + * @param the object's type. + * @param obj the checked object. + * @param supplier the exception factory. + * @return the object. + * @since 9.0.2 + */ + public static T notNull(@Nullable T obj, Supplier supplier) { + + if (obj == null) { + throw supplier.get(); } - /** - * @param the object's type. - * @param obj the object to check on not null. - * @return the passed object if it is not null. - * @see Objects#requireNonNull(Object) - */ - public static @NotNull T notNull(@Nullable T obj) { - return Objects.requireNonNull(obj); + return obj; + } + + /** + * Check the object to be not null. If the object is null this method throws an exception from the factory. + * + * @param the object's type. + * @param the argument's type. + * @param obj the checked object. + * @param arg the argument for the exception factory. + * @param factory the exception factory. + * @return the object. + * @since 9.0.2 + */ + public static T notNull( + @Nullable T obj, + F arg, + Function factory) { + + if (obj == null) { + throw factory.apply(arg); } - /** - * Check the object to be not null. If the object is null this method throws an exception from the supplier. - * - * @param the object's type. - * @param obj the checked object. - * @param supplier the exception factory. - * @return the object. - * @since 9.0.2 - */ - public static @NotNull T notNull(@Nullable T obj, @NotNull Supplier supplier) { - - if (obj == null) { - throw supplier.get(); - } - - return obj; + return obj; + } + + /** + * Check the object to be not null. If the object is null this method throws an exception from the factory. + * + * @param the object's type. + * @param obj the checked object. + * @param arg the argument for the exception factory. + * @param factory the exception factory. + * @return the object. + * @since 9.0.3 + */ + public static T notNull( + @Nullable T obj, + long arg, + LongFunction factory) { + + if (obj == null) { + throw factory.apply(arg); } - /** - * Check the object to be not null. If the object is null this method throws an exception from the factory. - * - * @param the object's type. - * @param the argument's type. - * @param obj the checked object. - * @param arg the argument for the exception factory. - * @param factory the exception factory. - * @return the object. - * @since 9.0.2 - */ - public static @NotNull T notNull( - @Nullable T obj, - @NotNull F arg, - @NotNull Function factory - ) { - - if (obj == null) { - throw factory.apply(arg); - } - - return obj; - } - - /** - * Check the object to be not null. If the object is null this method throws an exception from the factory. - * - * @param the object's type. - * @param obj the checked object. - * @param arg the argument for the exception factory. - * @param factory the exception factory. - * @return the object. - * @since 9.0.3 - */ - public static @NotNull T notNull( - @Nullable T obj, - long arg, - @NotNull LongFunction factory - ) { - - if (obj == null) { - throw factory.apply(arg); - } - - return obj; - } - - /** - * Returns the another object if the first object is null. - * - * @param obj the object. - * @param another the another object. - * @param the object's type. - * @return the another object if the first object is null. - */ - public static @NotNull T ifNull(@Nullable T obj, @NotNull T another) { - return obj == null ? another : obj; - } - - /** - * Returns a new object if the first object is null. - * - * @param obj the object. - * @param factory the factory. - * @param the object's type. - * @return a new object if the first object is null. - */ - public static @NotNull T ifNull(@Nullable T obj, @NotNull Supplier factory) { - return obj == null ? factory.get() : obj; - } - - /** - * Gets hash of the boolean value. - * - * @param value the boolean value. - * @return the hash. - */ - public static int hash(boolean value) { - return value ? 1231 : 1237; - } - - /** - * Gets hash of the long value. - * - * @param value the long value. - * @return the hash. - */ - public static int hash(long value) { - return (int) (value ^ value >>> 32); - } - - /** - * Gets hash of the object. - * - * @param object the object. - * @return the hash. - */ - public static int hash(@Nullable Object object) { - return object == null ? 0 : object.hashCode(); - } - - /** - * Call the method {@link Reusable#release()} if the object is instanceof {@link Reusable}. - * - * @param object the object. - */ - public static void release(@Nullable Object object) { - if (object instanceof Reusable) { - ((Reusable) object).release(); - } + return obj; + } + + /** + * Returns the another object if the first object is null. + * + * @param obj the object. + * @param another the another object. + * @param the object's type. + * @return the another object if the first object is null. + */ + public static T ifNull(@Nullable T obj, T another) { + return obj == null ? another : obj; + } + + /** + * Returns a new object if the first object is null. + * + * @param obj the object. + * @param factory the factory. + * @param the object's type. + * @return a new object if the first object is null. + */ + public static T ifNull(@Nullable T obj, Supplier factory) { + return obj == null ? factory.get() : obj; + } + + /** + * Gets hash of the boolean value. + * + * @param value the boolean value. + * @return the hash. + */ + public static int hash(boolean value) { + return value ? 1231 : 1237; + } + + /** + * Gets hash of the long value. + * + * @param value the long value. + * @return the hash. + */ + public static int hash(long value) { + return (int) (value ^ value >>> 32); + } + + /** + * Gets hash of the object. + * + * @param object the object. + * @return the hash. + */ + public static int hash(@Nullable Object object) { + return object == null ? 0 : object.hashCode(); + } + + /** + * Call the method {@link Reusable#release()} if the object is instanceof {@link Reusable}. + * + * @param object the object. + */ + public static void release(@Nullable Object object) { + if (object instanceof Reusable) { + ((Reusable) object).release(); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java b/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java index 1a74d5fc..3d00a653 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java @@ -5,65 +5,74 @@ import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The property loader using UTF-8 encoding. * * @author JavaSaBr */ +@NullMarked public class PropertyLoader extends ResourceBundle.Control { - private static final PropertyLoader INSTANCE = new PropertyLoader(); + private static final PropertyLoader INSTANCE = new PropertyLoader(); - /** - * Gets instance. - * - * @return the instance - */ - public static PropertyLoader getInstance() { - return INSTANCE; - } - - @Override - public ResourceBundle newBundle(final String baseName, final Locale locale, final String format, - final ClassLoader loader, final boolean reload) - throws IllegalAccessException, InstantiationException, IOException { + /** + * Gets instance. + * + * @return the instance + */ + public static PropertyLoader getInstance() { + return INSTANCE; + } - // The below is a copy of the default implementation. - final String bundleName = toBundleName(baseName, locale); - final String resourceName = toResourceName(bundleName, "properties"); + @Nullable + @Override + public ResourceBundle newBundle( + String baseName, + Locale locale, + String format, + ClassLoader loader, + boolean reload) + throws IOException { - ResourceBundle bundle = null; - InputStream stream = null; + // The below is a copy of the default implementation. + String bundleName = toBundleName(baseName, locale); + String resourceName = toResourceName(bundleName, "properties"); - if (reload) { + ResourceBundle bundle = null; + InputStream stream = null; - final URL url = loader.getResource(resourceName); + if (reload) { - if (url != null) { - final URLConnection connection = url.openConnection(); - if (connection != null) { - connection.setUseCaches(false); - stream = connection.getInputStream(); - } - } + final URL url = loader.getResource(resourceName); - } else { - stream = loader.getResourceAsStream(resourceName); + if (url != null) { + final URLConnection connection = url.openConnection(); + if (connection != null) { + connection.setUseCaches(false); + stream = connection.getInputStream(); } + } - if (stream != null) { - try { - // Only this line is changed to make it to read properties files as UTF-8. - bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8")); - } finally { - stream.close(); - } - } + } else { + stream = loader.getResourceAsStream(resourceName); + } - return bundle; + if (stream != null) { + try { + // Only this line is changed to make it to read properties files as UTF-8. + bundle = new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8)); + } finally { + stream.close(); + } } + + return bundle; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ReflectionUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ReflectionUtils.java index ac2357e6..38ea4acc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ReflectionUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ReflectionUtils.java @@ -6,412 +6,414 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javasabr.rlib.common.util.array.Array; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class with utility reflection methods. * * @author JavaSaBr */ +@NullMarked public final class ReflectionUtils { - /** - * Get all fields of the class. - * - * @param container the field container. - * @param startClass the class. - * @param lastClass the last class. - * @param declared the flag to get private fields as well. - * @param exceptions exception fields. - */ - public static void addAllFields( - @NotNull Array container, - @NotNull Class startClass, - @NotNull Class lastClass, - boolean declared, - @NotNull String... exceptions - ) { - - var next = startClass; - - while (next != null && next != lastClass) { - - var fields = declared ? next.getDeclaredFields() : next.getFields(); - - next = next.getSuperclass(); - - if (fields.length < 1) { - continue; - } - - if (exceptions.length < 1) { - container.addAll(fields); - } else { - ArrayUtils.forEach(fields, toCheck -> !contains(exceptions, toCheck.getName()), container::add); - } - } + /** + * Get all fields of the class. + * + * @param container the field container. + * @param startClass the class. + * @param lastClass the last class. + * @param declared the flag to get private fields as well. + * @param exceptions exception fields. + */ + public static void addAllFields( + Array container, + Class startClass, + Class lastClass, + boolean declared, + String... exceptions) { + + var next = startClass; + + while (next != null && next != lastClass) { + + var fields = declared ? next.getDeclaredFields() : next.getFields(); + + next = next.getSuperclass(); + + if (fields.length < 1) { + continue; + } + + if (exceptions.length < 1) { + container.addAll(fields); + } else { + ArrayUtils.forEach(fields, toCheck -> !contains(exceptions, toCheck.getName()), container::add); + } } - - /** - * Get all fields of a class. - * - * @param cs the class. - * @param exceptions exception fields. - * @return the all declared fields. - * @since 9.9.0 - */ - public static @NotNull Array getAllDeclaredFields(@NotNull Class cs, @NotNull String... exceptions) { - var container = Array.ofType(Field.class); - addAllFields(container, cs, Object.class, true, exceptions); - return container; - } - - /** - * Get all fields of the class. - * - * @param cs the class. - * @param last the last class. - * @param declared the flag of getting private fields. - * @param exceptions exception fields. - * @return the all fields - */ - public static @NotNull Array getAllFields( - @NotNull Class cs, - @NotNull Class last, - boolean declared, - @NotNull String... exceptions - ) { - var container = Array.ofType(Field.class); - addAllFields(container, cs, last, declared, exceptions); - return container; - } - - /** - * Get a field by the name from the type. - * - * @param type the type. - * @param fieldName the field name. - * @return the field. - */ - public static @NotNull Field getField(@NotNull Class type, @NotNull String fieldName) { - try { - return type.getDeclaredField(fieldName); - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException e) { - throw new RuntimeException(e); - } - } - - /** - * Get a field by the name from the type of the object. - * - * @param object the object. - * @param fieldName the field name. - * @return the field. - */ - public static @NotNull Field getField(@NotNull Object object, @NotNull String fieldName) { - return getField(object.getClass(), fieldName); + } + + /** + * Get all fields of a class. + * + * @param cs the class. + * @param exceptions exception fields. + * @return the all declared fields. + * @since 9.9.0 + */ + public static Array getAllDeclaredFields(Class cs, String... exceptions) { + var container = Array.ofType(Field.class); + addAllFields(container, cs, Object.class, true, exceptions); + return container; + } + + /** + * Get all fields of the class. + * + * @param cs the class. + * @param last the last class. + * @param declared the flag of getting private fields. + * @param exceptions exception fields. + * @return the all fields + */ + public static Array getAllFields( + Class cs, + Class last, + boolean declared, + String... exceptions) { + var container = Array.ofType(Field.class); + addAllFields(container, cs, last, declared, exceptions); + return container; + } + + /** + * Get a field by the name from the type. + * + * @param type the type. + * @param fieldName the field name. + * @return the field. + */ + public static Field getField(Class type, String fieldName) { + try { + return type.getDeclaredField(fieldName); + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException e) { + throw new RuntimeException(e); } - - /** - * Get a field by the name with full access from the type. - * - * @param type the type. - * @param fieldName the field name. - * @return the field. - */ - public static @NotNull Field getUnsafeField(@NotNull Class type, @NotNull String fieldName) { - try { - Field field = getField(type, fieldName); - field.setAccessible(true); - return field; - } catch (SecurityException | IllegalArgumentException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a field by the name from the type of the object. + * + * @param object the object. + * @param fieldName the field name. + * @return the field. + */ + public static Field getField(Object object, String fieldName) { + return getField(object.getClass(), fieldName); + } + + /** + * Get a field by the name with full access from the type. + * + * @param type the type. + * @param fieldName the field name. + * @return the field. + */ + public static Field getUnsafeField(Class type, String fieldName) { + try { + Field field = getField(type, fieldName); + field.setAccessible(true); + return field; + } catch (SecurityException | IllegalArgumentException e) { + throw new RuntimeException(e); } - - /** - * Get a field by the name with full access. - * - * @param object the object. - * @param fieldName the field name. - * @return the field. - */ - public static @NotNull Field getUnsafeField(@NotNull Object object, @NotNull String fieldName) { - return getUnsafeField(object.getClass(), fieldName); + } + + /** + * Get a field by the name with full access. + * + * @param object the object. + * @param fieldName the field name. + * @return the field. + */ + public static Field getUnsafeField(Object object, String fieldName) { + return getUnsafeField(object.getClass(), fieldName); + } + + /** + * Get a field value by the field name. + * + * @param the result value's type. + * @param object the object. + * @param fieldName the field name. + * @return the value. + */ + public static @Nullable T getFiledValue(Object object, String fieldName) { + try { + Field field = getField(object, fieldName); + return ClassUtils.unsafeCast(field.get(object)); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Get a field value by the field name. - * - * @param the result value's type. - * @param object the object. - * @param fieldName the field name. - * @return the value. - */ - public static @Nullable T getFiledValue(@NotNull Object object, @NotNull String fieldName) { - try { - Field field = getField(object, fieldName); - return ClassUtils.unsafeCast(field.get(object)); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a field value by the field name with full access. + * + * @param the result value's type. + * @param object the object. + * @param fieldName the field name. + * @return the value. + */ + public static @Nullable T getUnsafeFieldValue(final Object object, final String fieldName) { + try { + final Field field = getUnsafeField(object, fieldName); + return ClassUtils.unsafeCast(field.get(object)); + } catch (final SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Get a field value by the field name with full access. - * - * @param the result value's type. - * @param object the object. - * @param fieldName the field name. - * @return the value. - */ - public static @Nullable T getUnsafeFieldValue(@NotNull final Object object, @NotNull final String fieldName) { - try { - final Field field = getUnsafeField(object, fieldName); - return ClassUtils.unsafeCast(field.get(object)); - } catch (final SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a field value. + * + * @param the result value's type. + * @param object the object. + * @param field the field. + * @return the value. + */ + public static @Nullable T getFieldValue(Object object, Field field) { + try { + return ClassUtils.unsafeCast(field.get(object)); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Get a field value. - * - * @param the result value's type. - * @param object the object. - * @param field the field. - * @return the value. - */ - public static @Nullable T getFieldValue(@NotNull Object object, @NotNull Field field) { - try { - return ClassUtils.unsafeCast(field.get(object)); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - /** - * Set a field value. - * - * @param object the object. - * @param fieldName the field name. - * @param value the value. - */ - public static void setFieldValue(@NotNull Object object, @NotNull String fieldName, @NotNull Object value) { - try { - Field field = getField(object, fieldName); - field.set(object, value); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Set a field value. + * + * @param object the object. + * @param fieldName the field name. + * @param value the value. + */ + public static void setFieldValue(Object object, String fieldName, Object value) { + try { + Field field = getField(object, fieldName); + field.set(object, value); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Set a field value using full access. - * - * @param object the object. - * @param fieldName the field name. - * @param value the value. - */ - public static void setUnsafeFieldValue(@NotNull Object object, @NotNull String fieldName, @NotNull Object value) { - try { - Field field = getUnsafeField(object, fieldName); - field.set(object, value); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Set a field value using full access. + * + * @param object the object. + * @param fieldName the field name. + * @param value the value. + */ + public static void setUnsafeFieldValue(Object object, String fieldName, Object value) { + try { + Field field = getUnsafeField(object, fieldName); + field.set(object, value); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Set a field value. - * - * @param object the object. - * @param field the field. - * @param value the value. - */ - public static void setFieldValue(@NotNull Object object, @NotNull Field field, @NotNull Object value) { - try { - field.set(object, value); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Set a field value. + * + * @param object the object. + * @param field the field. + * @param value the value. + */ + public static void setFieldValue(Object object, Field field, Object value) { + try { + field.set(object, value); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Get a static field. - * - * @param type the class. - * @param fieldName the field name. - * @return the static field. - */ - public static @NotNull Field getStaticField(@NotNull Class type, @NotNull String fieldName) { - try { - return type.getDeclaredField(fieldName); - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a static field. + * + * @param type the class. + * @param fieldName the field name. + * @return the static field. + */ + public static Field getStaticField(Class type, String fieldName) { + try { + return type.getDeclaredField(fieldName); + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException e) { + throw new RuntimeException(e); } - - /** - * Get a static field using full access. - * - * @param type the class. - * @param fieldName the field name. - * @return the static field. - */ - public static @NotNull Field getUnsafeStaticField(@NotNull Class type, @NotNull String fieldName) { - try { - Field field = getStaticField(type, fieldName); - field.setAccessible(true); - return field; - } catch (SecurityException | IllegalArgumentException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a static field using full access. + * + * @param type the class. + * @param fieldName the field name. + * @return the static field. + */ + public static Field getUnsafeStaticField(Class type, String fieldName) { + try { + Field field = getStaticField(type, fieldName); + field.setAccessible(true); + return field; + } catch (SecurityException | IllegalArgumentException e) { + throw new RuntimeException(e); } - - /** - * Get a static field value. - * - * @param the type parameter - * @param type the class. - * @param fieldName the field name. - * @return the value. - */ - public static @Nullable T getStaticFieldValue(@NotNull Class type, @NotNull String fieldName) { - try { - Field field = getStaticField(type, fieldName); - return ClassUtils.unsafeCast(field.get(null)); - } catch (final SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a static field value. + * + * @param the type parameter + * @param type the class. + * @param fieldName the field name. + * @return the value. + */ + public static @Nullable T getStaticFieldValue(Class type, String fieldName) { + try { + Field field = getStaticField(type, fieldName); + return ClassUtils.unsafeCast(field.get(null)); + } catch (final SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Get a static field value using full access. - * - * @param the type parameter - * @param type the class. - * @param fieldName the field name. - * @return the value. - */ - public static @Nullable T getUnsafeStaticFieldValue(@NotNull Class type, @NotNull String fieldName) { - try { - Field field = getUnsafeStaticField(type, fieldName); - return ClassUtils.unsafeCast(field.get(null)); - } catch (final SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a static field value using full access. + * + * @param the type parameter + * @param type the class. + * @param fieldName the field name. + * @return the value. + */ + public static @Nullable T getUnsafeStaticFieldValue(Class type, String fieldName) { + try { + Field field = getUnsafeStaticField(type, fieldName); + return ClassUtils.unsafeCast(field.get(null)); + } catch (final SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Get a static field value. - * - * @param the type parameter - * @param field the field. - * @return the value. - */ - public static @Nullable T getStaticFieldValue(@NotNull Field field) { - try { - return ClassUtils.unsafeCast(field.get(null)); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a static field value. + * + * @param the type parameter + * @param field the field. + * @return the value. + */ + public static @Nullable T getStaticFieldValue(Field field) { + try { + return ClassUtils.unsafeCast(field.get(null)); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Set a static field value. - * - * @param type the class. - * @param fieldName the field name. - * @param value the new value. - */ - public static void setStaticFieldValue(@NotNull Class type, @NotNull String fieldName, @NotNull Object value) { - try { - Field field = getStaticField(type, fieldName); - field.set(null, value); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Set a static field value. + * + * @param type the class. + * @param fieldName the field name. + * @param value the new value. + */ + public static void setStaticFieldValue(Class type, String fieldName, Object value) { + try { + Field field = getStaticField(type, fieldName); + field.set(null, value); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Set a static field value. - * - * @param type the class. - * @param fieldName thr field name. - * @param value the new value. - */ - public static void setUnsafeStaticFieldValue(@NotNull Class type, @NotNull String fieldName, @NotNull Object value) { - try { - Field field = getUnsafeStaticField(type, fieldName); - field.set(null, value); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Set a static field value. + * + * @param type the class. + * @param fieldName thr field name. + * @param value the new value. + */ + public static void setUnsafeStaticFieldValue( + Class type, + String fieldName, + Object value) { + try { + Field field = getUnsafeStaticField(type, fieldName); + field.set(null, value); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Change a static field value. - * - * @param field the field. - * @param value the new value. - */ - public static void setStaticFieldValue(@NotNull Field field, @NotNull Object value) { - try { - field.set(null, value); - } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } + } + + /** + * Change a static field value. + * + * @param field the field. + * @param value the new value. + */ + public static void setStaticFieldValue(Field field, Object value) { + try { + field.set(null, value); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); } - - /** - * Get a method of the type by the method name and arg types. - * - * @param type the type. - * @param methodName the method name. - * @param argTypes the arg types. - * @return the found method. - */ - public static @NotNull Method getMethod(@NotNull Class type, @NotNull String methodName, Class... argTypes) { - try { - return type.getDeclaredMethod(methodName, argTypes); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } + } + + /** + * Get a method of the type by the method name and arg types. + * + * @param type the type. + * @param methodName the method name. + * @param argTypes the arg types. + * @return the found method. + */ + public static Method getMethod(Class type, String methodName, Class... argTypes) { + try { + return type.getDeclaredMethod(methodName, argTypes); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); } - - /** - * Call a void method of the object by the name. - * - * @param object the object. - * @param methodName the method name. - */ - public static void callVoidMethod(@NotNull Object object, @NotNull String methodName) { - try { - getMethod(object.getClass(), methodName).invoke(object); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } + } + + /** + * Call a void method of the object by the name. + * + * @param object the object. + * @param methodName the method name. + */ + public static void callVoidMethod(Object object, String methodName) { + try { + getMethod(object.getClass(), methodName).invoke(object); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); } - - /** - * Call a void method of the object by the name using full access. - * - * @param object the object. - * @param methodName the method name. - */ - public static void callUnsafeVoidMethod(@NotNull Object object, @NotNull String methodName) { - try { - Method method = getMethod(object.getClass(), methodName); - method.setAccessible(true); - method.invoke(object); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } + } + + /** + * Call a void method of the object by the name using full access. + * + * @param object the object. + * @param methodName the method name. + */ + public static void callUnsafeVoidMethod(Object object, String methodName) { + try { + Method method = getMethod(object.getClass(), methodName); + method.setAccessible(true); + method.invoke(object); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); } + } - private ReflectionUtils() { - throw new IllegalArgumentException(); - } + private ReflectionUtils() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/Reloadable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/Reloadable.java index aefc53d6..70083aad 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/Reloadable.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/Reloadable.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.util; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface for implementing the method for reloading the object to new version of the object. @@ -8,12 +8,13 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface Reloadable { - /** - * Reload this object to version of the object. - * - * @param updated the updated object. - */ - void reload(@NotNull E updated); + /** + * Reload this object to version of the object. + * + * @param updated the updated object. + */ + void reload(E updated); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/StringUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/StringUtils.java index 4166d1cd..056aa754 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/StringUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/StringUtils.java @@ -7,436 +7,437 @@ import java.security.NoSuchAlgorithmException; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The class with utility methods for working with strings. * * @author JavaSaBr */ +@NullMarked public class StringUtils { - public static final String EMPTY = ""; - - private static final Pattern EMAIL_PATTERN = Pattern.compile( - "^[_\\p{L}0-9-]+(\\.[_\\p{L}0-9-]+)*@[\\p{L}0-9]+" + - "(\\.[\\p{L}0-9]+)*(\\.[\\p{L}]{2,})$", - Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE - ); - - private static final ThreadLocal LOCAL_HASH_MD = - ThreadLocal.withInitial(StringUtils::getHashMD5); - - /** - * Return an empty string if the received string is null. - * - * @param string the string. - * @return an empty string if the received string is null. - */ - public static @NotNull String emptyIfNull(@Nullable String string) { - return string == null ? EMPTY : string; + public static final String EMPTY = ""; + + private static final Pattern EMAIL_PATTERN = Pattern.compile( + "^[_\\p{L}0-9-]+(\\.[_\\p{L}0-9-]+)*@[\\p{L}0-9]+" + "(\\.[\\p{L}0-9]+)*(\\.[\\p{L}]{2,})$", + Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); + + private static final ThreadLocal LOCAL_HASH_MD = ThreadLocal.withInitial(StringUtils::getHashMD5); + + /** + * Return an empty string if the received string is null. + * + * @param string the string. + * @return an empty string if the received string is null. + */ + public static String emptyIfNull(@Nullable String string) { + return string == null ? EMPTY : string; + } + + /** + * Return the another string if the received string is empty. + * + * @param string the string. + * @param another the another string. + * @return the another string if the received string is empty. + */ + public static String ifEmpty(@Nullable String string, String another) { + return isEmpty(string) ? another : string; + } + + /** + * Check a string email. + * + * @param email the string email. + * @return true if the email is correct. + */ + public static boolean isValidEmail(String email) { + var matcher = EMAIL_PATTERN.matcher(email); + return matcher.matches(); + } + + /** + * Simple check of the string value about does it look like an email. + * + * @param value the string value. + * @return true if it looks like an email. + */ + public static boolean isEmail(String value) { + + var lastDotIndex = value.lastIndexOf('.'); + var lastSignIndex = value.lastIndexOf('@'); + + return lastSignIndex > 1 && lastDotIndex > lastSignIndex && lastDotIndex < value.length() - 1; + } + + /** + * Compare two strings. + * + * @param first the first string. + * @param second the second string. + * @return 1 if the first string is null or is greater then second, 0 if the first string is the same or -1. + */ + public static int compare(@Nullable String first, @Nullable String second) { + if (first == null) { + return 1; + } else if (second == null) { + return -1; } - - /** - * Return the another string if the received string is empty. - * - * @param string the string. - * @param another the another string. - * @return the another string if the received string is empty. - */ - public static @NotNull String ifEmpty(@Nullable String string, @NotNull String another) { - return isEmpty(string) ? another : string; + return first.compareTo(second); + } + + /** + * Compare two strings with ignoring case. + * + * @param first the first string. + * @param second the second string. + * @return 1 if the first string is null or is greater then second, 0 if the first string is the same or -1. + */ + public static int compareIgnoreCase(@Nullable String first, @Nullable String second) { + if (first == null) { + return 1; + } else if (second == null) { + return -1; } - - /** - * Check a string email. - * - * @param email the string email. - * @return true if the email is correct. - */ - public static boolean isValidEmail(@NotNull String email) { - var matcher = EMAIL_PATTERN.matcher(email); - return matcher.matches(); + return first.compareToIgnoreCase(second); + } + + /** + * Compare two strings. + * + * @param first the first string. + * @param second the second string. + * @return true if these strings are equal. + */ + public static boolean equals(@Nullable String first, @Nullable String second) { + return !(first == null || second == null) && first.equals(second); + } + + /** + * Compare two strings with ignoring case. + * + * @param first the first string. + * @param second the second string. + * @return true if these strings are equal. + */ + public static boolean equalsIgnoreCase(@Nullable String first, @Nullable String second) { + return !(first == null || second == null) && first.equalsIgnoreCase(second); + } + + /** + * Print stack trace of an exception to a string. + * + * @param throwable the exception. + * @return the stack trace. + */ + public static String toString(Throwable throwable) { + return toString(throwable, 6); + } + + /** + * Print stack trace of an exception to a string. + * + * @param throwable the exception. + * @param deepLevel the max level of deep. + * @return the stack trace. + */ + public static String toString(Throwable throwable, int deepLevel) { + + var writer = new StringWriter(); + var printWriter = new PrintWriter(writer); + + throwable.printStackTrace(printWriter); + + var stackTrace = new StringBuilder(writer.toString()); + + int level = 0; + + for (var cause = throwable.getCause(); cause != null && level < deepLevel; cause = cause.getCause(), level++) { + + writer = new StringWriter(); + printWriter = new PrintWriter(writer); + + cause.printStackTrace(printWriter); + + stackTrace.append("\n caused by "); + stackTrace.append(writer.toString()); } - /** - * Simple check of the string value about does it look like an email. - * - * @param value the string value. - * @return true if it looks like an email. - */ - public static boolean isEmail(@NotNull String value) { - - var lastDotIndex = value.lastIndexOf('.'); - var lastSignIndex = value.lastIndexOf('@'); - - return lastSignIndex > 1 && - lastDotIndex > lastSignIndex && - lastDotIndex < value.length() - 1; + return stackTrace.toString(); + } + + /** + * Generate a random string using Aa-Zz characters. + * + * @param length the length of result string. + * @return the new string. + */ + public static String generate(int length) { + return generate(length, length); + } + + /** + * Generate a random string using Aa-Zz characters. + * + * @param minLength the min length of result string. + * @param maxLength the max length of result string. + * @return the new string. + */ + public static String generate(int minLength, int maxLength) { + + var localRandom = ThreadLocalRandom.current(); + var length = minLength == maxLength ? maxLength : localRandom.nextInt(minLength, maxLength); + var array = new char[length]; + var min = Math.min('a', 'A'); + var max = Math.max('z', 'z'); + + for (int i = 0; i < length; i++) { + array[i] = (char) localRandom.nextInt(min, max); } - /** - * Compare two strings. - * - * @param first the first string. - * @param second the second string. - * @return 1 if the first string is null or is greater then second, 0 if the first string is the same or -1. - */ - public static int compare(@Nullable String first, @Nullable String second) { - if (first == null) return 1; - else if (second == null) return -1; - return first.compareTo(second); + return String.valueOf(array); + } + + /** + * @return the md5 message digest. + */ + private static MessageDigest getHashMD5() { + try { + return MessageDigest.getInstance("MD5"); + } catch (final NoSuchAlgorithmException e) { + throw new RuntimeException(e); } - - /** - * Compare two strings with ignoring case. - * - * @param first the first string. - * @param second the second string. - * @return 1 if the first string is null or is greater then second, 0 if the first string is the same or -1. - */ - public static int compareIgnoreCase(@Nullable String first, @Nullable String second) { - if (first == null) return 1; - else if (second == null) return -1; - return first.compareToIgnoreCase(second); - } - - /** - * Compare two strings. - * - * @param first the first string. - * @param second the second string. - * @return true if these strings are equal. - */ - public static boolean equals(@Nullable String first, @Nullable String second) { - return !(first == null || second == null) && first.equals(second); + } + + /** + * Returns true if the string empty or null. + * + * @param string the string. + * @return true if the string is null or empty. + */ + public static boolean isEmpty(@Nullable String string) { + return string == null || string.isEmpty(); + } + + /** + * Returns true if the string isn't empty. + * + * @param string the string. + * @return true if the string isn't empty. + */ + public static boolean isNotEmpty(@Nullable String string) { + return !isEmpty(string); + } + + /** + * Gets the length of the string. + * + * @param string the string. + * @return length or 0 if a string is null or empty. + */ + public static int length(@Nullable String string) { + return string == null ? 0 : string.length(); + } + + /** + * Encode the string to hash MD5. + * + * @param string a string. + * @return the encoded string. + */ + public static String toMD5(String string) { + final MessageDigest hashMD5 = LOCAL_HASH_MD.get(); + hashMD5.update(string.getBytes(), 0, string.length()); + return new BigInteger(1, hashMD5.digest()).toString(16); + } + + /** + * Present the byte array as a hex string. + * + * @param array the byte array. + * @return the hex string. + * @since 9.0.3 + */ + public static String bytesToHexString(byte[] array) { + + var builder = new StringBuilder(array.length * 2); + + for (var value : array) { + + var element = Integer.toHexString(value & 0xFF); + + if (element.length() == 1) { + element = "0" + element; + } + + builder.append(element); } - /** - * Compare two strings with ignoring case. - * - * @param first the first string. - * @param second the second string. - * @return true if these strings are equal. - */ - public static boolean equalsIgnoreCase(@Nullable String first, @Nullable String second) { - return !(first == null || second == null) && first.equalsIgnoreCase(second); - } - - /** - * Print stack trace of an exception to a string. - * - * @param throwable the exception. - * @return the stack trace. - */ - public static @NotNull String toString(@NotNull Throwable throwable) { - return toString(throwable, 6); - } - - /** - * Print stack trace of an exception to a string. - * - * @param throwable the exception. - * @param deepLevel the max level of deep. - * @return the stack trace. - */ - public static @NotNull String toString(@NotNull Throwable throwable, int deepLevel) { - - var writer = new StringWriter(); - var printWriter = new PrintWriter(writer); - - throwable.printStackTrace(printWriter); + return builder.toString(); + } - var stackTrace = new StringBuilder(writer.toString()); + /** + * Parse the hex string to a byte array. + * + * @param string the hex string. + * @return the byte array. + * @since 9.0.3 + */ + public static byte[] hexStringToBytes(String string) { - int level = 0; + var array = string.toCharArray(); + var result = new byte[string.length() / 2]; - for (var cause = throwable.getCause(); cause != null && level < deepLevel; cause = cause.getCause(), level++) { - - writer = new StringWriter(); - printWriter = new PrintWriter(writer); - - cause.printStackTrace(printWriter); - - stackTrace.append("\n caused by "); - stackTrace.append(writer.toString()); - } - - return stackTrace.toString(); + for (int i = 0, g = 0, length = array.length - 1; i < length; i += 2) { + var element = String.valueOf(array, i, 2); + result[g++] = (byte) Integer.parseInt(element, 16); } - /** - * Generate a random string using Aa-Zz characters. - * - * @param length the length of result string. - * @return the new string. - */ - public static @NotNull String generate(int length) { - return generate(length, length); - } + return result; + } - /** - * Generate a random string using Aa-Zz characters. - * - * @param minLength the min length of result string. - * @param maxLength the max length of result string. - * @return the new string. - */ - public static @NotNull String generate(int minLength, int maxLength) { - - var localRandom = ThreadLocalRandom.current(); - var length = minLength == maxLength ? maxLength : localRandom.nextInt(minLength, maxLength); - var array = new char[length]; - var min = Math.min('a', 'A'); - var max = Math.max('z', 'z'); - - for (int i = 0; i < length; i++) { - array[i] = (char) localRandom.nextInt(min, max); - } - - return String.valueOf(array); - } + /** + * Convert the string from HEX to a plain string. + * + * @param string the HEX string. + * @return the plain string. + * @since 9.0.3 + */ + public static String fromHex(String string) { - /** - * @return the md5 message digest. - */ - private static @NotNull MessageDigest getHashMD5() { - try { - return MessageDigest.getInstance("MD5"); - } catch (final NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - /** - * Returns true if the string empty or null. - * - * @param string the string. - * @return true if the string is null or empty. - */ - public static boolean isEmpty(@Nullable String string) { - return string == null || string.isEmpty(); - } - - /** - * Returns true if the string isn't empty. - * - * @param string the string. - * @return true if the string isn't empty. - */ - public static boolean isNotEmpty(@Nullable String string) { - return !isEmpty(string); - } - - /** - * Gets the length of the string. - * - * @param string the string. - * @return length or 0 if a string is null or empty. - */ - public static int length(@Nullable String string) { - return string == null ? 0 : string.length(); - } + var array = string.toCharArray(); + var builder = new StringBuilder(string.length() / 4); - /** - * Encode the string to hash MD5. - * - * @param string a string. - * @return the encoded string. - */ - public static @NotNull String toMD5(@NotNull String string) { - final MessageDigest hashMD5 = LOCAL_HASH_MD.get(); - hashMD5.update(string.getBytes(), 0, string.length()); - return new BigInteger(1, hashMD5.digest()).toString(16); + for (int i = 0, length = array.length - 3; i < length; i += 4) { + var element = String.valueOf(array, i, 4); + builder.append((char) Integer.parseInt(element, 16)); } - /** - * Present the byte array as a hex string. - * - * @param array the byte array. - * @return the hex string. - * @since 9.0.3 - */ - public static @NotNull String bytesToHexString(@NotNull byte[] array) { + return builder.toString(); + } - var builder = new StringBuilder(array.length * 2); + /** + * Convert the plain string to a HEX string. + * + * @param string the plain string. + * @return the hex string. + * @since 9.0.3 + */ + public static String toHex(String string) { - for (var value : array) { + var builder = new StringBuilder(string.length() * 2); - var element = Integer.toHexString(value & 0xFF); + for (int i = 0, length = string.length(); i < length; i++) { - if (element.length() == 1) { - element = "0" + element; - } + var charAt = string.charAt(i); + var element = Integer.toHexString(charAt); - builder.append(element); - } + if (element.length() == 1) { + element = "000" + element; + } else if (element.length() == 2) { + element = "00" + element; + } else if (element.length() == 3) { + element = "0" + element; + } - return builder.toString(); + builder.append(element); } - /** - * Parse the hex string to a byte array. - * - * @param string the hex string. - * @return the byte array. - * @since 9.0.3 - */ - public static @NotNull byte[] hexStringToBytes(@NotNull String string) { - - var array = string.toCharArray(); - var result = new byte[string.length() / 2]; - - for (int i = 0, g = 0, length = array.length - 1; i < length; i += 2) { - var element = String.valueOf(array, i, 2); - result[g++] = (byte) Integer.parseInt(element, 16); - } - - return result; + return builder.toString(); + } + + /** + * Replace the variable in the string. + * + * @param string the source string. + * @param firstName the variable's name. + * @param firstVal the variable's value. + * @return result string. + */ + public static String replace(String string, String firstName, String firstVal) { + + var capacity = string.length(); + capacity = capacity - firstName.length() + firstVal.length(); + capacity = Math.max(capacity, string.length()); + + var builder = new StringBuilder(capacity); + builder.append(string); + + replace(builder, firstName, firstVal); + + return builder.toString(); + } + + /** + * Replace the variables in the string. + * + * @param string the source string. + * @param firstName the first variable's name. + * @param firstVal the first variable's value. + * @param secondName the second variable's name. + * @param secondVal the second variable's value. + * @return result string. + */ + public static String replace( + String string, + String firstName, + String firstVal, + String secondName, + String secondVal) { + + var capacity = string.length(); + capacity = capacity - firstName.length() + firstVal.length(); + capacity = capacity - secondName.length() + secondVal.length(); + capacity = Math.max(capacity, string.length()); + + var builder = new StringBuilder(capacity); + builder.append(string); + + replace(builder, firstName, firstVal); + replace(builder, secondName, secondVal); + + return builder.toString(); + } + + /** + * Replace the variables in the string. + * + * @param string the source string. + * @param params the variable's parameters, name -> val, name -> val. + * @return result string. + * @throws IllegalArgumentException if params count < 2 or % 2 != 0 + */ + public static String replace(String string, String... params) { + + if (params.length < 2 || params.length % 2 != 0) { + throw new IllegalArgumentException("Wrong params count."); } - /** - * Convert the string from HEX to a plain string. - * - * @param string the HEX string. - * @return the plain string. - * @since 9.0.3 - */ - public static @NotNull String fromHex(@NotNull String string) { - - var array = string.toCharArray(); - var builder = new StringBuilder(string.length() / 4); + var capacity = string.length(); - for (int i = 0, length = array.length - 3; i < length; i += 4) { - var element = String.valueOf(array, i, 4); - builder.append((char) Integer.parseInt(element, 16)); - } - - return builder.toString(); + for (int i = 0; i < params.length - 1; i += 2) { + capacity = capacity - params[i].length() + params[i + 1].length(); } - /** - * Convert the plain string to a HEX string. - * - * @param string the plain string. - * @return the hex string. - * @since 9.0.3 - */ - public static @NotNull String toHex(@NotNull String string) { - - var builder = new StringBuilder(string.length() * 2); - - for (int i = 0, length = string.length(); i < length; i++) { + capacity = Math.max(capacity, string.length()); - var charAt = string.charAt(i); - var element = Integer.toHexString(charAt); + var builder = new StringBuilder(capacity); + builder.append(string); - if (element.length() == 1) { - element = "000" + element; - } else if (element.length() == 2) { - element = "00" + element; - } else if (element.length() == 3) { - element = "0" + element; - } - - builder.append(element); - } - - return builder.toString(); + for (var i = 0; i < params.length - 1; i += 2) { + replace(builder, params[i], params[i + 1]); } - /** - * Replace the variable in the string. - * - * @param string the source string. - * @param firstName the variable's name. - * @param firstVal the variable's value. - * @return result string. - */ - public static @NotNull String replace(@NotNull String string, @NotNull String firstName, @NotNull String firstVal) { - - var capacity = string.length(); - capacity = capacity - firstName.length() + firstVal.length(); - capacity = Math.max(capacity, string.length()); - - var builder = new StringBuilder(capacity); - builder.append(string); - - replace(builder, firstName, firstVal); - - return builder.toString(); - } - - /** - * Replace the variables in the string. - * - * @param string the source string. - * @param firstName the first variable's name. - * @param firstVal the first variable's value. - * @param secondName the second variable's name. - * @param secondVal the second variable's value. - * @return result string. - */ - public static @NotNull String replace( - @NotNull String string, - @NotNull String firstName, - @NotNull String firstVal, - @NotNull String secondName, - @NotNull String secondVal - ) { - - var capacity = string.length(); - capacity = capacity - firstName.length() + firstVal.length(); - capacity = capacity - secondName.length() + secondVal.length(); - capacity = Math.max(capacity, string.length()); - - var builder = new StringBuilder(capacity); - builder.append(string); - - replace(builder, firstName, firstVal); - replace(builder, secondName, secondVal); - - return builder.toString(); - } - - /** - * Replace the variables in the string. - * - * @param string the source string. - * @param params the variable's parameters, name -> val, name -> val. - * @return result string. - * @throws IllegalArgumentException if params count < 2 or % 2 != 0 - */ - public static @NotNull String replace(@NotNull String string, @NotNull String... params) { - - if (params.length < 2 || params.length % 2 != 0) { - throw new IllegalArgumentException("Wrong params count."); - } - - var capacity = string.length(); - - for (int i = 0; i < params.length - 1; i += 2) { - capacity = capacity - params[i].length() + params[i + 1].length(); - } - - capacity = Math.max(capacity, string.length()); - - var builder = new StringBuilder(capacity); - builder.append(string); - - for (var i = 0; i < params.length - 1; i += 2) { - replace(builder, params[i], params[i + 1]); - } - - return builder.toString(); - } + return builder.toString(); + } - private static void replace(@NotNull StringBuilder builder, @NotNull String name, @NotNull String value) { + private static void replace(StringBuilder builder, String name, String value) { - for (int index = builder.indexOf(name), count = 0; - index != -1 && count < 100; index = builder.indexOf(name), count++) { - builder.replace(index, index + name.length(), value); - } + for (int index = builder.indexOf(name), count = 0; + index != -1 && count < 100; index = builder.indexOf(name), count++) { + builder.replace(index, index + name.length(), value); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java index 0deb7a99..5d520118 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java @@ -16,380 +16,372 @@ import javasabr.rlib.common.function.NotNullSafeTriFunction; import javasabr.rlib.common.function.SafeRunnable; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The utility class. * * @author JavaSaBr */ +@NullMarked public final class Utils { - /** - * Get a folder of a class. - * - * @param cs the class. - * @return the path to the folder. - */ - public static @NotNull Path getRootFolderFromClass(@NotNull final Class cs) { + /** + * Get a folder of a class. + * + * @param cs the class. + * @return the path to the folder. + */ + public static Path getRootFolderFromClass(Class cs) { - var className = cs.getName(); - var builder = new StringBuilder(className.length()) - .append('/'); + var className = cs.getName(); + var builder = new StringBuilder(className.length()).append('/'); - for (int i = 0, length = className.length(); i < length; i++) { + for (int i = 0, length = className.length(); i < length; i++) { - var ch = className.charAt(i); + var ch = className.charAt(i); - if (ch == '.') { - ch = '/'; - } + if (ch == '.') { + ch = '/'; + } - builder.append(ch); - } - - builder.append(".class"); - - className = builder.toString(); - - try { - - var url = Utils.class.getResource(className); - - var path = url.getPath(); - path = path.substring(0, path.length() - className.length()); - path = path.substring(0, path.lastIndexOf('/')); + builder.append(ch); + } - var uri = new URI(path); + builder.append(".class"); - path = uri.getPath(); - path = path.replaceAll("%20", " "); + className = builder.toString(); - if (File.separatorChar != '/') { + try { - var pathBuilder = new StringBuilder(); + var url = Utils.class.getResource(className); - for (int i = 0, length = path.length(); i < length; i++) { + var path = url.getPath(); + path = path.substring(0, path.length() - className.length()); + path = path.substring(0, path.lastIndexOf('/')); - var ch = path.charAt(i); + var uri = new URI(path); - if (ch == '/' && i == 0) { - continue; - } + path = uri.getPath(); + path = path.replaceAll("%20", " "); - if (ch == '/') { - ch = File.separatorChar; - } + if (File.separatorChar != '/') { - pathBuilder.append(ch); - } + var pathBuilder = new StringBuilder(); - path = pathBuilder.toString(); - } + for (int i = 0, length = path.length(); i < length; i++) { - var file = Paths.get(path); + var ch = path.charAt(i); - while (path.lastIndexOf(File.separatorChar) != -1 && !Files.exists(file)) { - path = path.substring(0, path.lastIndexOf(File.separatorChar)); - file = Paths.get(uri); - } + if (ch == '/' && i == 0) { + continue; + } - return file; + if (ch == '/') { + ch = File.separatorChar; + } - } catch (Exception e) { - throw new RuntimeException(e); + pathBuilder.append(ch); } - } - /** - * Get a username of a computer user. - * - * @return the username. - */ - public static @NotNull String getUserName() { - return System.getProperty("user.name"); - } + path = pathBuilder.toString(); + } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param function the function. - */ - public static void unchecked(@NotNull SafeRunnable function) { - try { - function.run(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + var file = Paths.get(path); - /** - * Try to execute a function with some result. - * - * @param function the function. - * @param the result's type. - * @return the result or null. - * @since 9.5.0 - */ - public static @Nullable R tryGet(@NotNull NotNullSafeSupplier function) { - try { - return function.get(); - } catch (Exception e) { - // can be ignored - return null; - } - } + while (path.lastIndexOf(File.separatorChar) != -1 && !Files.exists(file)) { + path = path.substring(0, path.lastIndexOf(File.separatorChar)); + file = Paths.get(uri); + } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the argument. - * @param function the function. - * @param the argument's type. - */ - public static void unchecked(@NotNull F first, @NotNull NotNullSafeConsumer function) { - try { - function.accept(first); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + return file; - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the first argument's type. - * @param the second argument's type. - */ - public static void unchecked( - @NotNull F first, - @NotNull S second, - @NotNull NotNullSafeBiConsumer consumer - ) { - try { - consumer.accept(first, second); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param function the function. - * @param the result type. - * @return the result. - */ - public static @NotNull R uncheckedGet(@NotNull NotNullSafeFactory function) { - try { - return function.get(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } + } + + /** + * Get a username of a computer user. + * + * @return the username. + */ + public static String getUserName() { + return System.getProperty("user.name"); + } + + /** + * Execute the function with auto-converting a checked exception to an unchecked. + * + * @param function the function. + */ + public static void unchecked(SafeRunnable function) { + try { + function.run(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result. - */ - public static @NotNull R uncheckedGet( - @NotNull F argument, - @NotNull NotNullSafeFunction function - ) { - try { - return function.apply(argument); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } + } + + /** + * Try to execute a function with some result. + * + * @param function the function. + * @param the result's type. + * @return the result or null. + * @since 9.5.0 + */ + public static @Nullable R tryGet(NotNullSafeSupplier function) { + try { + return function.get(); + } catch (Exception e) { + // can be ignored + return null; } - - /** - * Execute the function with returning default value if got an exception. - * - * @param argument the argument. - * @param function the function. - * @param def the default value. - * @param the argument's type. - * @param the result's type. - * @return the result. - */ - public static @NotNull R uncheckedGet( - @NotNull F argument, - @NotNull NotNullSafeFunction function, - @NotNull R def - ) { - try { - return function.apply(argument); - } catch (Exception e) { - return def; - } + } + + /** + * Execute the function with auto-converting a checked exception to an unchecked. + * + * @param first the argument. + * @param function the function. + * @param the argument's type. + */ + public static void unchecked(F first, NotNullSafeConsumer function) { + try { + function.accept(first); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first's type. - * @param the second's type. - * @param the result's type. - * @return the result. - * @since 9.2.1 - */ - public static @NotNull R uncheckedGet( - @NotNull F first, - @NotNull S second, - @NotNull NotNullSafeBiFunction function - ) { - try { - return function.apply(first, second); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } + } + + /** + * Execute the function with auto-converting a checked exception to an unchecked. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the first argument's type. + * @param the second argument's type. + */ + public static void unchecked( + F first, + S second, + NotNullSafeBiConsumer consumer) { + try { + consumer.accept(first, second); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first's type. - * @param the second's type. - * @param the third's type. - * @param the result's type. - * @return the result. - * @since 9.9.0 - */ - public static @NotNull R uncheckedGet( - @NotNull F first, - @NotNull S second, - @NotNull T third, - @NotNull NotNullSafeTriFunction function - ) { - try { - return function.apply(first, second, third); - } catch (IOException e) { - throw new UncheckedIOException(e); - } catch (Exception e) { - throw new RuntimeException(e); - } + } + + /** + * Execute the function with auto-converting a checked exception to an unchecked. + * + * @param function the function. + * @param the result type. + * @return the result. + */ + public static R uncheckedGet(NotNullSafeFactory function) { + try { + return function.get(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Try to execute a function with some result. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result or null. - * @since 9.3.0 - */ - public static @Nullable R tryGet( - @NotNull F argument, - @NotNull NotNullSafeFunction function - ) { - try { - return function.apply(argument); - } catch (Exception e) { - // can be ignored - return null; - } + } + + /** + * Execute the function with auto-converting a checked exception to an unchecked. + * + * @param argument the argument. + * @param function the function. + * @param the argument's type. + * @param the result's type. + * @return the result. + */ + public static R uncheckedGet(F argument, NotNullSafeFunction function) { + try { + return function.apply(argument); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Try to execute a function with some result. - * - * @param argument the argument. - * @param function the function. - * @param def the default value. - * @param the argument's type. - * @param the result's type. - * @return the result or null. - * @since 9.3.0 - */ - public static @NotNull R tryGet( - @NotNull F argument, - @NotNull NotNullSafeFunction function, - @NotNull R def - ) { - try { - return function.apply(argument); - } catch (Exception e) { - // can be ignored - return def; - } + } + + /** + * Execute the function with returning default value if got an exception. + * + * @param argument the argument. + * @param function the function. + * @param def the default value. + * @param the argument's type. + * @param the result's type. + * @return the result. + */ + public static R uncheckedGet( + F argument, + NotNullSafeFunction function, + R def) { + try { + return function.apply(argument); + } catch (Exception e) { + return def; } - - /** - * Try to execute a function with some result and convert this result to another. - * - * @param argument the argument. - * @param function the function. - * @param resultConverter the result converter. - * @param the argument's type. - * @param the function result's type. - * @param the converter result's type. - * @return the final result or null. - * @since 9.3.0 - */ - public static @Nullable FR tryGetAndConvert( - @NotNull F argument, - @NotNull NotNullSafeFunction function, - @NotNull NotNullSafeFunction resultConverter - ) { - try { - return resultConverter.apply(function.apply(argument)); - } catch (Exception e) { - // can be ignored - return null; - } + } + + /** + * Execute the function with auto-converting a checked exception to an unchecked. + * + * @param first the first argument. + * @param second the second argument. + * @param function the function. + * @param the first's type. + * @param the second's type. + * @param the result's type. + * @return the result. + * @since 9.2.1 + */ + public static R uncheckedGet( + F first, + S second, + NotNullSafeBiFunction function) { + try { + return function.apply(first, second); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Print an exception to log. - * - * @param exception the exception. - * @since 9.8.0 - */ - public static void print(@NotNull Exception exception) { - LoggerManager.getDefaultLogger().warning(exception); + } + + /** + * Execute the function with auto-converting a checked exception to an unchecked. + * + * @param first the first argument. + * @param second the second argument. + * @param function the function. + * @param the first's type. + * @param the second's type. + * @param the third's type. + * @param the result's type. + * @return the result. + * @since 9.9.0 + */ + public static R uncheckedGet( + F first, + S second, + T third, + NotNullSafeTriFunction function) { + try { + return function.apply(first, second, third); + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Print a message to log. - * - * @param message the message. - * @since 9.8.0 - */ - public static void print(@NotNull String message) { - LoggerManager.getDefaultLogger().warning(message); + } + + /** + * Try to execute a function with some result. + * + * @param argument the argument. + * @param function the function. + * @param the argument's type. + * @param the result's type. + * @return the result or null. + * @since 9.3.0 + */ + public static @Nullable R tryGet(F argument, NotNullSafeFunction function) { + try { + return function.apply(argument); + } catch (Exception e) { + // can be ignored + return null; } - - private Utils() { - throw new RuntimeException(); + } + + /** + * Try to execute a function with some result. + * + * @param argument the argument. + * @param function the function. + * @param def the default value. + * @param the argument's type. + * @param the result's type. + * @return the result or null. + * @since 9.3.0 + */ + public static R tryGet( + F argument, + NotNullSafeFunction function, + R def) { + try { + return function.apply(argument); + } catch (Exception e) { + // can be ignored + return def; + } + } + + /** + * Try to execute a function with some result and convert this result to another. + * + * @param argument the argument. + * @param function the function. + * @param resultConverter the result converter. + * @param the argument's type. + * @param the function result's type. + * @param the converter result's type. + * @return the final result or null. + * @since 9.3.0 + */ + public static @Nullable FR tryGetAndConvert( + F argument, + NotNullSafeFunction function, + NotNullSafeFunction resultConverter) { + try { + return resultConverter.apply(function.apply(argument)); + } catch (Exception e) { + // can be ignored + return null; } + } + + /** + * Print an exception to log. + * + * @param exception the exception. + * @since 9.8.0 + */ + public static void print(Exception exception) { + LoggerManager + .getDefaultLogger() + .warning(exception); + } + + /** + * Print a message to log. + * + * @param message the message. + * @since 9.8.0 + */ + public static void print(String message) { + LoggerManager + .getDefaultLogger() + .warning(message); + } + + private Utils() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/VarTable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/VarTable.java index 157bf47c..0e4d2633 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/VarTable.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/VarTable.java @@ -7,1326 +7,1350 @@ import javasabr.rlib.common.geom.Vector3f; import javasabr.rlib.common.util.dictionary.DictionaryFactory; import javasabr.rlib.common.util.dictionary.ObjectDictionary; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The utility class to contain properties of different types. * * @author JavaSaBr */ +@NullMarked public class VarTable { - /** - * The table with values. - */ - @NotNull - private final ObjectDictionary values; - - /** - * @since 8.1.0 - */ - public VarTable() { - this.values = DictionaryFactory.newObjectDictionary(); - } - - /** - * Clear this table. - */ - public void clear() { - values.clear(); - } - - /** - * Get a value by the key. - * - * @param key the key. - * @param the value's type. - * @return the value. - * @throws IllegalArgumentException if the value is null. - */ - public @NotNull T get(@NotNull String key) { - - T result = ClassUtils.unsafeCast(values.get(key)); - - if (result != null) { - return result; - } - - throw new IllegalArgumentException("Not found value for the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param key the key. - * @param type the type. - * @return the value. - * @throws IllegalArgumentException if the value is null or has wrong type. - */ - public @NotNull T get(@NotNull String key, @NotNull Class type) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found value for the key: " + key); - } else if (type.isInstance(object)) { - return type.cast(object); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param the default value's type. - * @param key the key. - * @param type the type. - * @param def the default value. - * @return the value or default if the value is null or has wrong type. - */ - public @NotNull T get(@NotNull String key, @NotNull Class type, @NotNull E def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return type.cast(object); - } - - return def; - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param the default value's type. - * @param key the key. - * @param type the type. - * @param def the default value. - * @return the value or default if the value not found. - * @throws IllegalArgumentException if the value has wrong type. - */ - public @Nullable T getNullable(@NotNull String key, @NotNull Class type, @Nullable E def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return type.cast(object); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param key the key. - * @param def the default value. - * @return the value or default if the value is null. - */ - public @NotNull T get(@NotNull String key, @NotNull T def) { - - var object = values.get(key); - - if (object == null) { - return def; - } - - var type = def.getClass(); - - if (type.isInstance(object)) { - return notNull(ClassUtils.unsafeCast(object)); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param key the key. - * @param def the default value. - * @return the value or default if the value is not found. - */ - public @Nullable T getNullable(@NotNull String key, @Nullable T def) { - - var object = values.get(key); - - if (object == null) { - return def; - } - - if (def != null) { - - var type = def.getClass(); - - if (type.isInstance(object)) { - return ClassUtils.unsafeCast(object); - } - - return def; - - } else { - return ClassUtils.unsafeCast(object); - } - } - - /** - * Get an array of a key. - * - * @param the array element's type. - * @param key the key. - * @param type the array's type. - * @param def the default array. - * @return the array. - */ - @SafeVarargs - public final @NotNull T[] getArray(@NotNull String key, @NotNull Class type, @NotNull T... def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return ClassUtils.unsafeNNCast(object); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a boolean value by a key. - * - * @param key the key. - * @return the value. - */ - public boolean getBoolean(@NotNull String key) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found value for the key: " + key); - } else if (object instanceof Boolean) { - return (Boolean) object; - } else if (object instanceof String) { - return Boolean.parseBoolean(object.toString()); - } - - throw new IllegalArgumentException( - "Value: " + object + " cannot be converted to boolean by the key: " + key); - } - - /** - * Get a boolean value by a key. - * - * @param key the key. - * @param def the default value. - * @return the value. - */ - public boolean getBoolean(@NotNull String key, boolean def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Boolean) { - return (Boolean) object; - } else if (object instanceof String) { - return Boolean.parseBoolean(object.toString()); - } - - throw new IllegalArgumentException( - "Value: " + object + " cannot be converted to boolean by the key: " + key); - } - - /** - * Get a boolean array by a key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the boolean array. - */ - public @NotNull boolean[] getBooleanArray(@NotNull String key, @NotNull String regex) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found value for the key: " + key); - } else if (object instanceof boolean[]) { - return (boolean[]) object; - } else if (object instanceof String) { - return parseBooleanArray(regex, object); - } - - throw new IllegalArgumentException( - "Value: " + object + " cannot be converted to boolean array by the key: " + key); - } - - private boolean[] parseBooleanArray(@NotNull String regex, @NotNull Object object) { - - var strings = object.toString().split(regex); - var booleans = new boolean[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - booleans[i] = Boolean.parseBoolean(strings[i].trim()); - } - - return booleans; - } - - /** - * Get a boolean array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the boolean array. - */ - public @NotNull boolean[] getBooleanArray(@NotNull final String key, @NotNull final String regex, - @NotNull final boolean... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof boolean[]) { - return (boolean[]) object; - } else if (object instanceof String) { - return parseBooleanArray(regex, object); - } - - return def; - } - - /** - * Get a byte value by the key. - * - * @param key the key. - * @return the byte. - */ - public byte getByte(@NotNull final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Byte) { - return (Byte) object; - } else if (object instanceof String) { - return Byte.parseByte(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a byte value by the key. - * - * @param key the key. - * @param def the default value. - * @return the byte. - */ - public byte getByte(@NotNull final String key, final byte def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Byte) { - return (Byte) object; - } else if (object instanceof String) { - return Byte.parseByte(object.toString()); - } - - return def; - } - - /** - * Get a byte array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the byte array. - */ - public @NotNull byte[] getByteArray(@NotNull final String key, @NotNull final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof byte[]) { - return (byte[]) object; - } else if (object instanceof String) { - return parseByteArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private byte[] parseByteArray(@NotNull final String regex, @NotNull final Object object) { - - final String[] strings = object.toString().split(regex); - final byte[] result = new byte[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Byte.parseByte(strings[i]); - } - - return result; - } - - /** - * Get a byte array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default byte array. - * @return the byte array. - */ - public @NotNull byte[] getByteArray(@NotNull final String key, @NotNull final String regex, - @NotNull final byte... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof byte[]) { - return (byte[]) object; - } else if (object instanceof String) { - return parseByteArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a double value by the key. - * - * @param key the key. - * @return the value. - */ - public double getDouble(@NotNull final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Double) { - return (Double) object; - } else if (object instanceof String) { - return Double.parseDouble(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a double value by the key. - * - * @param key the key. - * @param def the default value. - * @return the value. - */ - public double getDouble(@NotNull final String key, final double def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Double) { - return (Double) object; - } else if (object instanceof String) { - return Double.parseDouble(object.toString()); - } - - return def; - } - - /** - * Get a double array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the double array. - */ - public @NotNull double[] getDoubleArray(@NotNull final String key, @NotNull final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof double[]) { - return (double[]) object; - } else if (object instanceof String) { - return parseDoubleArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private double[] parseDoubleArray(@NotNull final String regex, @NotNull final Object object) { - - final String[] strings = object.toString().split(regex); - final double[] result = new double[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Double.parseDouble(strings[i]); - } + /** + * The table with values. + */ + private final ObjectDictionary values; + + /** + * @since 8.1.0 + */ + public VarTable() { + this.values = DictionaryFactory.newObjectDictionary(); + } + + /** + * Clear this table. + */ + public void clear() { + values.clear(); + } + + /** + * Get a value by the key. + * + * @param key the key. + * @param the value's type. + * @return the value. + * @throws IllegalArgumentException if the value is null. + */ + public T get(String key) { + + T result = ClassUtils.unsafeCast(values.get(key)); + + if (result != null) { + return result; + } + + throw new IllegalArgumentException("Not found value for the key: " + key); + } + + /** + * Get a value by a key. + * + * @param the value's type. + * @param key the key. + * @param type the type. + * @return the value. + * @throws IllegalArgumentException if the value is null or has wrong type. + */ + public T get(String key, Class type) { + + var object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found value for the key: " + key); + } else if (type.isInstance(object)) { + return type.cast(object); + } + + throw new IllegalArgumentException( + "Value: " + object + " has another type than requested: " + type + " by the key: " + key); + } - return result; + /** + * Get a value by a key. + * + * @param the value's type. + * @param the default value's type. + * @param key the key. + * @param type the type. + * @param def the default value. + * @return the value or default if the value is null or has wrong type. + */ + public T get(String key, Class type, E def) { + + var object = values.get(key); + + if (object == null) { + return def; + } else if (type.isInstance(object)) { + return type.cast(object); + } + + return def; + } + + /** + * Get a value by a key. + * + * @param the value's type. + * @param the default value's type. + * @param key the key. + * @param type the type. + * @param def the default value. + * @return the value or default if the value not found. + * @throws IllegalArgumentException if the value has wrong type. + */ + public @Nullable T getNullable(String key, Class type, @Nullable E def) { + + var object = values.get(key); + + if (object == null) { + return def; + } else if (type.isInstance(object)) { + return type.cast(object); + } + + throw new IllegalArgumentException( + "Value: " + object + " has another type than requested: " + type + " by the key: " + key); + } + + /** + * Get a value by a key. + * + * @param the value's type. + * @param key the key. + * @param def the default value. + * @return the value or default if the value is null. + */ + public T get(String key, T def) { + + var object = values.get(key); + + if (object == null) { + return def; } - /** - * Get a double array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the double array. - */ - public @NotNull double[] getDoubleArray(@NotNull final String key, @NotNull final String regex, - @NotNull final double... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof double[]) { - return (double[]) object; - } else if (object instanceof String) { - return parseDoubleArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } + var type = def.getClass(); - /** - * Get an enum value by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @return the value. - */ - public @NotNull > T getEnum(@NotNull final String key, @NotNull final Class type) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (type.isInstance(object)) { - return type.cast(object); - } else if (object instanceof String) { - return Enum.valueOf(type, object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); + if (type.isInstance(object)) { + return notNull(ClassUtils.unsafeCast(object)); } - /** - * Get an enum value by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @param def the default value. - * @return the value. - */ - public > @NotNull T getEnum(@NotNull final String key, @NotNull final Class type, - @NotNull final T def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return type.cast(object); - } else if (object instanceof String) { - return Enum.valueOf(type, object.toString()); - } - - return def; - } + throw new IllegalArgumentException( + "Value: " + object + " has another type than requested: " + type + " by the key: " + key); + } - /** - * Get an enum array by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @param regex the regex to split if a value is string. - * @return the enum array. - */ - public > @NotNull T[] getEnumArray(@NotNull final String key, @NotNull final Class type, - @NotNull final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Enum[]) { - return notNull(ClassUtils.unsafeCast(object)); - } else if (object instanceof String) { - return parseEnumArray(type, regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } + /** + * Get a value by a key. + * + * @param the value's type. + * @param key the key. + * @param def the default value. + * @return the value or default if the value is not found. + */ + public @Nullable T getNullable(String key, @Nullable T def) { - private > @NotNull T[] parseEnumArray(@NotNull final Class type, @NotNull final String regex, - @NotNull final Object object) { + var object = values.get(key); - final String[] strings = object.toString().split(regex); - final T[] result = notNull(ClassUtils.unsafeCast(ArrayUtils.create(type, strings.length))); + if (object == null) { + return def; + } - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Enum.valueOf(type, strings[i]); - } + if (def != null) { - return result; - } + var type = def.getClass(); - /** - * Get an enum array by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the enum array. - */ - - public > @NotNull T[] getEnumArray(@NotNull final String key, @NotNull final Class type, - @NotNull final String regex, @NotNull final T... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Enum[]) { - return notNull(ClassUtils.unsafeCast(object)); - } else if (object instanceof String) { - return parseEnumArray(type, regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } + if (type.isInstance(object)) { + return ClassUtils.unsafeCast(object); + } - /** - * Get a float value by the key. - * - * @param key the key. - * @return the float value. - */ - public float getFloat(@NotNull final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Float) { - return (Float) object; - } else if (object instanceof String) { - return Float.parseFloat(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a float value by the key. - * - * @param key the key. - * @param def the default value. - * @return the float value. - */ - public float getFloat(@NotNull final String key, final float def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Float) { - return (Float) object; - } else if (object instanceof String) { - return Float.parseFloat(object.toString()); - } - - return def; - } + return def; - /** - * Get a float array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the float array. - */ - public @NotNull float[] getFloatArray(@NotNull final String key, @NotNull final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException(); - } else if (object instanceof float[]) { - return (float[]) object; - } else if (object instanceof String) { - return parseFloatArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); + } else { + return ClassUtils.unsafeCast(object); } + } - private @NotNull float[] parseFloatArray(@NotNull final String regex, @NotNull final Object object) { - - final String[] strings = object.toString().split(regex); - final float[] result = new float[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Float.parseFloat(strings[i]); - } - - return result; - } - - /** - * Get a float array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the float array. - */ - public @NotNull float[] getFloatArray( - @NotNull String key, - @NotNull String regex, - @NotNull float... def - ) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof float[]) { - return (float[]) object; - } else if (object instanceof String) { - return parseFloatArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - - /** - * Get an integer value by the key. - * - * @param key the key. - * @return the integer value. - * @throws IllegalArgumentException if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int. - * @since 8.1.0 - */ - public int getInt(@NotNull String key) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Integer) { - return (Integer) object; - } else if (object instanceof String) { - return Integer.parseInt(object.toString()); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int, key: " + key); - } - - /** - * Get an integer value by the key. - * - * @param key the key. - * @param def the default value. - * @return the integer value or the default value if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int. - * @since 8.1.0 - */ - public int getInt(@NotNull String key, int def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Integer) { - return (Integer) object; - } else if (object instanceof String) { - return Integer.parseInt(object.toString()); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int, key: " + key); - } + /** + * Get an array of a key. + * + * @param the array element's type. + * @param key the key. + * @param type the array's type. + * @param def the default array. + * @return the array. + */ + @SafeVarargs + public final T[] getArray(String key, Class type, T... def) { - /** - * Get an int array value by the key. - * - * @param key the key. - * @return the int array value. - * @throws IllegalStateException if the value can't be presented as int array. - * @throws IllegalArgumentException if the value isn't exist. - * @since 9.2.1 - */ - public @NotNull int[] getIntArray(@NotNull String key) { - - var object = values.get(key); - - if(object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof int[]) { - return (int[]) object; - } else if (object instanceof Integer[]) { - return ArrayUtils.toIntArray((Integer[]) object); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); - } + var object = values.get(key); - /** - * Get an int array value by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the int array value. - * @throws IllegalArgumentException if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int array. - * @since 8.1.0 - */ - public @NotNull int[] getIntArray(@NotNull String key, @NotNull String regex) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof int[]) { - return (int[]) object; - } else if (object instanceof String) { - return ArrayUtils.toIntArray((String) object, regex); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); + if (object == null) { + return def; + } else if (type.isInstance(object)) { + return ClassUtils.unsafeNNCast(object); } - /** - * Get an int array value by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default value. - * @return the int array value or the default value if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int array. - * @since 8.1.0 - */ - public @NotNull int[] getIntArray(@NotNull String key, @NotNull String regex, @NotNull int... def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof int[]) { - return (int[]) object; - } else if (object instanceof String) { - return ArrayUtils.toIntArray((String) object, regex); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); - } + throw new IllegalArgumentException( + "Value: " + object + " has another type than requested: " + type + " by the key: " + key); + } - /** - * Get a long value by the key. - * - * @param key the key. - * @return the long value. - */ - public long getLong(@NotNull final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Long) { - return (Long) object; - } else if (object instanceof String) { - return Long.parseLong(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } + /** + * Get a boolean value by a key. + * + * @param key the key. + * @return the value. + */ + public boolean getBoolean(String key) { - /** - * Get a long value by the key. - * - * @param key the key. - * @param def the default value. - * @return the long value. - */ - public long getLong(@NotNull final String key, final long def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Long) { - return (Long) object; - } else if (object instanceof String) { - return Long.parseLong(object.toString()); - } - - return def; - } + var object = values.get(key); - /** - * Get a long array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the long array. - */ - public @NotNull long[] getLongArray(@NotNull final String key, @NotNull final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof long[]) { - return (long[]) object; - } else if (object instanceof String) { - return parseLongArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); + if (object == null) { + throw new IllegalArgumentException("Not found value for the key: " + key); + } else if (object instanceof Boolean) { + return (Boolean) object; + } else if (object instanceof String) { + return Boolean.parseBoolean(object.toString()); } - private @NotNull long[] parseLongArray(@NotNull final String regex, @NotNull final Object object) { + throw new IllegalArgumentException("Value: " + object + " cannot be converted to boolean by the key: " + key); + } - final String[] strings = object.toString().split(regex); - final long[] result = new long[strings.length]; + /** + * Get a boolean value by a key. + * + * @param key the key. + * @param def the default value. + * @return the value. + */ + public boolean getBoolean(String key, boolean def) { - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Long.parseLong(strings[i]); - } + var object = values.get(key); - return result; + if (object == null) { + return def; + } else if (object instanceof Boolean) { + return (Boolean) object; + } else if (object instanceof String) { + return Boolean.parseBoolean(object.toString()); } - /** - * Get a long array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the long array. - */ - public @NotNull long[] getLongArray(@NotNull final String key, @NotNull final String regex, - @NotNull final long... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof long[]) { - return (long[]) object; - } else if (object instanceof String) { - return parseLongArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } + throw new IllegalArgumentException("Value: " + object + " cannot be converted to boolean by the key: " + key); + } + + /** + * Get a boolean array by a key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the boolean array. + */ + public boolean[] getBooleanArray(String key, String regex) { - /** - * Get a rotation by the key. - * - * @param key the key. - * @return the rotation. - */ - public @NotNull Quaternion4f getRotation(@NotNull final String key) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Quaternion4f) { - return (Quaternion4f) object; - } else if (object instanceof String) { - return parseRotation((String) object); - } - - throw new IllegalArgumentException("Not found " + key); - } + var object = values.get(key); - private @NotNull Quaternion4f parseRotation(@NotNull String object) { + if (object == null) { + throw new IllegalArgumentException("Not found value for the key: " + key); + } else if (object instanceof boolean[]) { + return (boolean[]) object; + } else if (object instanceof String) { + return parseBooleanArray(regex, object); + } + + throw new IllegalArgumentException("Value: " + object + " cannot be converted to boolean array by the key: " + key); + } + + private boolean[] parseBooleanArray(String regex, Object object) { + + var strings = object + .toString() + .split(regex); + var booleans = new boolean[strings.length]; + + for (int i = 0, length = strings.length; i < length; i++) { + booleans[i] = Boolean.parseBoolean(strings[i].trim()); + } + + return booleans; + } + + /** + * Get a boolean array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default array. + * @return the boolean array. + */ + public boolean[] getBooleanArray( + final String key, + final String regex, + final boolean... def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof boolean[]) { + return (boolean[]) object; + } else if (object instanceof String) { + return parseBooleanArray(regex, object); + } + + return def; + } + + /** + * Get a byte value by the key. + * + * @param key the key. + * @return the byte. + */ + public byte getByte(final String key) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Byte) { + return (Byte) object; + } else if (object instanceof String) { + return Byte.parseByte(object.toString()); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a byte value by the key. + * + * @param key the key. + * @param def the default value. + * @return the byte. + */ + public byte getByte(final String key, final byte def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Byte) { + return (Byte) object; + } else if (object instanceof String) { + return Byte.parseByte(object.toString()); + } + + return def; + } + + /** + * Get a byte array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the byte array. + */ + public byte[] getByteArray(final String key, final String regex) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof byte[]) { + return (byte[]) object; + } else if (object instanceof String) { + return parseByteArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + private byte[] parseByteArray(final String regex, final Object object) { + + final String[] strings = object + .toString() + .split(regex); + final byte[] result = new byte[strings.length]; + + for (int i = 0, length = strings.length; i < length; i++) { + result[i] = Byte.parseByte(strings[i]); + } + + return result; + } + + /** + * Get a byte array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default byte array. + * @return the byte array. + */ + public byte[] getByteArray( + final String key, + final String regex, + final byte... def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof byte[]) { + return (byte[]) object; + } else if (object instanceof String) { + return parseByteArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a double value by the key. + * + * @param key the key. + * @return the value. + */ + public double getDouble(final String key) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Double) { + return (Double) object; + } else if (object instanceof String) { + return Double.parseDouble(object.toString()); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a double value by the key. + * + * @param key the key. + * @param def the default value. + * @return the value. + */ + public double getDouble(final String key, final double def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Double) { + return (Double) object; + } else if (object instanceof String) { + return Double.parseDouble(object.toString()); + } + + return def; + } + + /** + * Get a double array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the double array. + */ + public double[] getDoubleArray(final String key, final String regex) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof double[]) { + return (double[]) object; + } else if (object instanceof String) { + return parseDoubleArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + private double[] parseDoubleArray(final String regex, final Object object) { + + final String[] strings = object + .toString() + .split(regex); + final double[] result = new double[strings.length]; + + for (int i = 0, length = strings.length; i < length; i++) { + result[i] = Double.parseDouble(strings[i]); + } + + return result; + } + + /** + * Get a double array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default array. + * @return the double array. + */ + public double[] getDoubleArray( + final String key, + final String regex, + final double... def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof double[]) { + return (double[]) object; + } else if (object instanceof String) { + return parseDoubleArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get an enum value by the key. + * + * @param the type parameter + * @param key the key. + * @param type the type of enum. + * @return the value. + */ + public > T getEnum(final String key, final Class type) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (type.isInstance(object)) { + return type.cast(object); + } else if (object instanceof String) { + return Enum.valueOf(type, object.toString()); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get an enum value by the key. + * + * @param the type parameter + * @param key the key. + * @param type the type of enum. + * @param def the default value. + * @return the value. + */ + public > T getEnum( + final String key, + final Class type, + final T def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (type.isInstance(object)) { + return type.cast(object); + } else if (object instanceof String) { + return Enum.valueOf(type, object.toString()); + } + + return def; + } + + /** + * Get an enum array by the key. + * + * @param the type parameter + * @param key the key. + * @param type the type of enum. + * @param regex the regex to split if a value is string. + * @return the enum array. + */ + public > T[] getEnumArray( + final String key, + final Class type, + final String regex) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Enum[]) { + return notNull(ClassUtils.unsafeCast(object)); + } else if (object instanceof String) { + return parseEnumArray(type, regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + private > T[] parseEnumArray( + final Class type, + final String regex, + final Object object) { + + final String[] strings = object + .toString() + .split(regex); + final T[] result = notNull(ClassUtils.unsafeCast(ArrayUtils.create(type, strings.length))); + + for (int i = 0, length = strings.length; i < length; i++) { + result[i] = Enum.valueOf(type, strings[i]); + } + + return result; + } + + /** + * Get an enum array by the key. + * + * @param the type parameter + * @param key the key. + * @param type the type of enum. + * @param regex the regex to split if a value is string. + * @param def the default array. + * @return the enum array. + */ + + public > T[] getEnumArray( + final String key, + final Class type, + final String regex, + final T... def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Enum[]) { + return notNull(ClassUtils.unsafeCast(object)); + } else if (object instanceof String) { + return parseEnumArray(type, regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a float value by the key. + * + * @param key the key. + * @return the float value. + */ + public float getFloat(final String key) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Float) { + return (Float) object; + } else if (object instanceof String) { + return Float.parseFloat(object.toString()); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a float value by the key. + * + * @param key the key. + * @param def the default value. + * @return the float value. + */ + public float getFloat(final String key, final float def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Float) { + return (Float) object; + } else if (object instanceof String) { + return Float.parseFloat(object.toString()); + } + + return def; + } + + /** + * Get a float array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the float array. + */ + public float[] getFloatArray(final String key, final String regex) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException(); + } else if (object instanceof float[]) { + return (float[]) object; + } else if (object instanceof String) { + return parseFloatArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + private float[] parseFloatArray(final String regex, final Object object) { + + final String[] strings = object + .toString() + .split(regex); + final float[] result = new float[strings.length]; + + for (int i = 0, length = strings.length; i < length; i++) { + result[i] = Float.parseFloat(strings[i]); + } + + return result; + } + + /** + * Get a float array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default array. + * @return the float array. + */ + public float[] getFloatArray(String key, String regex, float... def) { + + var object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof float[]) { + return (float[]) object; + } else if (object instanceof String) { + return parseFloatArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get an integer value by the key. + * + * @param key the key. + * @return the integer value. + * @throws IllegalArgumentException if the value isn't exist. + * @throws IllegalStateException if the value can't be presented as int. + * @since 8.1.0 + */ + public int getInt(String key) { + + var object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Integer) { + return (Integer) object; + } else if (object instanceof String) { + return Integer.parseInt(object.toString()); + } + + throw new IllegalStateException("Value: " + object + " can't be presented as int, key: " + key); + } + + /** + * Get an integer value by the key. + * + * @param key the key. + * @param def the default value. + * @return the integer value or the default value if the value isn't exist. + * @throws IllegalStateException if the value can't be presented as int. + * @since 8.1.0 + */ + public int getInt(String key, int def) { + + var object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Integer) { + return (Integer) object; + } else if (object instanceof String) { + return Integer.parseInt(object.toString()); + } + + throw new IllegalStateException("Value: " + object + " can't be presented as int, key: " + key); + } + + /** + * Get an int array value by the key. + * + * @param key the key. + * @return the int array value. + * @throws IllegalStateException if the value can't be presented as int array. + * @throws IllegalArgumentException if the value isn't exist. + * @since 9.2.1 + */ + public int[] getIntArray(String key) { + + var object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof int[]) { + return (int[]) object; + } else if (object instanceof Integer[]) { + return ArrayUtils.toIntArray((Integer[]) object); + } + + throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); + } + + /** + * Get an int array value by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the int array value. + * @throws IllegalArgumentException if the value isn't exist. + * @throws IllegalStateException if the value can't be presented as int array. + * @since 8.1.0 + */ + public int[] getIntArray(String key, String regex) { + + var object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof int[]) { + return (int[]) object; + } else if (object instanceof String) { + return ArrayUtils.toIntArray((String) object, regex); + } + + throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); + } + + /** + * Get an int array value by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default value. + * @return the int array value or the default value if the value isn't exist. + * @throws IllegalStateException if the value can't be presented as int array. + * @since 8.1.0 + */ + public int[] getIntArray(String key, String regex, int... def) { + + var object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof int[]) { + return (int[]) object; + } else if (object instanceof String) { + return ArrayUtils.toIntArray((String) object, regex); + } + + throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); + } + + /** + * Get a long value by the key. + * + * @param key the key. + * @return the long value. + */ + public long getLong(final String key) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Long) { + return (Long) object; + } else if (object instanceof String) { + return Long.parseLong(object.toString()); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a long value by the key. + * + * @param key the key. + * @param def the default value. + * @return the long value. + */ + public long getLong(final String key, final long def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Long) { + return (Long) object; + } else if (object instanceof String) { + return Long.parseLong(object.toString()); + } + + return def; + } + + /** + * Get a long array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the long array. + */ + public long[] getLongArray(final String key, final String regex) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof long[]) { + return (long[]) object; + } else if (object instanceof String) { + return parseLongArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + private long[] parseLongArray(final String regex, final Object object) { + + final String[] strings = object + .toString() + .split(regex); + final long[] result = new long[strings.length]; + + for (int i = 0, length = strings.length; i < length; i++) { + result[i] = Long.parseLong(strings[i]); + } + + return result; + } + + /** + * Get a long array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default array. + * @return the long array. + */ + public long[] getLongArray( + final String key, + final String regex, + final long... def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof long[]) { + return (long[]) object; + } else if (object instanceof String) { + return parseLongArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a rotation by the key. + * + * @param key the key. + * @return the rotation. + */ + public Quaternion4f getRotation(final String key) { + + var object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Quaternion4f) { + return (Quaternion4f) object; + } else if (object instanceof String) { + return parseRotation((String) object); + } + + throw new IllegalArgumentException("Not found " + key); + } - var values = object.split(","); + private Quaternion4f parseRotation(String object) { - var rotation = new Quaternion4f(); - rotation.setXYZW( - parseFloat(values[0]), - parseFloat(values[1]), - parseFloat(values[2]), - parseFloat(values[3]) - ); + var values = object.split(","); - return rotation; - } + var rotation = new Quaternion4f(); + rotation.setXYZW(parseFloat(values[0]), parseFloat(values[1]), parseFloat(values[2]), parseFloat(values[3])); - /** - * Get a rotation by the key. - * - * @param key the key. - * @param def the default value. - * @return the rotation. - */ - public @NotNull Quaternion4f getRotation(@NotNull final String key, @NotNull final Quaternion4f def) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Quaternion4f) { - return (Quaternion4f) object; - } else if (object instanceof String) { - return parseRotation((String) object); - } - - return def; - } + return rotation; + } - /** - * Get a short value by the key. - * - * @param key the key. - * @return the short value. - */ - public short getShort(@NotNull final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Short) { - return (Short) object; - } else if (object instanceof String) { - return Short.parseShort(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); + /** + * Get a rotation by the key. + * + * @param key the key. + * @param def the default value. + * @return the rotation. + */ + public Quaternion4f getRotation(final String key, final Quaternion4f def) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Quaternion4f) { + return (Quaternion4f) object; + } else if (object instanceof String) { + return parseRotation((String) object); } - /** - * Get a short value by the key. - * - * @param key the key. - * @param def the default value. - * @return the short value. - */ - public short getShort(@NotNull final String key, final short def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Short) { - return (Short) object; - } else if (object instanceof String) { - return Short.parseShort(object.toString()); - } - - return def; - } + return def; + } + + /** + * Get a short value by the key. + * + * @param key the key. + * @return the short value. + */ + public short getShort(final String key) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Short) { + return (Short) object; + } else if (object instanceof String) { + return Short.parseShort(object.toString()); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a short value by the key. + * + * @param key the key. + * @param def the default value. + * @return the short value. + */ + public short getShort(final String key, final short def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Short) { + return (Short) object; + } else if (object instanceof String) { + return Short.parseShort(object.toString()); + } + + return def; + } + + /** + * Get a short array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the short array. + */ + public short[] getShortArray(final String key, final String regex) { + + final Object object = values.get(key); - /** - * Get a short array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the short array. - */ - public @NotNull short[] getShortArray(@NotNull final String key, @NotNull final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof short[]) { - return (short[]) object; - } else if (object instanceof String) { - return parseShortArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof short[]) { + return (short[]) object; + } else if (object instanceof String) { + return parseShortArray(regex, object); } - private @NotNull short[] parseShortArray(@NotNull final String regex, @NotNull final Object object) { - - final String[] strings = object.toString().split(regex); - final short[] result = new short[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Short.parseShort(strings[i]); - } - - return result; - } - - /** - * Get a short array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the short array. - */ - public @NotNull short[] getShortArray(@NotNull final String key, @NotNull final String regex, - @NotNull final short... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof short[]) { - return (short[]) object; - } else if (object instanceof String) { - return parseShortArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a string by the key. - * - * @param key the key. - * @return the string value. - * @throws IllegalArgumentException if the value isn't exist. - */ - public @NotNull String getString(@NotNull String key) { - - var object = values.get(key); + throw new IllegalArgumentException("Not found " + key); + } - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof String) { - return object.toString(); - } + private short[] parseShortArray(final String regex, final Object object) { - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a string by the key. - * - * @param key the key. - * @param def the default string. - * @return the string. - */ - public @NotNull String getString(@NotNull final String key, @NotNull final String def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof String) { - return object.toString(); - } - - return def; - } - - /** - * Get a string by the key. - * - * @param key the key. - * @param def the default string. - * @return the string. - */ - public @Nullable String getNullableString(@NotNull final String key, @Nullable final String def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof String) { - return object.toString(); - } - - return def; - } - - /** - * Get a string array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the string array. - */ - public @NotNull String[] getStringArray(@NotNull final String key, @NotNull final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof String[]) { - return (String[]) object; - } else if (object instanceof String) { - return object.toString().split(regex); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a string array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the string array. - */ - public @NotNull String[] getStringArray(@NotNull final String key, @NotNull final String regex, - @NotNull final String... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof String[]) { - return (String[]) object; - } else if (object instanceof String) { - return ((String) object).split(regex); - } - - throw new IllegalArgumentException("no found " + key); - } - - /** - * Get the values table. - * - * @return the values table. - */ - public @NotNull ObjectDictionary getValues() { - return values; - } - - /** - * Get a vector by the key. - * - * @param key the key. - * @return the vector. - */ - public @NotNull Vector3f getVector(@NotNull String key) { - - Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Vector3f) { - return (Vector3f) object; - } else if (object instanceof String) { - return parseVector((String) object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private @NotNull Vector3f parseVector(@NotNull String object) { - String[] values = object.split(","); - return new Vector3f(parseFloat(values[0]), parseFloat(values[1]), parseFloat(values[2])); - } - - /** - * Get a vector by the key. - * - * @param key the key. - * @param def the default vector. - * @return the vector. - */ - public @NotNull Vector3f getVector(@NotNull final String key, @NotNull final Vector3f def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Vector3f) { - return (Vector3f) object; - } else if (object instanceof String) { - return parseVector((String) object); - } - - return def; - } - - /** - * Put the value by the key to this vars table. - * - * @param key the key. - * @param value the value. - * @since 8.1.0 - */ - public void put(@NotNull String key, @NotNull Object value) { - values.put(key, notNull(value)); - } - - /** - * Clear a value by the key. - * - * @param key the key. - */ - public void clear(@NotNull String key) { - values.remove(key); - } - - /** - * Copy all values from the another vars table. - * - * @param vars the another vars table. - * @return this vars table. - * @throws IllegalArgumentException is the vars table is the same as this vars table. - * @since 8.1.0 - */ - public @NotNull VarTable put(@NotNull VarTable vars) { - - if (vars == this) { - throw new IllegalArgumentException("Can't set itself."); - } - - values.put(vars.getValues()); - return this; - } - - /** - * Return true if a value by the key is presented in this vars table. - * - * @param key the key. - * @return true if a value by the key is presented in this vars table. - */ - public boolean has(@NotNull String key) { - return values.containsKey(key); - } - - @Override - public String toString() { - return "VarTable: " + ("values = " + values); - } + final String[] strings = object + .toString() + .split(regex); + final short[] result = new short[strings.length]; + + for (int i = 0, length = strings.length; i < length; i++) { + result[i] = Short.parseShort(strings[i]); + } + + return result; + } + + /** + * Get a short array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default array. + * @return the short array. + */ + public short[] getShortArray( + final String key, + final String regex, + final short... def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof short[]) { + return (short[]) object; + } else if (object instanceof String) { + return parseShortArray(regex, object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a string by the key. + * + * @param key the key. + * @return the string value. + * @throws IllegalArgumentException if the value isn't exist. + */ + public String getString(String key) { + + var object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof String) { + return object.toString(); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a string by the key. + * + * @param key the key. + * @param def the default string. + * @return the string. + */ + public String getString(final String key, final String def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof String) { + return object.toString(); + } + + return def; + } + + /** + * Get a string by the key. + * + * @param key the key. + * @param def the default string. + * @return the string. + */ + public @Nullable String getNullableString(final String key, @Nullable final String def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof String) { + return object.toString(); + } + + return def; + } + + /** + * Get a string array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @return the string array. + */ + public String[] getStringArray(final String key, final String regex) { + + final Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof String[]) { + return (String[]) object; + } else if (object instanceof String) { + return object + .toString() + .split(regex); + } + + throw new IllegalArgumentException("Not found " + key); + } + + /** + * Get a string array by the key. + * + * @param key the key. + * @param regex the regex to split if a value is string. + * @param def the default array. + * @return the string array. + */ + public String[] getStringArray( + final String key, + final String regex, + final String... def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof String[]) { + return (String[]) object; + } else if (object instanceof String) { + return ((String) object).split(regex); + } + + throw new IllegalArgumentException("no found " + key); + } + + /** + * Get the values table. + * + * @return the values table. + */ + public ObjectDictionary getValues() { + return values; + } + + /** + * Get a vector by the key. + * + * @param key the key. + * @return the vector. + */ + public Vector3f getVector(String key) { + + Object object = values.get(key); + + if (object == null) { + throw new IllegalArgumentException("Not found " + key); + } else if (object instanceof Vector3f) { + return (Vector3f) object; + } else if (object instanceof String) { + return parseVector((String) object); + } + + throw new IllegalArgumentException("Not found " + key); + } + + private Vector3f parseVector(String object) { + String[] values = object.split(","); + return new Vector3f(parseFloat(values[0]), parseFloat(values[1]), parseFloat(values[2])); + } + + /** + * Get a vector by the key. + * + * @param key the key. + * @param def the default vector. + * @return the vector. + */ + public Vector3f getVector(final String key, final Vector3f def) { + + final Object object = values.get(key); + + if (object == null) { + return def; + } else if (object instanceof Vector3f) { + return (Vector3f) object; + } else if (object instanceof String) { + return parseVector((String) object); + } + + return def; + } + + /** + * Put the value by the key to this vars table. + * + * @param key the key. + * @param value the value. + * @since 8.1.0 + */ + public void put(String key, Object value) { + values.put(key, notNull(value)); + } + + /** + * Clear a value by the key. + * + * @param key the key. + */ + public void clear(String key) { + values.remove(key); + } + + /** + * Copy all values from the another vars table. + * + * @param vars the another vars table. + * @return this vars table. + * @throws IllegalArgumentException is the vars table is the same as this vars table. + * @since 8.1.0 + */ + public VarTable put(VarTable vars) { + + if (vars == this) { + throw new IllegalArgumentException("Can't set itself."); + } + + values.put(vars.getValues()); + return this; + } + + /** + * Return true if a value by the key is presented in this vars table. + * + * @param key the key. + * @return true if a value by the key is presented in this vars table. + */ + public boolean has(String key) { + return values.containsKey(key); + } + + @Override + public String toString() { + return "VarTable: " + ("values = " + values); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java index bcd1575b..827c80f2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java @@ -44,1429 +44,1411 @@ */ public interface Array extends Collection, Serializable, Reusable, Cloneable, RandomAccess { - /** - * Create an empty read only array. - * - * @param the result element's type. - * @return the empty array. - */ - static @NotNull ReadOnlyArray empty() { - return unsafeNNCast(ArrayFactory.EMPTY_ARRAY); + /** + * Create an empty read only array. + * + * @param the result element's type. + * @return the empty array. + */ + static @NotNull ReadOnlyArray empty() { + return unsafeNNCast(ArrayFactory.EMPTY_ARRAY); + } + + /** + * Create a new array for the element's type. + * + * @param type the element's type. + * @param the element's type. + * @return the new array. + */ + static @NotNull Array ofType(@NotNull Class type) { + return ArrayFactory.newArray(type); + } + + /** + * Create a new array for the element's type. + * + * @param type the element's type. + * @param capacity the start capacity of this array. + * @param the element's type. + * @return the new array. + */ + static @NotNull Array ofType(@NotNull Class type, int capacity) { + return ArrayFactory.newArray(type, capacity); + } + + /** + * Copy an array to a read only array. + * + * @param another the another array. + * @param the element's type. + * @return the new read only array. + */ + static @NotNull ReadOnlyArray of(@NotNull Array another) { + return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOfRange(another.array(), 0, another.size())); + } + + /** + * Creates a single element read only array. + * + * @param element the element. + * @param the element's type. + * @return the read only array. + */ + static @NotNull ReadOnlyArray of(@NotNull T element) { + + T[] newArray = ArrayUtils.create(element.getClass(), 1); + newArray[0] = element; + + return ArrayFactory.newReadOnlyArray(newArray); + } + + @SafeVarargs + static @NotNull ReadOnlyArray of(@NotNull T... elements) { + return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOf(elements)); + } + + @SafeVarargs + static @NotNull ReadOnlyArray optionals(@NotNull Class type, @NotNull Optional... elements) { + return ArrayFactory.newReadOnlyArray(Arrays + .stream(elements) + .filter(Optional::isPresent) + .map(Optional::get) + .toArray(value -> ArrayUtils.create(type, value))); + } + + static > @NotNull A append(@NotNull A first, @NotNull A second) { + first.addAll(second); + return first; + } + + static @NotNull ReadOnlyArray combine(@NotNull Array first, @NotNull Array second) { + + var componentType = ClassUtils.>unsafeNNCast(first + .array() + .getClass() + .getComponentType()); + + var newArray = ArrayUtils.combine(first.toArray(componentType), second.toArray(componentType)); + + return ArrayFactory.newReadOnlyArray(newArray); + } + + /** + * Create a supplier which creates new arrays. + * + * @param type the element's type. + * @param the element's type. + * @return the supplier. + */ + static @NotNull NotNullSupplier> supplier(@NotNull Class type) { + return () -> ArrayFactory.newConcurrentStampedLockArray(type); + } + + /** + * Create a function which creates new arrays. + * + * @param type the element's type. + * @param the element's type. + * @return the supplier. + */ + static @NotNull NotNullFunction, Array> function(@NotNull Class type) { + return ArrayFactory::newConcurrentStampedLockArray; + } + + /** + * Copy all elements from this array to a target array. + * + * @param target the target array. + */ + default void copyTo(@NotNull Array target) { + target.addAll(this); + } + + /** + * Adds all elements from the array to this array. + * + * @param array the array with new elements. + * @return true if this array was changed. + */ + boolean addAll(@NotNull Array array); + + /** + * Adds all elements from the array to this array. + * + * @param array the array with new elements. + * @return true if this array was changed. + */ + boolean addAll(@NotNull E[] array); + + /** + * Applies this function to each element of this array with replacing to result element from thia function. + * + * @param function the function. + */ + default void apply(@NotNull Function function) { + + E[] array = array(); + + for (int i = 0, length = size(); i < length; i++) { + array[i] = function.apply(array[i]); + } + } + + /** + * Get the wrapped array. + * + * @return the wrapped array. + */ + E @NotNull [] array(); + + @Override + default @NotNull Stream stream() { + return Arrays.stream(array(), 0, size()); + } + + @Override + default @NotNull Stream parallelStream() { + return stream().parallel(); + } + + @Override + default boolean contains(@NotNull Object object) { + + for (E element : array()) { + if (element == null) { + break; + } else if (element.equals(object)) { + return true; + } } - /** - * Create a new array for the element's type. - * - * @param type the element's type. - * @param the element's type. - * @return the new array. - */ - static @NotNull Array ofType(@NotNull Class type) { - return ArrayFactory.newArray(type); - } + return false; + } - /** - * Create a new array for the element's type. - * - * @param type the element's type. - * @param capacity the start capacity of this array. - * @param the element's type. - * @return the new array. - */ - static @NotNull Array ofType(@NotNull Class type, int capacity) { - return ArrayFactory.newArray(type, capacity); - } + /** + * Returns true if this array contains all of the elements in the specified array. + * + * @param array the array to be checked for containment in this array + * @return true if this array contains all of the elements in the specified array. + */ + default boolean containsAll(@NotNull Array array) { - /** - * Copy an array to a read only array. - * - * @param another the another array. - * @param the element's type. - * @return the new read only array. - */ - static @NotNull ReadOnlyArray of(@NotNull Array another) { - return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOfRange(another.array(), 0, another.size())); + if (array.isEmpty()) { + return false; } - /** - * Creates a single element read only array. - * - * @param element the element. - * @param the element's type. - * @return the read only array. - */ - static @NotNull ReadOnlyArray of(@NotNull T element) { - - T[] newArray = ArrayUtils.create(element.getClass(), 1); - newArray[0] = element; - - return ArrayFactory.newReadOnlyArray(newArray); + for (var element : array.array()) { + if (element == null) { + break; + } else if (!contains(element)) { + return false; + } } - @SafeVarargs - static @NotNull ReadOnlyArray of(@NotNull T... elements) { - return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOf(elements)); - } + return true; + } - @SafeVarargs - static @NotNull ReadOnlyArray optionals(@NotNull Class type, @NotNull Optional... elements) { - return ArrayFactory.newReadOnlyArray(Arrays.stream(elements) - .filter(Optional::isPresent) - .map(Optional::get) - .toArray(value -> ArrayUtils.create(type, value))); - } + @Override + default boolean containsAll(@NotNull Collection array) { - static > @NotNull A append(@NotNull A first, @NotNull A second) { - first.addAll(second); - return first; + if (array.isEmpty()) { + return false; } - static @NotNull ReadOnlyArray combine(@NotNull Array first, @NotNull Array second) { - - var componentType = ClassUtils.>unsafeNNCast(first.array() - .getClass() - .getComponentType()); - - var newArray = ArrayUtils.combine(first.toArray(componentType), second.toArray(componentType)); - - return ArrayFactory.newReadOnlyArray(newArray); + for (var element : array) { + if (element == null) { + break; + } else if (!contains(element)) { + return false; + } } - /** - * Create a supplier which creates new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static @NotNull NotNullSupplier> supplier(@NotNull Class type) { - return () -> ArrayFactory.newConcurrentStampedLockArray(type); - } + return true; + } - /** - * Create a function which creates new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static @NotNull NotNullFunction, Array> function(@NotNull Class type) { - return ArrayFactory::newConcurrentStampedLockArray; - } + /** + * Returns true if this array contains all of the elements in the specified array. + * + * @param array the array to be checked for containment in this array + * @return true if this array contains all of the elements in the specified array. + */ + default boolean containsAll(@NotNull Object[] array) { - /** - * Copy all elements from this array to a target array. - * - * @param target the target array. - */ - default void copyTo(@NotNull Array target) { - target.addAll(this); + if (array.length < 1) { + return false; } - /** - * Adds all elements from the array to this array. - * - * @param array the array with new elements. - * @return true if this array was changed. - */ - boolean addAll(@NotNull Array array); - - /** - * Adds all elements from the array to this array. - * - * @param array the array with new elements. - * @return true if this array was changed. - */ - boolean addAll(@NotNull E[] array); - - /** - * Applies this function to each element of this array with replacing to result element from thia function. - * - * @param function the function. - */ - default void apply(@NotNull Function function) { - - E[] array = array(); - - for (int i = 0, length = size(); i < length; i++) { - array[i] = function.apply(array[i]); - } + for (Object element : array) { + if (!contains(element)) { + return false; + } } - /** - * Get the wrapped array. - * - * @return the wrapped array. - */ - E @NotNull [] array(); + return true; + } + + @Override + default void free() { + clear(); + } - @Override - default @NotNull Stream stream() { - return Arrays.stream(array(), 0, size()); - } + /** + * Removes the element at index possible with reordering. + * + * @param index the index of removing the element. + * @return the removed element. + */ + @NotNull E fastRemove(int index); - @Override - default @NotNull Stream parallelStream() { - return stream().parallel(); - } + /** + * Removes an element without saving original ordering of other elements. + * + * @param object the element to remove. + * @return true if the element was removed. + */ + default boolean fastRemove(@NotNull Object object) { - @Override - default boolean contains(@NotNull Object object) { - - for (E element : array()) { - if (element == null) { - break; - } else if (element.equals(object)) { - return true; - } - } + int index = indexOf(object); - return false; + if (index >= 0) { + fastRemove(index); } - /** - * Returns true if this array contains all of the elements in the specified array. - * - * @param array the array to be checked for containment in this array - * @return true if this array contains all of the elements in the specified array. - */ - default boolean containsAll(@NotNull Array array) { + return index >= 0; + } - if (array.isEmpty()) { - return false; - } + /** + * Removes the each element from the array. + * + * @param array the array with elements to remove. + * @return count of removed elements. + */ + default int fastRemoveAll(@NotNull E[] array) { - for (var element : array.array()) { - if (element == null) { - break; - } else if (!contains(element)) { - return false; - } - } + int count = 0; - return true; + for (var object : array) { + if (fastRemove(object)) { + count++; + } } - @Override - default boolean containsAll(@NotNull Collection array) { - - if (array.isEmpty()) { - return false; - } - - for (var element : array) { - if (element == null) { - break; - } else if (!contains(element)) { - return false; - } - } - - return true; - } + return count; + } - /** - * Returns true if this array contains all of the elements in the specified array. - * - * @param array the array to be checked for containment in this array - * @return true if this array contains all of the elements in the specified array. - */ - default boolean containsAll(@NotNull Object[] array) { + /** + * Try to get the first element of this array. + * + * @return the first element or null. + */ + default @Nullable E first() { + return isEmpty() ? null : get(0); + } + + /** + * Get an element by an index. + * + * @param index the index of the element. + * @return the element. + */ + @NotNull E get(int index); - if (array.length < 1) { - return false; - } + /** + * Find an index of the object in this array. + * + * @param object the object to find. + * @return the index of the object or -1. + */ + default int indexOf(@NotNull Object object) { - for (Object element : array) { - if (!contains(element)) { - return false; - } - } + int index = 0; - return true; - } + for (E element : array()) { - @Override - default void free() { - clear(); - } + if (element == null) { + break; + } else if (Objects.equals(object, element)) { + return index; + } - /** - * Removes the element at index possible with reordering. - * - * @param index the index of removing the element. - * @return the removed element. - */ - @NotNull E fastRemove(int index); - - /** - * Removes an element without saving original ordering of other elements. - * - * @param object the element to remove. - * @return true if the element was removed. - */ - default boolean fastRemove(@NotNull Object object) { - - int index = indexOf(object); - - if (index >= 0) { - fastRemove(index); - } + index++; + } - return index >= 0; - } + return -1; + } - /** - * Removes the each element from the array. - * - * @param array the array with elements to remove. - * @return count of removed elements. - */ - default int fastRemoveAll(@NotNull E[] array) { + @Override + default @NotNull ArrayIterator iterator() { + return new DefaultArrayIterator<>(this); + } - int count = 0; + /** + * Try to get the last element. + * + * @return the last element or null. + */ + default @Nullable E last() { - for (var object : array) { - if (fastRemove(object)) { - count++; - } - } + int size = size(); - return count; + if (size < 1) { + return null; } - /** - * Try to get the first element of this array. - * - * @return the first element or null. - */ - default @Nullable E first() { - return isEmpty() ? null : get(0); - } + return get(size - 1); + } - /** - * Get an element by an index. - * - * @param index the index of the element. - * @return the element. - */ - @NotNull E get(int index); - - /** - * Find an index of the object in this array. - * - * @param object the object to find. - * @return the index of the object or -1. - */ - default int indexOf(@NotNull Object object) { - - int index = 0; - - for (E element : array()) { - - if (element == null) { - break; - } else if (Objects.equals(object, element)) { - return index; - } - - index++; - } + /** + * Find the last index of the object in this array. + * + * @param object the object. + * @return the last index or -1. + */ + default int lastIndexOf(@NotNull Object object) { - return -1; - } + E[] array = array(); - @Override - default @NotNull ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } + int last = -1; - /** - * Try to get the last element. - * - * @return the last element or null. - */ - default @Nullable E last() { + for (int i = 0, length = size(); i < length; i++) { - int size = size(); - - if (size < 1) { - return null; - } + E element = array[i]; - return get(size - 1); + if (element.equals(object)) { + last = i; + } } - /** - * Find the last index of the object in this array. - * - * @param object the object. - * @return the last index or -1. - */ - default int lastIndexOf(@NotNull Object object) { + return last; + } - E[] array = array(); + /** + * Get and remove the first element from this array. + * + * @return the first element or null. + */ + default @Nullable E poll() { + return isEmpty() ? null : remove(0); + } - int last = -1; + /** + * Get and remove the last element of this array. + * + * @return the last element or null. + */ + default @Nullable E pop() { + return isEmpty() ? null : fastRemove(size() - 1); + } - for (int i = 0, length = size(); i < length; i++) { + /** + * Removes all of this target's elements that are also contained in the specified array (optional operation). + * + * @param target array containing elements to be removed from this array. + * @return true if this array changed as a result of the call. + */ + default boolean removeAll(@NotNull Array target) { - E element = array[i]; - - if (element.equals(object)) { - last = i; - } - } - - return last; + if (target.isEmpty()) { + return false; } - /** - * Get and remove the first element from this array. - * - * @return the first element or null. - */ - default @Nullable E poll() { - return isEmpty() ? null : remove(0); - } + int count = 0; - /** - * Get and remove the last element of this array. - * - * @return the last element or null. - */ - default @Nullable E pop() { - return isEmpty() ? null : fastRemove(size() - 1); + for (var element : target.array()) { + if (element == null) { + break; + } else if (remove(element)) { + count++; + } } - /** - * Removes all of this target's elements that are also contained in the specified array (optional operation). - * - * @param target array containing elements to be removed from this array. - * @return true if this array changed as a result of the call. - */ - default boolean removeAll(@NotNull Array target) { - - if (target.isEmpty()) { - return false; - } - - int count = 0; + return count > 0; + } - for (var element : target.array()) { - if (element == null) { - break; - } else if (remove(element)) { - count++; - } - } + /** + * Removes all of this target's elements that are also contained in the specified array (optional operation) with + * reordering. + * + * @param target array containing elements to be removed from this array. + * @return true if this array changed as a result of the call. + */ + default boolean fastRemoveAll(@NotNull Array target) { - return count > 0; + if (target.isEmpty()) { + return false; } - /** - * Removes all of this target's elements that are also contained in the specified array (optional operation) - * with reordering. - * - * @param target array containing elements to be removed from this array. - * @return true if this array changed as a result of the call. - */ - default boolean fastRemoveAll(@NotNull Array target) { - - if (target.isEmpty()) { - return false; - } - - var count = 0; - var array = array(); + var count = 0; + var array = array(); - for (int i = 0, length = size(); i < length; i++) { + for (int i = 0, length = size(); i < length; i++) { - var element = array[i]; + var element = array[i]; - if (!target.contains(element)) { - continue; - } + if (!target.contains(element)) { + continue; + } - fastRemove(i); - i--; - length--; - count++; - } - - return count > 0; + fastRemove(i); + i--; + length--; + count++; } - @Override - default boolean removeAll(@NotNull Collection target) { + return count > 0; + } - if (target.isEmpty()) { - return false; - } + @Override + default boolean removeAll(@NotNull Collection target) { - int count = 0; - - for (var element : target) { - if (remove(element)) { - count++; - } - } - - return count == target.size(); + if (target.isEmpty()) { + return false; } - /** - * Retains only the elements in this array that are contained in the specified array (optional operation). In other - * words, removes from this array all of its elements that are not contained in the specified array. - * - * @param target array containing elements to be retained in this array. - * @return true if this array changed as a result of the call. - */ - default boolean retainAll(@NotNull Array target) { - - E[] array = array(); - - for (int i = 0, length = size(); i < length; i++) { - if (!target.contains(array[i])) { - fastRemove(i--); - length--; - } - } + int count = 0; - return true; + for (var element : target) { + if (remove(element)) { + count++; + } } - @Override - default boolean retainAll(@NotNull Collection target) { + return count == target.size(); + } - E[] array = array(); + /** + * Retains only the elements in this array that are contained in the specified array (optional operation). In other + * words, removes from this array all of its elements that are not contained in the specified array. + * + * @param target array containing elements to be retained in this array. + * @return true if this array changed as a result of the call. + */ + default boolean retainAll(@NotNull Array target) { - for (int i = 0, length = size(); i < length; i++) { - if (!target.contains(array[i])) { - fastRemove(i--); - length--; - } - } + E[] array = array(); - return true; + for (int i = 0, length = size(); i < length; i++) { + if (!target.contains(array[i])) { + fastRemove(i--); + length--; + } } - /** - * Replace an element by an index. - * - * @param index the element's index. - * @param element the new element. - */ - void replace(int index, @NotNull E element); - - /** - * Removes the element at index. - * - * @param index the index of removing the element. - * @return the removed element. - */ - @NotNull E remove(int index); - - @Override - default boolean remove(@NotNull Object object) { - - var index = indexOf(object); - - if (index >= 0) { - remove(index); - } + return true; + } - return index >= 0; - } + @Override + default boolean retainAll(@NotNull Collection target) { - /** - * Sort this array using the comparator. - * - * @param comparator the comparator. - * @return the array - */ - default @NotNull Array sort(@NotNull ArrayComparator comparator) { - ArrayUtils.sort(array(), 0, size(), comparator); - return this; - } + E[] array = array(); - @Override - default @NotNull T[] toArray(@NotNull T[] newArray) { + for (int i = 0, length = size(); i < length; i++) { + if (!target.contains(array[i])) { + fastRemove(i--); + length--; + } + } - E[] array = array(); + return true; + } - if (newArray.length >= size()) { + /** + * Replace an element by an index. + * + * @param index the element's index. + * @param element the new element. + */ + void replace(int index, @NotNull E element); - for (int i = 0, j = 0, length = array.length, newLength = newArray.length; - i < length && j < newLength; i++) { - if (array[i] == null) continue; - newArray[j++] = unsafeCast(array[i]); - } + /** + * Removes the element at index. + * + * @param index the index of removing the element. + * @return the removed element. + */ + @NotNull E remove(int index); - return newArray; - } + @Override + default boolean remove(@NotNull Object object) { - Class arrayClass = unsafeCast(newArray.getClass()); - Class componentType = unsafeCast(arrayClass.getComponentType()); + var index = indexOf(object); - return toArray(componentType); + if (index >= 0) { + remove(index); } - /** - * Copy this array to the new array. - * - * @param the type parameter - * @param componentType the type of the new array. - * @return the copied array. - */ - default @NotNull T[] toArray(@NotNull Class componentType) { + return index >= 0; + } - T[] newArray = ArrayUtils.create(componentType, size()); - E[] array = array(); + /** + * Sort this array using the comparator. + * + * @param comparator the comparator. + * @return the array + */ + default @NotNull Array sort(@NotNull ArrayComparator comparator) { + ArrayUtils.sort(array(), 0, size(), comparator); + return this; + } - System.arraycopy(array, 0, newArray, 0, size()); + @Override + default @NotNull T[] toArray(@NotNull T[] newArray) { - return newArray; - } + E[] array = array(); + + if (newArray.length >= size()) { - /** - * Get the unsafe interface of this array. - * - * @return the unsafe interface of this array. - */ - default @NotNull UnsafeArray asUnsafe() { - if (this instanceof UnsafeArray) { - return (UnsafeArray) this; - } else { - throw new UnsupportedOperationException(); + for (int i = 0, j = 0, length = array.length, newLength = newArray.length; i < length && j < newLength; i++) { + if (array[i] == null) { + continue; } - } + newArray[j++] = unsafeCast(array[i]); + } - @Override - default boolean isEmpty() { - return size() < 1; + return newArray; } - @Override - default @NotNull E[] toArray() { - var array = array(); - return Arrays.copyOf(array, size(), (Class) array.getClass()); - } + Class arrayClass = unsafeCast(newArray.getClass()); + Class componentType = unsafeCast(arrayClass.getComponentType()); - @NotNull String toString(@NotNull Function toString); + return toArray(componentType); + } - @Override - default boolean removeIf(@NotNull Predicate<@NotNull ? super E> filter) { + /** + * Copy this array to the new array. + * + * @param the type parameter + * @param componentType the type of the new array. + * @return the copied array. + */ + default @NotNull T[] toArray(@NotNull Class componentType) { + + T[] newArray = ArrayUtils.create(componentType, size()); + E[] array = array(); - var array = array(); - var removed = 0; + System.arraycopy(array, 0, newArray, 0, size()); - for (int i = 0, length = size(); i < length; i++) { + return newArray; + } - var element = array[i]; + /** + * Get the unsafe interface of this array. + * + * @return the unsafe interface of this array. + */ + default @NotNull UnsafeArray asUnsafe() { + if (this instanceof UnsafeArray) { + return (UnsafeArray) this; + } else { + throw new UnsupportedOperationException(); + } + } - if (filter.test(element)) { - remove(i); - i--; - length--; - removed++; - } - } + @Override + default boolean isEmpty() { + return size() < 1; + } + + @Override + default @NotNull E[] toArray() { + var array = array(); + return Arrays.copyOf(array, size(), (Class) array.getClass()); + } + + @NotNull String toString(@NotNull Function toString); + + @Override + default boolean removeIf(@NotNull Predicate<@NotNull ? super E> filter) { + + var array = array(); + var removed = 0; + + for (int i = 0, length = size(); i < length; i++) { + + var element = array[i]; + + if (filter.test(element)) { + remove(i); + i--; + length--; + removed++; + } + } + + return removed > 0; + } + + /** + * Removes all of the elements of this collection that satisfy the given predicate. + * + * @param argument the additional argument. + * @param filter the predicate which returns {@code true} for elements to be removed. + * @param the argument's type. + * @return {@code true} if any elements were removed. + */ + default boolean removeIf(@NotNull A argument, @NotNull NotNullBiPredicate filter) { + + var array = array(); + var removed = 0; + + for (int i = 0, length = size(); i < length; i++) { + + var element = array[i]; + + if (filter.test(argument, element)) { + remove(i); + i--; + length--; + removed++; + } + } + + return removed > 0; + } + + /** + * Removes all of the elements of this collection that satisfy the given predicate. + * + * @param argument the additional argument. + * @param converter the converter of the argument. + * @param filter the predicate which returns {@code true} for elements to be removed. + * @param the argument's type. + * @param the argument converted type. + * @return {@code true} if any elements were removed. + */ + default boolean removeIf( + @NotNull A argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { + + var array = array(); + var removed = 0; + + for (int i = 0, length = size(); i < length; i++) { + + var element = array[i]; + + if (filter.test(converter.apply(argument), element)) { + remove(i); + i--; + length--; + removed++; + } + } + + return removed > 0; + } + + /** + * Removes all of the elements of this collection that satisfy the given predicate. + * + * @param argument the additional argument. + * @param converter the converter of the elements. + * @param filter the predicate which returns {@code true} for elements to be removed. + * @param the argument's type. + * @param the element converted type. + * @return {@code true} if any elements were removed. + * @since 9.6.0 + */ + default boolean removeIfConverted( + @NotNull A argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { + + var array = array(); + var removed = 0; + + for (int i = 0, length = size(); i < length; i++) { + + var element = array[i]; + + if (filter.test(argument, converter.apply(element))) { + remove(i); + i--; + length--; + removed++; + } + } + + return removed > 0; + } + + /** + * Return true if there is at least an element for the condition. + * + * @param argument the argument. + * @param filter the condition. + * @param the argument's type. + * @return true if there is at least an element for the condition. + */ + default boolean anyMatch(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + return findAny(argument, filter) != null; + } + + /** + * Return true if there is at least a converted element for the condition. + * + * @param argument the argument. + * @param converter the converter element to another type. + * @param filter the condition. + * @param the argument's type. + * @param the converted element's type. + * @return true if there is at least an element for the condition. + * @since 9.7.0 + */ + default boolean anyMatchConverted( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { + return findAnyConverted(argument, converter, filter) != null; + } + + /** + * Return true if there is at least an element for the condition. + * + * @param argument the argument. + * @param filter the condition. + * @return true if there is at least an element for the condition. + */ + default boolean anyMatch(int argument, @NotNull NotNullIntObjectPredicate filter) { + return findAny(argument, filter) != null; + } + + /** + * Return true if there is at least an element for the condition. + * + * @param the argument's type. + * @param argument the argument. + * @param filter the condition. + * @return true if there is at least an element for the condition. + */ + default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + return findAnyR(argument, filter) != null; + } + + /** + * Find an element using the condition. + * + * @param filter the condition. + * @return the found element or null. + */ + default @Nullable E findAny(@NotNull NotNullPredicate filter) { + + if (isEmpty()) { + return null; + } + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + + var element = array[i]; + + if (filter.test(element)) { + return element; + } + } + + return null; + } + + /** + * Search an element using the condition. + * + * @param argument the argument. + * @param filter the condition. + * @param the argument's type. + * @return the found element or null. + */ + default @Nullable E findAny(@NotNull T argument, @NotNull NotNullBiPredicate filter) { - return removed > 0; + if (isEmpty()) { + return null; } - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIf(@NotNull A argument, @NotNull NotNullBiPredicate filter) { - - var array = array(); - var removed = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, element)) { - remove(i); - i--; - length--; - removed++; - } - } + var array = array(); - return removed > 0; - } + for (int i = 0, length = size(); i < length; i++) { - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param converter the converter of the argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the argument converted type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIf( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - - var array = array(); - var removed = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(converter.apply(argument), element)) { - remove(i); - i--; - length--; - removed++; - } - } + var element = array[i]; - return removed > 0; - } + if (filter.test(argument, element)) { + return element; + } + } + + return null; + } - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param converter the converter of the elements. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the element converted type. - * @return {@code true} if any elements were removed. - * @since 9.6.0 - */ - default boolean removeIfConverted( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - - var array = array(); - var removed = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, converter.apply(element))) { - remove(i); - i--; - length--; - removed++; - } - } + /** + * Search an element using the condition by converted value. + * + * @param argument the argument. + * @param converter the converted an element to another type. + * @param filter the condition. + * @param the argument's type. + * @param the converted element's type. + * @return the found element or null. + * @since 9.7.0 + */ + default @Nullable E findAnyConverted( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { - return removed > 0; + if (isEmpty()) { + return null; } - /** - * Return true if there is at least an element for the condition. - * - * @param argument the argument. - * @param filter the condition. - * @param the argument's type. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatch(@NotNull T argument, @NotNull NotNullBiPredicate filter) { - return findAny(argument, filter) != null; - } + var array = array(); - /** - * Return true if there is at least a converted element for the condition. - * - * @param argument the argument. - * @param converter the converter element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return true if there is at least an element for the condition. - * @since 9.7.0 - */ - default boolean anyMatchConverted( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - return findAnyConverted(argument, converter, filter) != null; - } + for (int i = 0, length = size(); i < length; i++) { - /** - * Return true if there is at least an element for the condition. - * - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatch(int argument, @NotNull NotNullIntObjectPredicate filter) { - return findAny(argument, filter) != null; - } + var element = array[i]; - /** - * Return true if there is at least an element for the condition. - * - * @param the argument's type. - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { - return findAnyR(argument, filter) != null; + if (filter.test(argument, converter.apply(element))) { + return element; + } } - /** - * Find an element using the condition. - * - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAny(@NotNull NotNullPredicate filter) { + return null; + } - if (isEmpty()) { - return null; - } + /** + * Find an element for the condition. + * + * @param the argument's type. + * @param argument the argument. + * @param filter the condition. + * @return the found element or null. + */ + default @Nullable E findAnyR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { - var array = array(); + if (isEmpty()) { + return null; + } - for (int i = 0, length = size(); i < length; i++) { + var array = array(); - var element = array[i]; + for (int i = 0, length = size(); i < length; i++) { - if (filter.test(element)) { - return element; - } - } + var element = array[i]; - return null; + if (filter.test(element, argument)) { + return element; + } } - /** - * Search an element using the condition. - * - * @param argument the argument. - * @param filter the condition. - * @param the argument's type. - * @return the found element or null. - */ - default @Nullable E findAny(@NotNull T argument, @NotNull NotNullBiPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); + return null; + } - for (int i = 0, length = size(); i < length; i++) { + /** + * Search an element using the condition. + * + * @param argument the argument. + * @param filter the condition. + * @return the found element or null. + */ + default @Nullable E findAny(int argument, @NotNull NotNullIntObjectPredicate filter) { - var element = array[i]; - - if (filter.test(argument, element)) { - return element; - } - } - - return null; + if (isEmpty()) { + return null; } - /** - * Search an element using the condition by converted value. - * - * @param argument the argument. - * @param converter the converted an element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConverted( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - - if (isEmpty()) { - return null; - } - - var array = array(); + var array = array(); - for (int i = 0, length = size(); i < length; i++) { + for (int i = 0, length = size(); i < length; i++) { - var element = array[i]; + var element = array[i]; - if (filter.test(argument, converter.apply(element))) { - return element; - } - } - - return null; + if (filter.test(argument, element)) { + return element; + } } - /** - * Find an element for the condition. - * - * @param the argument's type. - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAnyR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { + return null; + } - var element = array[i]; + /** + * Search an element using the condition. + * + * @param argument the argument. + * @param filter the condition. + * @return the found element or null. + */ + default @Nullable E findAnyL(long argument, @NotNull NotNullLongObjectPredicate filter) { - if (filter.test(element, argument)) { - return element; - } - } - - return null; + if (isEmpty()) { + return null; } - /** - * Search an element using the condition. - * - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAny(int argument, @NotNull NotNullIntObjectPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { + var array = array(); - var element = array[i]; + for (int i = 0, length = size(); i < length; i++) { - if (filter.test(argument, element)) { - return element; - } - } + var element = array[i]; - return null; + if (filter.test(argument, element)) { + return element; + } } + return null; + } - /** - * Search an element using the condition. - * - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAnyL(long argument, @NotNull NotNullLongObjectPredicate filter) { - - if (isEmpty()) { - return null; - } + /** + * Search an element using the condition. + * + * @param first the first argument. + * @param second the second argument. + * @param filter the condition. + * @param the first argument's type. + * @param the second argument's type. + * @return the found element or null. + */ + default @Nullable E findAny( + @NotNull F first, + @NotNull S second, + @NotNull NotNullTriplePredicate filter) { - var array = array(); + if (isEmpty()) { + return null; + } - for (int i = 0, length = size(); i < length; i++) { + var array = array(); - var element = array[i]; + for (int i = 0, length = size(); i < length; i++) { - if (filter.test(argument, element)) { - return element; - } - } + var element = array[i]; - return null; + if (filter.test(first, second, element)) { + return element; + } } - /** - * Search an element using the condition. - * - * @param first the first argument. - * @param second the second argument. - * @param filter the condition. - * @param the first argument's type. - * @param the second argument's type. - * @return the found element or null. - */ - default @Nullable E findAny( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTriplePredicate filter - ) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { + return null; + } - var element = array[i]; - - if (filter.test(first, second, element)) { - return element; - } - } + /** + * Search a converted element to int using the condition. + * + * @param argument the argument. + * @param converter the converter element to int. + * @param filter the condition. + * @return the found element or null. + * @since 9.6.0 + */ + default @Nullable E findAnyConvertedToInt( + int argument, + @NotNull NotNullFunctionInt converter, + @NotNull BiIntPredicate filter) { - return null; + if (isEmpty()) { + return null; } - /** - * Search a converted element to int using the condition. - * - * @param argument the argument. - * @param converter the converter element to int. - * @param filter the condition. - * @return the found element or null. - * @since 9.6.0 - */ - default @Nullable E findAnyConvertedToInt( - int argument, - @NotNull NotNullFunctionInt converter, - @NotNull BiIntPredicate filter - ) { - - if (isEmpty()) { - return null; - } - - var array = array(); + var array = array(); - for (int i = 0, length = size(); i < length; i++) { + for (int i = 0, length = size(); i < length; i++) { - var element = array[i]; - - if (filter.test(argument, converter.apply(element))) { - return element; - } - } + var element = array[i]; - return null; + if (filter.test(argument, converter.apply(element))) { + return element; + } } - /** - * Search a converted element to int using the condition. - * - * @param argument the argument. - * @param firstConverter the converter element to T. - * @param secondConverter the converter element to int. - * @param filter the condition. - * @param the first converted type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConvertedToInt( - int argument, - @NotNull NotNullFunction firstConverter, - @NotNull NotNullFunctionInt secondConverter, - @NotNull BiIntPredicate filter - ) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { + return null; + } - var element = array[i]; - - if (filter.test(argument, secondConverter.apply(firstConverter.apply(element)))) { - return element; - } - } + /** + * Search a converted element to int using the condition. + * + * @param argument the argument. + * @param firstConverter the converter element to T. + * @param secondConverter the converter element to int. + * @param filter the condition. + * @param the first converted type. + * @return the found element or null. + * @since 9.7.0 + */ + default @Nullable E findAnyConvertedToInt( + int argument, + @NotNull NotNullFunction firstConverter, + @NotNull NotNullFunctionInt secondConverter, + @NotNull BiIntPredicate filter) { - return null; + if (isEmpty()) { + return null; } - /** - * Calculate a count of matched elements. - * - * @param filter the condition. - * @return the count of matched elements. - * @since 9.5.0 - */ - default int count(@NotNull NotNullPredicate filter) { + var array = array(); - var array = array(); - var count = 0; + for (int i = 0, length = size(); i < length; i++) { - for (int i = 0, length = size(); i < length; i++) { + var element = array[i]; - var element = array[i]; - - if (filter.test(element)) { - count++; - } - } - - return count; + if (filter.test(argument, secondConverter.apply(firstConverter.apply(element)))) { + return element; + } } - /** - * Calculate a count of matched elements. - * - * @param arg the argument. - * @param filter the condition. - * @param the argument's type. - * @return the count of matched elements. - */ - default int count(@NotNull F arg, @NotNull NotNullBiPredicate filter) { + return null; + } - var array = array(); - var count = 0; + /** + * Calculate a count of matched elements. + * + * @param filter the condition. + * @return the count of matched elements. + * @since 9.5.0 + */ + default int count(@NotNull NotNullPredicate filter) { - for (int i = 0, length = size(); i < length; i++) { + var array = array(); + var count = 0; - var element = array[i]; + for (int i = 0, length = size(); i < length; i++) { - if (filter.test(arg, element)) { - count++; - } - } + var element = array[i]; - return count; + if (filter.test(element)) { + count++; + } } - /** - * Calculate a count of matched elements with reversed ordering of arguments. - * - * @param the argument's type. - * @param arg the argument. - * @param filter the condition. - * @return the count of matched elements. - */ - default int countR(@NotNull F arg, @NotNull NotNullBiPredicate filter) { + return count; + } - var array = array(); - var count = 0; + /** + * Calculate a count of matched elements. + * + * @param arg the argument. + * @param filter the condition. + * @param the argument's type. + * @return the count of matched elements. + */ + default int count(@NotNull F arg, @NotNull NotNullBiPredicate filter) { - for (int i = 0, length = size(); i < length; i++) { + var array = array(); + var count = 0; - var element = array[i]; + for (int i = 0, length = size(); i < length; i++) { - if (filter.test(element, arg)) { - count++; - } - } + var element = array[i]; - return count; + if (filter.test(arg, element)) { + count++; + } } - @Override - default void forEach(@NotNull Consumer consumer) { + return count; + } - var array = array(); + /** + * Calculate a count of matched elements with reversed ordering of arguments. + * + * @param the argument's type. + * @param arg the argument. + * @param filter the condition. + * @return the count of matched elements. + */ + default int countR(@NotNull F arg, @NotNull NotNullBiPredicate filter) { - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i]); - } - } - - /** - * Apply a function to each filtered element. - * - * @param filter the condition. - * @param consumer the function. - */ - default void forEachFiltered(@NotNull NotNullPredicate filter, @NotNull NotNullConsumer consumer) { + var array = array(); + var count = 0; - var array = array(); + for (int i = 0, length = size(); i < length; i++) { - for (int i = 0, length = size(); i < length; i++) { + var element = array[i]; - E element = array[i]; - - if (filter.test(element)) { - consumer.accept(element); - } - } + if (filter.test(element, arg)) { + count++; + } } - /** - * Apply a function to each element. - * - * @param argument the argument. - * @param consumer the function. - * @param the type of an argument. - */ - default void forEach(@NotNull T argument, @NotNull NotNullBiConsumer consumer) { + return count; + } - var array = array(); + @Override + default void forEach(@NotNull Consumer consumer) { - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(argument, array[i]); - } - } - - /** - * Apply a function to each element. - * - * @param argument the argument. - * @param consumer the function. - * @param the argument's type. - */ - default void forEachR(@NotNull T argument, @NotNull NotNullBiConsumer consumer) { + var array = array(); - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i], argument); - } + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(array[i]); } + } - /** - * Apply a function to each converted element. - * - * @param argument the argument. - * @param converter the converter from E to C. - * @param consumer the function. - * @param the argument's type. - * @param the converted type. - */ - default void forEachConverted( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(argument, converter.apply(array[i])); - } - } + /** + * Apply a function to each filtered element. + * + * @param filter the condition. + * @param consumer the function. + */ + default void forEachFiltered(@NotNull NotNullPredicate filter, @NotNull NotNullConsumer consumer) { - /** - * Apply a function to each converted element. - * - * @param first the first argument. - * @param second the second argument. - * @param converter the converter from E to C. - * @param consumer the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the converted type. - */ - default void forEachConverted( - @NotNull F first, - @NotNull S second, - @NotNull NotNullFunction converter, - @NotNull NotNullTripleConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, converter.apply(array[i])); - } - } + var array = array(); - /** - * Apply a function to each element and converted argument. - * - * @param argument the argument. - * @param converter the converter from T to C. - * @param consumer the function. - * @param the argument's type. - * @param the converted type. - * @since 9.8.0 - */ - default void forEach( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(converter.apply(argument), array[i]); - } - } + for (int i = 0, length = size(); i < length; i++) { - /** - * Apply a function to each filtered element. - * - * @param the type of an argument. - * @param argument the argument. - * @param filter the condition. - * @param consumer the function. - */ - default void forEachFiltered( - @NotNull T argument, - @NotNull NotNullBiPredicate filter, - @NotNull NotNullBiConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - E element = array[i]; - - if (filter.test(argument, element)) { - consumer.accept(argument, element); - } - } - } + E element = array[i]; - /** - * Apply a function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the firs argument's type. - * @param the second argument's type. - */ - default void forEach( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } + if (filter.test(element)) { + consumer.accept(element); + } } + } - /** - * Apply a function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the second argument's type. - */ - default void forEach( - int first, - @NotNull A second, - @NotNull NotNullIntBiObjectConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } - } + /** + * Apply a function to each element. + * + * @param argument the argument. + * @param consumer the function. + * @param the type of an argument. + */ + default void forEach(@NotNull T argument, @NotNull NotNullBiConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(argument, array[i]); + } + } - /** - * Apply the function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the first argument type. - * @param the second argument type. - */ - default void forEachR( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i], first, second); - } - } + /** + * Apply a function to each element. + * + * @param argument the argument. + * @param consumer the function. + * @param the argument's type. + */ + default void forEachR(@NotNull T argument, @NotNull NotNullBiConsumer consumer) { - /** - * Apply a function to each filtered element. - * - * @param first the first argument. - * @param second the second argument. - * @param filter the condition. - * @param consumer the function. - * @param the firs argument's type. - * @param the second argument's type. - */ - default void forEachFiltered( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTriplePredicate filter, - @NotNull NotNullTripleConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - E element = array[i]; - - if (filter.test(first, second, element)) { - consumer.accept(first, second, element); - } - } - } + var array = array(); - /** - * Apply a function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the second argument's type. - */ - default void forEachL( - long first, - @NotNull F second, - @NotNull NotNullLongBiObjectConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } - } - - /** - * Apply a function to each element. - * - * @param the type parameter - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - */ - default void forEachF( - float first, - @NotNull F second, - @NotNull NotNullFloatBiObjectConsumer consumer - ) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(array[i], argument); } + } + + /** + * Apply a function to each converted element. + * + * @param argument the argument. + * @param converter the converter from E to C. + * @param consumer the function. + * @param the argument's type. + * @param the converted type. + */ + default void forEachConverted( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(argument, converter.apply(array[i])); + } + } + + /** + * Apply a function to each converted element. + * + * @param first the first argument. + * @param second the second argument. + * @param converter the converter from E to C. + * @param consumer the function. + * @param the first argument's type. + * @param the second argument's type. + * @param the converted type. + */ + default void forEachConverted( + @NotNull F first, + @NotNull S second, + @NotNull NotNullFunction converter, + @NotNull NotNullTripleConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(first, second, converter.apply(array[i])); + } + } + + /** + * Apply a function to each element and converted argument. + * + * @param argument the argument. + * @param converter the converter from T to C. + * @param consumer the function. + * @param the argument's type. + * @param the converted type. + * @since 9.8.0 + */ + default void forEach( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(converter.apply(argument), array[i]); + } + } + + /** + * Apply a function to each filtered element. + * + * @param the type of an argument. + * @param argument the argument. + * @param filter the condition. + * @param consumer the function. + */ + default void forEachFiltered( + @NotNull T argument, + @NotNull NotNullBiPredicate filter, + @NotNull NotNullBiConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + + E element = array[i]; + + if (filter.test(argument, element)) { + consumer.accept(argument, element); + } + } + } + + /** + * Apply a function to each element. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the firs argument's type. + * @param the second argument's type. + */ + default void forEach( + @NotNull F first, + @NotNull S second, + @NotNull NotNullTripleConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(first, second, array[i]); + } + } + + /** + * Apply a function to each element. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the second argument's type. + */ + default void forEach(int first, @NotNull A second, @NotNull NotNullIntBiObjectConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(first, second, array[i]); + } + } + + /** + * Apply the function to each element. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the first argument type. + * @param the second argument type. + */ + default void forEachR( + @NotNull F first, + @NotNull S second, + @NotNull NotNullTripleConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(array[i], first, second); + } + } + + /** + * Apply a function to each filtered element. + * + * @param first the first argument. + * @param second the second argument. + * @param filter the condition. + * @param consumer the function. + * @param the firs argument's type. + * @param the second argument's type. + */ + default void forEachFiltered( + @NotNull F first, + @NotNull S second, + @NotNull NotNullTriplePredicate filter, + @NotNull NotNullTripleConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + + E element = array[i]; + + if (filter.test(first, second, element)) { + consumer.accept(first, second, element); + } + } + } + + /** + * Apply a function to each element. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the second argument's type. + */ + default void forEachL( + long first, + @NotNull F second, + @NotNull NotNullLongBiObjectConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(first, second, array[i]); + } + } + + /** + * Apply a function to each element. + * + * @param the type parameter + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + */ + default void forEachF( + float first, + @NotNull F second, + @NotNull NotNullFloatBiObjectConsumer consumer) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(first, second, array[i]); + } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java index b7013ea4..57c15b0e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java @@ -19,130 +19,125 @@ */ public class ArrayCollectors { - private static @NotNull Set CH_ID = unmodifiableSet( - EnumSet.of(Collector.Characteristics.IDENTITY_FINISH) - ); - - private static @NotNull Set CH_ID_CONC = unmodifiableSet(EnumSet.of( - Collector.Characteristics.IDENTITY_FINISH, - Collector.Characteristics.CONCURRENT - )); - - /** - * Get a collector to collect elements into an array. - * - * @param type the type of elements. - * @param arrayFactory the array factory. - * @param the array element's type. - * @param the array's type. - * @return the collector. - */ - public static > @NotNull Collector collector( - @NotNull Class type, - @NotNull Function, A> arrayFactory - ) { - return new Collector<>() { - - private final @NotNull Supplier supplier = () -> arrayFactory.apply(type); - - @Override - public Supplier supplier() { - return supplier; - } - - @Override - public BiConsumer accumulator() { - return Collection::add; - } - - @Override - public BinaryOperator combiner() { - return (source, toAdd) -> { - source.addAll(toAdd); - return source; - }; - } - - @Override - public Function finisher() { - return array -> array; - } - - @Override - public Set characteristics() { - return CH_ID; - } + private static @NotNull Set CH_ID = + unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); + + private static @NotNull Set CH_ID_CONC = unmodifiableSet(EnumSet.of( + Collector.Characteristics.IDENTITY_FINISH, + Collector.Characteristics.CONCURRENT)); + + /** + * Get a collector to collect elements into an array. + * + * @param type the type of elements. + * @param arrayFactory the array factory. + * @param the array element's type. + * @param the array's type. + * @return the collector. + */ + public static > @NotNull Collector collector( + @NotNull Class type, + @NotNull Function, A> arrayFactory) { + return new Collector<>() { + + private final @NotNull Supplier supplier = () -> arrayFactory.apply(type); + + @Override + public Supplier supplier() { + return supplier; + } + + @Override + public BiConsumer accumulator() { + return Collection::add; + } + + @Override + public BinaryOperator combiner() { + return (source, toAdd) -> { + source.addAll(toAdd); + return source; }; - } - - /** - * Get a collector to collect elements in a thread safe array. - * - * @param type the type of elements. - * @param arrayFactory the array factory. - * @param the array element's type. - * @param the array's type. - * @return the collector. - */ - public static > @NotNull Collector concurrentCollector( - @NotNull Class type, - @NotNull Function, A> arrayFactory - ) { - return new Collector<>() { - - private final @NotNull Supplier supplier = () -> arrayFactory.apply(type); - - @Override - public Supplier supplier() { - return supplier; - } - - @Override - public BiConsumer accumulator() { - return Collection::add; - } - - @Override - public BinaryOperator combiner() { - return (source, toAdd) -> { - source.runInWriteLock(toAdd, Array::addAll); - return source; - }; - } - - @Override - public Function finisher() { - return array -> array; - } - - @Override - public Set characteristics() { - return CH_ID_CONC; - } + } + + @Override + public Function finisher() { + return array -> array; + } + + @Override + public Set characteristics() { + return CH_ID; + } + }; + } + + /** + * Get a collector to collect elements in a thread safe array. + * + * @param type the type of elements. + * @param arrayFactory the array factory. + * @param the array element's type. + * @param the array's type. + * @return the collector. + */ + public static > @NotNull Collector concurrentCollector( + @NotNull Class type, + @NotNull Function, A> arrayFactory) { + return new Collector<>() { + + private final @NotNull Supplier supplier = () -> arrayFactory.apply(type); + + @Override + public Supplier supplier() { + return supplier; + } + + @Override + public BiConsumer accumulator() { + return Collection::add; + } + + @Override + public BinaryOperator combiner() { + return (source, toAdd) -> { + source.runInWriteLock(toAdd, Array::addAll); + return source; }; - } - - /** - * Get a collector to collect elements into an array. - * - * @param type the type of elements. - * @param the array element's type. - * @return the collector. - */ - public static @NotNull Collector, Array> toArray(@NotNull Class type) { - return collector(type, ArrayFactory::newArray); - } - - /** - * Get a collector to collect elements in a thread safe array. - * - * @param type the type of elements. - * @param the array element's type. - * @return the collector. - */ - public static @NotNull Collector, ConcurrentArray> toConcurrentArray( - @NotNull Class type - ) { - return concurrentCollector(type, ArrayFactory::newConcurrentStampedLockArray); - } + } + + @Override + public Function finisher() { + return array -> array; + } + + @Override + public Set characteristics() { + return CH_ID_CONC; + } + }; + } + + /** + * Get a collector to collect elements into an array. + * + * @param type the type of elements. + * @param the array element's type. + * @return the collector. + */ + public static @NotNull Collector, Array> toArray(@NotNull Class type) { + return collector(type, ArrayFactory::newArray); + } + + /** + * Get a collector to collect elements in a thread safe array. + * + * @param type the type of elements. + * @param the array element's type. + * @return the collector. + */ + public static @NotNull Collector, ConcurrentArray> toConcurrentArray( + @NotNull Class type) { + return concurrentCollector(type, ArrayFactory::newConcurrentStampedLockArray); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java index ca40020f..734a303b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java @@ -12,25 +12,25 @@ */ public interface ArrayComparator extends Comparator { - @Override - default int compare(@Nullable T first, @Nullable T second) { + @Override + default int compare(@Nullable T first, @Nullable T second) { - if (first == null) { - return 1; - } else if (second == null) { - return -1; - } - - return compareImpl(first, second); + if (first == null) { + return 1; + } else if (second == null) { + return -1; } - /** - * Compare the two objects. - * - * @param first the first. - * @param second the second. - * @return a negative integer, zero, or a positive integer as the first argument - * is less than, equal to, or greater than the second. - */ - int compareImpl(@NotNull T first, @NotNull T second); + return compareImpl(first, second); + } + + /** + * Compare the two objects. + * + * @param first the first. + * @param second the second. + * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater + * than the second. + */ + int compareImpl(@NotNull T first, @NotNull T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java index cf197154..f7aaf868 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java @@ -25,117 +25,119 @@ */ public class ArrayFactory { - public static final Array EMPTY_ARRAY = newReadOnlyArray(ArrayUtils.EMPTY_OBJECT_ARRAY); + public static final Array EMPTY_ARRAY = newReadOnlyArray(ArrayUtils.EMPTY_OBJECT_ARRAY); - @SafeVarargs - public static @NotNull Array asArray(@NotNull E... args) { - return new FastArray<>(args); - } + @SafeVarargs + public static @NotNull Array asArray(@NotNull E... args) { + return new FastArray<>(args); + } - public static @NotNull Array newArray(@NotNull Class type) { - return newUnsafeArray(type); - } + public static @NotNull Array newArray(@NotNull Class type) { + return newUnsafeArray(type); + } - public static @NotNull Array newArray(@NotNull Class type, int capacity) { - return newUnsafeArray(type, capacity); - } + public static @NotNull Array newArray(@NotNull Class type, int capacity) { + return newUnsafeArray(type, capacity); + } - public static @NotNull Array newCopyOnModifyArray(@NotNull Class type) { - return new CopyOnModifyArray<>(type, 0); - } + public static @NotNull Array newCopyOnModifyArray(@NotNull Class type) { + return new CopyOnModifyArray<>(type, 0); + } - public static @NotNull UnsafeArray newUnsafeArray(@NotNull Class type) { - return new FastArray<>(type); - } + public static @NotNull UnsafeArray newUnsafeArray(@NotNull Class type) { + return new FastArray<>(type); + } - public static UnsafeArray newUnsafeArray(@NotNull Class type, int capacity) { - return new FastArray<>(type, capacity); - } + public static UnsafeArray newUnsafeArray(@NotNull Class type, int capacity) { + return new FastArray<>(type, capacity); + } - public static @NotNull ReadOnlyArray newReadOnlyArray(@NotNull E[] elements) { - return new ReadOnlyFastArray<>(elements); - } + public static @NotNull ReadOnlyArray newReadOnlyArray(@NotNull E[] elements) { + return new ReadOnlyFastArray<>(elements); + } - public static @NotNull Array newArraySet(@NotNull Class type) { - return new FastArraySet<>(type); - } + public static @NotNull Array newArraySet(@NotNull Class type) { + return new FastArraySet<>(type); + } - public static @NotNull ConcurrentArray newConcurrentReentrantRWLockArray(@NotNull Class type) { - return new ConcurrentReentrantRWLockArray<>(type); - } + public static @NotNull ConcurrentArray newConcurrentReentrantRWLockArray(@NotNull Class type) { + return new ConcurrentReentrantRWLockArray<>(type); + } - public static @NotNull ConcurrentArray newConcurrentReentrantRWLockArraySet(@NotNull Class type) { - return new ConcurrentReentrantRWLockArraySet<>(type); - } + public static @NotNull ConcurrentArray newConcurrentReentrantRWLockArraySet(@NotNull Class type) { + return new ConcurrentReentrantRWLockArraySet<>(type); + } - public static @NotNull ConcurrentArray newConcurrentAtomicARSWLockArray(@NotNull Class type) { - return new ConcurrentAtomicARSWLockArray<>(type); - } + public static @NotNull ConcurrentArray newConcurrentAtomicARSWLockArray(@NotNull Class type) { + return new ConcurrentAtomicARSWLockArray<>(type); + } - public static @NotNull ConcurrentArray newConcurrentStampedLockArray(@NotNull Class type) { - return new ConcurrentStampedLockArray<>(type); - } + public static @NotNull ConcurrentArray newConcurrentStampedLockArray(@NotNull Class type) { + return new ConcurrentStampedLockArray<>(type); + } - public static @NotNull ConcurrentArray newConcurrentStampedLockArray(E @NotNull [] array) { + public static @NotNull ConcurrentArray newConcurrentStampedLockArray(E @NotNull [] array) { - Class type = unsafeNNCast(array.getClass().getComponentType()); + Class type = unsafeNNCast(array + .getClass() + .getComponentType()); - var result = new ConcurrentStampedLockArray(type, array.length); - result.addAll(array); + var result = new ConcurrentStampedLockArray(type, array.length); + result.addAll(array); - return result; - } + return result; + } - public static @NotNull ConcurrentArray newConcurrentStampedLockArraySet(@NotNull Class type) { - return new ConcurrentStampedLockArraySet<>(type); - } + public static @NotNull ConcurrentArray newConcurrentStampedLockArraySet(@NotNull Class type) { + return new ConcurrentStampedLockArraySet<>(type); + } - public static > @NotNull Array newSortedArray(@NotNull Class type) { - return new SortedFastArray<>(unsafeNNCast(type)); - } + public static > @NotNull Array newSortedArray(@NotNull Class type) { + return new SortedFastArray<>(unsafeNNCast(type)); + } - public static @NotNull Array newSynchronizedArray(@NotNull Class type) { - return new SynchronizedArray<>(type); - } + public static @NotNull Array newSynchronizedArray(@NotNull Class type) { + return new SynchronizedArray<>(type); + } - public static @NotNull MutableIntegerArray newMutableIntegerArray() { - return new DefaultIntegerArray(); - } + public static @NotNull MutableIntegerArray newMutableIntegerArray() { + return new DefaultIntegerArray(); + } - public static @NotNull MutableIntegerArray newMutableIntegerArray(int capacity) { - return new DefaultIntegerArray(capacity); - } + public static @NotNull MutableIntegerArray newMutableIntegerArray(int capacity) { + return new DefaultIntegerArray(capacity); + } - public static @NotNull MutableIntegerArray newMutableIntegerArray(int... numbers) { - return new DefaultIntegerArray(numbers); - } + public static @NotNull MutableIntegerArray newMutableIntegerArray(int... numbers) { + return new DefaultIntegerArray(numbers); + } - public static @NotNull LongArray newLongArray() { - return new FastLongArray(); - } + public static @NotNull LongArray newLongArray() { + return new FastLongArray(); + } - public static @NotNull LongArray newLongArray(int capacity) { - return new FastLongArray(capacity); - } + public static @NotNull LongArray newLongArray(int capacity) { + return new FastLongArray(capacity); + } - public static @NotNull float[] toFloatArray(float... elements) { - return elements; - } + public static @NotNull float[] toFloatArray(float... elements) { + return elements; + } - public static @NotNull int[] toIntArray(int... elements) { - return elements; - } + public static @NotNull int[] toIntArray(int... elements) { + return elements; + } - public static @NotNull long[] toLongArray(long... elements) { - return elements; - } + public static @NotNull long[] toLongArray(long... elements) { + return elements; + } - public static @NotNull boolean[] toBooleanArray(boolean... elements) { - return elements; - } + public static @NotNull boolean[] toBooleanArray(boolean... elements) { + return elements; + } - @SafeVarargs - public static @NotNull T[] toArray(K... elements) { - return elements; - } + @SafeVarargs + public static @NotNull T[] toArray(K... elements) { + return elements; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayIterator.java index 5e36231d..d25c72a1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayIterator.java @@ -10,15 +10,15 @@ */ public interface ArrayIterator extends Iterator { - /** - * Removes the current element using reordering. - */ - void fastRemove(); + /** + * Removes the current element using reordering. + */ + void fastRemove(); - /** - * Index int. - * - * @return the current position of this {@link Array}. - */ - int index(); + /** + * Index int. + * + * @return the current position of this {@link Array}. + */ + int index(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java index bdad106b..153406f4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java @@ -27,819 +27,797 @@ */ public interface ConcurrentArray extends Array { - @SafeVarargs - static @NotNull ConcurrentArray of(@NotNull T... elements) { - return ArrayFactory.newConcurrentStampedLockArray(elements); - } - - /** - * Create a new concurrent array for the element's type. - * - * @param type the element's type. - * @param the element's type. - * @return the new concurrent array. - */ - static @NotNull ConcurrentArray ofType(@NotNull Class type) { - return ArrayFactory.newConcurrentStampedLockArray(type); - } - - /** - * Create a supplier to create new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static @NotNull NotNullSupplier> supplier(@NotNull Class type) { - return () -> ArrayFactory.newConcurrentStampedLockArray(type); - } - - /** - * Create a function to create new arrays. - * - * @param the element's type. - * @return the supplier. - */ - static @NotNull Function, ConcurrentArray> function() { - return ArrayFactory::newConcurrentStampedLockArray; - } - - /** - * Create a function to create new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static @NotNull Function, ConcurrentArray> function(@NotNull Class type) { - return aClass -> ArrayFactory.newConcurrentStampedLockArray(ClassUtils.>unsafeNNCast(type)); - } - - /** - * Lock this array for reading. - * - * @return the stamp of read lock or 0. - */ - default long readLock() { - throw new UnsupportedOperationException(); - } - - /** - * Unlock the read lock. - * - * @param stamp the stamp of read lock. - */ - default void readUnlock(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Try to optimistic read. - * - * @return the stamp of optimistic read or 0 if it was failed. - */ - default long tryOptimisticRead() { - throw new UnsupportedOperationException(); - } - - /** - * Validate this stamp. - * - * @param stamp the stamp. - * @return true is this stamp is valid. - */ - default boolean validate(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Lock this array for writing. - * - * @return the stamp of write lock or 0. - */ - default long writeLock() { - throw new UnsupportedOperationException(); - } - - /** - * Unlock the write lock. - * - * @param stamp the stamp of write lock. - */ - default void writeUnlock(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param consumer the consumer. - * @return this array. - */ - default @NotNull ConcurrentArray forEachInReadLock(@NotNull NotNullConsumer consumer) { - - var stamp = readLock(); - try { - forEach(consumer); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @return this array. - */ - default @NotNull ConcurrentArray forEachInReadLock( - @NotNull T argument, - @NotNull NotNullBiConsumer function - ) { - - var stamp = readLock(); - try { - forEach(argument, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the second argument's type. - * @return this array. - */ - default @NotNull ConcurrentArray forEachInReadLock( - int first, - @NotNull A second, - @NotNull NotNullIntBiObjectConsumer consumer - ) { - - var stamp = readLock(); - try { - forEach(first, second, consumer); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the firs argument's type. - * @param the second argument's type. - * @return this array. - */ - default @NotNull ConcurrentArray forEachInReadLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer consumer - ) { - - var stamp = readLock(); - try { - forEach(first, second, consumer); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @return this array. - */ - default @NotNull ConcurrentArray forEachInReadLockR( - @NotNull T argument, - @NotNull NotNullBiConsumer function - ) { - - var stamp = readLock(); - try { - forEachR(argument, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each converted element under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter from T to C. - * @param function the function. - * @param the argument's type. - * @param the converted type. - * @return this array. - */ - default @NotNull ConcurrentArray forEachConvertedInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer function - ) { - - var stamp = readLock(); - try { - forEachConverted(argument, converter, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each converted element under {@link #readLock()} block. - * - * @param first the first argument. - * @param second the second argument. - * @param converter the converter from E to C. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the converted type. - * @return this array. - * @since 9.8.0 - */ - default @NotNull ConcurrentArray forEachConvertedInReadLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullFunction converter, - @NotNull NotNullTripleConsumer function - ) { - - var stamp = readLock(); - try { - forEachConverted(first, second, converter, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element and converted argument under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter from T to C. - * @param function the function. - * @param the argument's type. - * @param the converted type. - * @return this array. - */ - default @NotNull ConcurrentArray forEachInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer function - ) { - - var stamp = readLock(); - try { - forEach(argument, converter, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function to get some result under {@link #readLock()} block. - * - * @param function the function. - * @param the result's type. - * @return the result from the function. - */ - default @Nullable R getInReadLock(@NotNull NotNullNullableFunction, R> function) { - var stamp = readLock(); - try { - return function.apply(this); - } finally { - readUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #readLock()} block. - * - * @param arg the argument for the function. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.5.0 - */ - default @Nullable R getInReadLock( - @NotNull A arg, - @NotNull NotNullNullableBiFunction, A, R> function - ) { - var stamp = readLock(); - try { - return function.apply(this, arg); - } finally { - readUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #readLock()} block. - * - * @param first the first argument for the function. - * @param second the second argument for the function. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.9.0 - */ - default @Nullable R getInReadLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullNullableTripleFunction, A, T, R> function - ) { - var stamp = readLock(); - try { - return function.apply(this, first, second); - } finally { - readUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #writeLock()} block. - * - * @param function the function. - * @param the result's type. - * @return the result from the function. - */ - default @Nullable R getInWriteLock(@NotNull NotNullNullableFunction, R> function) { - var stamp = writeLock(); - try { - return function.apply(this); - } finally { - writeUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #writeLock()} block. - * - * @param argument the argument for the function. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.5.0 - */ - default @Nullable R getInWriteLock( - @NotNull A argument, - @NotNull NotNullNullableBiFunction, A, R> function - ) { - var stamp = writeLock(); - try { - return function.apply(this, argument); - } finally { - writeUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #writeLock()} block. - * - * @param first the first argument for the function. - * @param second the second argument for the function. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.9.0 - */ - default @Nullable R getInWriteLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullNullableTripleFunction, A, T, R> function - ) { - var stamp = writeLock(); - try { - return function.apply(this, first, second); - } finally { - writeUnlock(stamp); - } - } - - /** - * Execute a function under {@link #readLock()} block. - * - * @param function the function. - * @return this array. - */ - default @NotNull ConcurrentArray runInReadLock(@NotNull NotNullConsumer> function) { - - var stamp = readLock(); - try { - function.accept(this); - } finally { - readUnlock(stamp); - } - - return this; - } - - - /** - * Execute a function under {@link #readLock()} block. - * - * @param the argument's type. - * @param argument the argument. - * @param function the function. - * @return this array. - */ - default @NotNull ConcurrentArray runInReadLock( - @NotNull F argument, - @NotNull NotNullBiConsumer, F> function - ) { - - var stamp = readLock(); - try { - function.accept(this, argument); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #readLock()} block. - * - * @param the first argument's type. - * @param the second argument's type. - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @return this array. - * @since 9.9.0 - */ - default @NotNull ConcurrentArray runInReadLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullTripleConsumer, A, T> function - ) { - - var stamp = readLock(); - try { - function.accept(this, first, second); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #writeLock()} block. - * - * @param function the function. - * @return this array. - */ - default @NotNull ConcurrentArray runInWriteLock(@NotNull NotNullConsumer> function) { - - var stamp = writeLock(); - try { - function.accept(this); - } finally { - writeUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #writeLock()} block. - * - * @param the argument's type. - * @param argument the argument. - * @param function the function. - * @return this array. - */ - default @NotNull ConcurrentArray runInWriteLock( - @NotNull F argument, - @NotNull NotNullBiConsumer, F> function - ) { - - var stamp = writeLock(); - try { - function.accept(this, argument); - } finally { - writeUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #writeLock()} block. - * - * @param first the first argument for the function. - * @param second the second argument for the function. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @return this array. - * @since 9.9.0 - */ - default @NotNull ConcurrentArray runInWriteLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullTripleConsumer, A, T> function - ) { - var stamp = writeLock(); - try { - function.accept(this, first, second); - } finally { - writeUnlock(stamp); - } - return this; - } - - /** - * Search an element using the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - * @since 9.5.0 - */ - default @Nullable E findAnyInReadLock(int argument, @NotNull NotNullIntObjectPredicate filter) { - - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAny(argument, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search an element using the condition by converted value under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converted an element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConvertedInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAnyConverted(argument, converter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search a converted element to int using the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter element to int. - * @param filter the condition. - * @return the found element or null. - * @since 9.6.0 - */ - default @Nullable E findAnyConvertedToIntInReadLock( - int argument, - @NotNull NotNullFunctionInt converter, - @NotNull BiIntPredicate filter - ) { - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAnyConvertedToInt(argument, converter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search a converted element to int using the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param firstConverter the converter element to T. - * @param secondConverter the converter element to int. - * @param filter the condition. - * @param the first converted type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConvertedToIntInReadLock( - int argument, - @NotNull NotNullFunction firstConverter, - @NotNull NotNullFunctionInt secondConverter, - @NotNull BiIntPredicate filter - ) { - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAnyConvertedToInt(argument, firstConverter, secondConverter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search an element by condition under {@link #readLock()} block. - * - * @param the argument's type. - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatchInReadLock(@NotNull T argument, @NotNull NotNullBiPredicate filter) { - - if (isEmpty()) { - return false; - } - - var stamp = readLock(); - try { - return anyMatch(argument, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search an element by condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatchInReadLock(int argument, @NotNull NotNullIntObjectPredicate filter) { - - if (isEmpty()) { - return false; - } - - var stamp = readLock(); - try { - return anyMatch(argument, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Return true if there is at least a converted element for the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return true if there is at least an element for the condition. - * @since 9.7.0 - */ - default boolean anyMatchConvertedInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - if (isEmpty()) { - return false; - } - - var stamp = readLock(); - try { - return anyMatchConverted(argument, converter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. - * - * @param filter the predicate which returns {@code true} for elements to be removed. - * @return {@code true} if any elements were removed. - */ - default boolean removeIfInWriteLock(@NotNull NotNullPredicate filter) { - var stamp = writeLock(); - try { - return removeIf(filter); - } finally { - writeUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. - * - * @param argument the additional argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIfInWriteLock(@NotNull A argument, @NotNull NotNullBiPredicate filter) { - var stamp = writeLock(); - try { - return removeIf(argument, filter); - } finally { - writeUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. - * - * @param argument the additional argument. - * @param converter the converter of the argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the argument converted type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIfInWriteLock( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - var stamp = writeLock(); - try { - return removeIf(argument, converter, filter); - } finally { - writeUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param converter the converter of the elements. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the element converted type. - * @return {@code true} if any elements were removed. - * @since 9.6.0 - */ - default boolean removeIfConvertedInWriteLock( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter - ) { - var stamp = writeLock(); - try { - return removeIfConverted(argument, converter, filter); - } finally { - writeUnlock(stamp); - } - } + @SafeVarargs + static @NotNull ConcurrentArray of(@NotNull T... elements) { + return ArrayFactory.newConcurrentStampedLockArray(elements); + } + + /** + * Create a new concurrent array for the element's type. + * + * @param type the element's type. + * @param the element's type. + * @return the new concurrent array. + */ + static @NotNull ConcurrentArray ofType(@NotNull Class type) { + return ArrayFactory.newConcurrentStampedLockArray(type); + } + + /** + * Create a supplier to create new arrays. + * + * @param type the element's type. + * @param the element's type. + * @return the supplier. + */ + static @NotNull NotNullSupplier> supplier(@NotNull Class type) { + return () -> ArrayFactory.newConcurrentStampedLockArray(type); + } + + /** + * Create a function to create new arrays. + * + * @param the element's type. + * @return the supplier. + */ + static @NotNull Function, ConcurrentArray> function() { + return ArrayFactory::newConcurrentStampedLockArray; + } + + /** + * Create a function to create new arrays. + * + * @param type the element's type. + * @param the element's type. + * @return the supplier. + */ + static @NotNull Function, ConcurrentArray> function(@NotNull Class type) { + return aClass -> ArrayFactory.newConcurrentStampedLockArray(ClassUtils.>unsafeNNCast(type)); + } + + /** + * Lock this array for reading. + * + * @return the stamp of read lock or 0. + */ + default long readLock() { + throw new UnsupportedOperationException(); + } + + /** + * Unlock the read lock. + * + * @param stamp the stamp of read lock. + */ + default void readUnlock(long stamp) { + throw new UnsupportedOperationException(); + } + + /** + * Try to optimistic read. + * + * @return the stamp of optimistic read or 0 if it was failed. + */ + default long tryOptimisticRead() { + throw new UnsupportedOperationException(); + } + + /** + * Validate this stamp. + * + * @param stamp the stamp. + * @return true is this stamp is valid. + */ + default boolean validate(long stamp) { + throw new UnsupportedOperationException(); + } + + /** + * Lock this array for writing. + * + * @return the stamp of write lock or 0. + */ + default long writeLock() { + throw new UnsupportedOperationException(); + } + + /** + * Unlock the write lock. + * + * @param stamp the stamp of write lock. + */ + default void writeUnlock(long stamp) { + throw new UnsupportedOperationException(); + } + + /** + * Apply a function to each element under {@link #readLock()} block. + * + * @param consumer the consumer. + * @return this array. + */ + default @NotNull ConcurrentArray forEachInReadLock(@NotNull NotNullConsumer consumer) { + + var stamp = readLock(); + try { + forEach(consumer); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Apply a function to each element under {@link #readLock()} block. + * + * @param argument the argument. + * @param function the function. + * @param the argument's type. + * @return this array. + */ + default @NotNull ConcurrentArray forEachInReadLock( + @NotNull T argument, + @NotNull NotNullBiConsumer function) { + + var stamp = readLock(); + try { + forEach(argument, function); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Apply a function to each element under {@link #readLock()} block. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the second argument's type. + * @return this array. + */ + default @NotNull ConcurrentArray forEachInReadLock( + int first, + @NotNull A second, + @NotNull NotNullIntBiObjectConsumer consumer) { + + var stamp = readLock(); + try { + forEach(first, second, consumer); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Apply a function to each element under {@link #readLock()} block. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the firs argument's type. + * @param the second argument's type. + * @return this array. + */ + default @NotNull ConcurrentArray forEachInReadLock( + @NotNull F first, + @NotNull S second, + @NotNull NotNullTripleConsumer consumer) { + + var stamp = readLock(); + try { + forEach(first, second, consumer); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Apply a function to each element under {@link #readLock()} block. + * + * @param argument the argument. + * @param function the function. + * @param the argument's type. + * @return this array. + */ + default @NotNull ConcurrentArray forEachInReadLockR( + @NotNull T argument, + @NotNull NotNullBiConsumer function) { + + var stamp = readLock(); + try { + forEachR(argument, function); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Apply a function to each converted element under {@link #readLock()} block. + * + * @param argument the argument. + * @param converter the converter from T to C. + * @param function the function. + * @param the argument's type. + * @param the converted type. + * @return this array. + */ + default @NotNull ConcurrentArray forEachConvertedInReadLock( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiConsumer function) { + + var stamp = readLock(); + try { + forEachConverted(argument, converter, function); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Apply a function to each converted element under {@link #readLock()} block. + * + * @param first the first argument. + * @param second the second argument. + * @param converter the converter from E to C. + * @param function the function. + * @param the first argument's type. + * @param the second argument's type. + * @param the converted type. + * @return this array. + * @since 9.8.0 + */ + default @NotNull ConcurrentArray forEachConvertedInReadLock( + @NotNull F first, + @NotNull S second, + @NotNull NotNullFunction converter, + @NotNull NotNullTripleConsumer function) { + + var stamp = readLock(); + try { + forEachConverted(first, second, converter, function); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Apply a function to each element and converted argument under {@link #readLock()} block. + * + * @param argument the argument. + * @param converter the converter from T to C. + * @param function the function. + * @param the argument's type. + * @param the converted type. + * @return this array. + */ + default @NotNull ConcurrentArray forEachInReadLock( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiConsumer function) { + + var stamp = readLock(); + try { + forEach(argument, converter, function); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Execute a function to get some result under {@link #readLock()} block. + * + * @param function the function. + * @param the result's type. + * @return the result from the function. + */ + default @Nullable R getInReadLock(@NotNull NotNullNullableFunction, R> function) { + var stamp = readLock(); + try { + return function.apply(this); + } finally { + readUnlock(stamp); + } + } + + /** + * Execute a function to get some result under {@link #readLock()} block. + * + * @param arg the argument for the function. + * @param function the function. + * @param the argument's type. + * @param the result's type. + * @return the result from the function. + * @since 9.5.0 + */ + default @Nullable R getInReadLock( + @NotNull A arg, + @NotNull NotNullNullableBiFunction, A, R> function) { + var stamp = readLock(); + try { + return function.apply(this, arg); + } finally { + readUnlock(stamp); + } + } + + /** + * Execute a function to get some result under {@link #readLock()} block. + * + * @param first the first argument for the function. + * @param second the second argument for the function. + * @param function the function. + * @param the first argument's type. + * @param the second argument's type. + * @param the result's type. + * @return the result from the function. + * @since 9.9.0 + */ + default @Nullable R getInReadLock( + @NotNull A first, + @NotNull T second, + @NotNull NotNullNullableTripleFunction, A, T, R> function) { + var stamp = readLock(); + try { + return function.apply(this, first, second); + } finally { + readUnlock(stamp); + } + } + + /** + * Execute a function to get some result under {@link #writeLock()} block. + * + * @param function the function. + * @param the result's type. + * @return the result from the function. + */ + default @Nullable R getInWriteLock(@NotNull NotNullNullableFunction, R> function) { + var stamp = writeLock(); + try { + return function.apply(this); + } finally { + writeUnlock(stamp); + } + } + + /** + * Execute a function to get some result under {@link #writeLock()} block. + * + * @param argument the argument for the function. + * @param function the function. + * @param the argument's type. + * @param the result's type. + * @return the result from the function. + * @since 9.5.0 + */ + default @Nullable R getInWriteLock( + @NotNull A argument, + @NotNull NotNullNullableBiFunction, A, R> function) { + var stamp = writeLock(); + try { + return function.apply(this, argument); + } finally { + writeUnlock(stamp); + } + } + + /** + * Execute a function to get some result under {@link #writeLock()} block. + * + * @param first the first argument for the function. + * @param second the second argument for the function. + * @param function the function. + * @param the first argument's type. + * @param the second argument's type. + * @param the result's type. + * @return the result from the function. + * @since 9.9.0 + */ + default @Nullable R getInWriteLock( + @NotNull A first, + @NotNull T second, + @NotNull NotNullNullableTripleFunction, A, T, R> function) { + var stamp = writeLock(); + try { + return function.apply(this, first, second); + } finally { + writeUnlock(stamp); + } + } + + /** + * Execute a function under {@link #readLock()} block. + * + * @param function the function. + * @return this array. + */ + default @NotNull ConcurrentArray runInReadLock(@NotNull NotNullConsumer> function) { + + var stamp = readLock(); + try { + function.accept(this); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Execute a function under {@link #readLock()} block. + * + * @param the argument's type. + * @param argument the argument. + * @param function the function. + * @return this array. + */ + default @NotNull ConcurrentArray runInReadLock( + @NotNull F argument, + @NotNull NotNullBiConsumer, F> function) { + + var stamp = readLock(); + try { + function.accept(this, argument); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Execute a function under {@link #readLock()} block. + * + * @param the first argument's type. + * @param the second argument's type. + * @param first the first argument. + * @param second the second argument. + * @param function the function. + * @return this array. + * @since 9.9.0 + */ + default @NotNull ConcurrentArray runInReadLock( + @NotNull A first, + @NotNull T second, + @NotNull NotNullTripleConsumer, A, T> function) { + + var stamp = readLock(); + try { + function.accept(this, first, second); + } finally { + readUnlock(stamp); + } + + return this; + } + + /** + * Execute a function under {@link #writeLock()} block. + * + * @param function the function. + * @return this array. + */ + default @NotNull ConcurrentArray runInWriteLock(@NotNull NotNullConsumer> function) { + + var stamp = writeLock(); + try { + function.accept(this); + } finally { + writeUnlock(stamp); + } + + return this; + } + + /** + * Execute a function under {@link #writeLock()} block. + * + * @param the argument's type. + * @param argument the argument. + * @param function the function. + * @return this array. + */ + default @NotNull ConcurrentArray runInWriteLock( + @NotNull F argument, + @NotNull NotNullBiConsumer, F> function) { + + var stamp = writeLock(); + try { + function.accept(this, argument); + } finally { + writeUnlock(stamp); + } + + return this; + } + + /** + * Execute a function under {@link #writeLock()} block. + * + * @param first the first argument for the function. + * @param second the second argument for the function. + * @param function the function. + * @param the first argument's type. + * @param the second argument's type. + * @return this array. + * @since 9.9.0 + */ + default @NotNull ConcurrentArray runInWriteLock( + @NotNull A first, + @NotNull T second, + @NotNull NotNullTripleConsumer, A, T> function) { + var stamp = writeLock(); + try { + function.accept(this, first, second); + } finally { + writeUnlock(stamp); + } + return this; + } + + /** + * Search an element using the condition under {@link #readLock()} block. + * + * @param argument the argument. + * @param filter the condition. + * @return the found element or null. + * @since 9.5.0 + */ + default @Nullable E findAnyInReadLock(int argument, @NotNull NotNullIntObjectPredicate filter) { + + if (isEmpty()) { + return null; + } + + var stamp = readLock(); + try { + return findAny(argument, filter); + } finally { + readUnlock(stamp); + } + } + + /** + * Search an element using the condition by converted value under {@link #readLock()} block. + * + * @param argument the argument. + * @param converter the converted an element to another type. + * @param filter the condition. + * @param the argument's type. + * @param the converted element's type. + * @return the found element or null. + * @since 9.7.0 + */ + default @Nullable E findAnyConvertedInReadLock( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { + if (isEmpty()) { + return null; + } + + var stamp = readLock(); + try { + return findAnyConverted(argument, converter, filter); + } finally { + readUnlock(stamp); + } + } + + /** + * Search a converted element to int using the condition under {@link #readLock()} block. + * + * @param argument the argument. + * @param converter the converter element to int. + * @param filter the condition. + * @return the found element or null. + * @since 9.6.0 + */ + default @Nullable E findAnyConvertedToIntInReadLock( + int argument, + @NotNull NotNullFunctionInt converter, + @NotNull BiIntPredicate filter) { + if (isEmpty()) { + return null; + } + + var stamp = readLock(); + try { + return findAnyConvertedToInt(argument, converter, filter); + } finally { + readUnlock(stamp); + } + } + + /** + * Search a converted element to int using the condition under {@link #readLock()} block. + * + * @param argument the argument. + * @param firstConverter the converter element to T. + * @param secondConverter the converter element to int. + * @param filter the condition. + * @param the first converted type. + * @return the found element or null. + * @since 9.7.0 + */ + default @Nullable E findAnyConvertedToIntInReadLock( + int argument, + @NotNull NotNullFunction firstConverter, + @NotNull NotNullFunctionInt secondConverter, + @NotNull BiIntPredicate filter) { + if (isEmpty()) { + return null; + } + + var stamp = readLock(); + try { + return findAnyConvertedToInt(argument, firstConverter, secondConverter, filter); + } finally { + readUnlock(stamp); + } + } + + /** + * Search an element by condition under {@link #readLock()} block. + * + * @param the argument's type. + * @param argument the argument. + * @param filter the condition. + * @return true if there is at least an element for the condition. + */ + default boolean anyMatchInReadLock(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + + if (isEmpty()) { + return false; + } + + var stamp = readLock(); + try { + return anyMatch(argument, filter); + } finally { + readUnlock(stamp); + } + } + + /** + * Search an element by condition under {@link #readLock()} block. + * + * @param argument the argument. + * @param filter the condition. + * @return true if there is at least an element for the condition. + */ + default boolean anyMatchInReadLock(int argument, @NotNull NotNullIntObjectPredicate filter) { + + if (isEmpty()) { + return false; + } + + var stamp = readLock(); + try { + return anyMatch(argument, filter); + } finally { + readUnlock(stamp); + } + } + + /** + * Return true if there is at least a converted element for the condition under {@link #readLock()} block. + * + * @param argument the argument. + * @param converter the converter element to another type. + * @param filter the condition. + * @param the argument's type. + * @param the converted element's type. + * @return true if there is at least an element for the condition. + * @since 9.7.0 + */ + default boolean anyMatchConvertedInReadLock( + @NotNull T argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { + if (isEmpty()) { + return false; + } + + var stamp = readLock(); + try { + return anyMatchConverted(argument, converter, filter); + } finally { + readUnlock(stamp); + } + } + + /** + * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. + * + * @param filter the predicate which returns {@code true} for elements to be removed. + * @return {@code true} if any elements were removed. + */ + default boolean removeIfInWriteLock(@NotNull NotNullPredicate filter) { + var stamp = writeLock(); + try { + return removeIf(filter); + } finally { + writeUnlock(stamp); + } + } + + /** + * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. + * + * @param argument the additional argument. + * @param filter the predicate which returns {@code true} for elements to be removed. + * @param the argument's type. + * @return {@code true} if any elements were removed. + */ + default boolean removeIfInWriteLock(@NotNull A argument, @NotNull NotNullBiPredicate filter) { + var stamp = writeLock(); + try { + return removeIf(argument, filter); + } finally { + writeUnlock(stamp); + } + } + + /** + * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. + * + * @param argument the additional argument. + * @param converter the converter of the argument. + * @param filter the predicate which returns {@code true} for elements to be removed. + * @param the argument's type. + * @param the argument converted type. + * @return {@code true} if any elements were removed. + */ + default boolean removeIfInWriteLock( + @NotNull A argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { + var stamp = writeLock(); + try { + return removeIf(argument, converter, filter); + } finally { + writeUnlock(stamp); + } + } + + /** + * Removes all of the elements of this collection that satisfy the given predicate. + * + * @param argument the additional argument. + * @param converter the converter of the elements. + * @param filter the predicate which returns {@code true} for elements to be removed. + * @param the argument's type. + * @param the element converted type. + * @return {@code true} if any elements were removed. + * @since 9.6.0 + */ + default boolean removeIfConvertedInWriteLock( + @NotNull A argument, + @NotNull NotNullFunction converter, + @NotNull NotNullBiPredicate filter) { + var stamp = writeLock(); + try { + return removeIfConverted(argument, converter, filter); + } finally { + writeUnlock(stamp); + } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java index 87cabc23..d7992913 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java @@ -2,27 +2,27 @@ public interface ConcurrentIntegerArray { - /** - * Write lock. - */ - default void writeLock() { - } + /** + * Write lock. + */ + default void writeLock() { + } - /** - * Write unlock. - */ - default void writeUnlock() { - } + /** + * Write unlock. + */ + default void writeUnlock() { + } - /** - * Read lock. - */ - default void readLock() { - } + /** + * Read lock. + */ + default void readLock() { + } - /** - * Read unlock. - */ - default void readUnlock() { - } + /** + * Read unlock. + */ + default void readUnlock() { + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java index 921e1839..b025d1bc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java @@ -13,202 +13,201 @@ */ public interface IntegerArray extends Iterable { - @NotNull IntegerArray EMPTY = new ReadOnlyIntegerArray(ArrayUtils.EMPTY_INT_ARRAY); + @NotNull IntegerArray EMPTY = new ReadOnlyIntegerArray(ArrayUtils.EMPTY_INT_ARRAY); - static @NotNull IntegerArray of(int value) { - return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(value)); - } - - static @NotNull IntegerArray of(int v1, int v2) { - return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(v1, v2)); - } + static @NotNull IntegerArray of(int value) { + return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(value)); + } - static @NotNull IntegerArray of(int v1, int v2, int v3) { - return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(v1, v2, v3)); - } + static @NotNull IntegerArray of(int v1, int v2) { + return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(v1, v2)); + } - static @NotNull IntegerArray of(int... values) { - return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(values)); - } + static @NotNull IntegerArray of(int v1, int v2, int v3) { + return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(v1, v2, v3)); + } - /** - * Return the wrapped int array. - * Don't change this array, please. - * - * @return the wrapped int array. - */ - int @NotNull [] array(); + static @NotNull IntegerArray of(int... values) { + return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(values)); + } - default boolean contains(int element) { + /** + * Return the wrapped int array. Don't change this array, please. + * + * @return the wrapped int array. + */ + int @NotNull [] array(); - var array = array(); + default boolean contains(int element) { - for (int i = 0, length = size(); i < length; i++) { - if (array[i] == element) { - return true; - } - } + var array = array(); - return false; + for (int i = 0, length = size(); i < length; i++) { + if (array[i] == element) { + return true; + } } - default boolean containsAll(int @NotNull [] array) { + return false; + } - for (int val : array) { - if (!contains(val)) { - return false; - } - } + default boolean containsAll(int @NotNull [] array) { - return true; + for (int val : array) { + if (!contains(val)) { + return false; + } } - default boolean containsAll(@NotNull IntegerArray array) { + return true; + } - var elements = array.array(); + default boolean containsAll(@NotNull IntegerArray array) { - for (int i = 0, length = array.size(); i < length; i++) { - if (!contains(elements[i])) { - return false; - } - } + var elements = array.array(); - return true; + for (int i = 0, length = array.size(); i < length; i++) { + if (!contains(elements[i])) { + return false; + } } - /** - * Get the first number. - * - * @return the first number. - * @throws IllegalStateException if this array is empty. - */ - int first(); - - /** - * Get a number by the index. - * - * @param index the index. - * @return the number. - */ - int get(int index); - - /** - * Find index of the first equal number in this array. - * - * @param element the checked number. - * @return the found index or -1. - */ - default int indexOf(int element) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - if (element == array[i]) { - return i; - } - } - - return -1; + return true; + } + + /** + * Get the first number. + * + * @return the first number. + * @throws IllegalStateException if this array is empty. + */ + int first(); + + /** + * Get a number by the index. + * + * @param index the index. + * @return the number. + */ + int get(int index); + + /** + * Find index of the first equal number in this array. + * + * @param element the checked number. + * @return the found index or -1. + */ + default int indexOf(int element) { + + var array = array(); + + for (int i = 0, length = size(); i < length; i++) { + if (element == array[i]) { + return i; + } } - /** - * Return true if this array is empty. - * - * @return true if this array is empty. - */ - default boolean isEmpty() { - return size() < 1; - } + return -1; + } + + /** + * Return true if this array is empty. + * + * @return true if this array is empty. + */ + default boolean isEmpty() { + return size() < 1; + } - @Override - @NotNull ArrayIterator iterator(); + @Override + @NotNull ArrayIterator iterator(); - @Override - default void forEach(@NotNull Consumer consumer) { + @Override + default void forEach(@NotNull Consumer consumer) { - var array = array(); + var array = array(); - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i]); - } + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(array[i]); } + } - default void forEachInt(@NotNull IntConsumer consumer) { + default void forEachInt(@NotNull IntConsumer consumer) { - var array = array(); + var array = array(); - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i]); - } + for (int i = 0, length = size(); i < length; i++) { + consumer.accept(array[i]); } - - /** - * Get the last number in this array. - * - * @return the last number. - * @throws IllegalStateException if this array is empty. - */ - int last(); - - /** - * Find index of the last equal number in this array. - * - * @param element the checked number. - * @return the found index or -1. - */ - default int lastIndexOf(int element) { - - var array = array(); - var last = -1; - - for (int i = 0, length = size(); i < length; i++) { - if (element == array[i]) { - last = i; - } - } - - return last; + } + + /** + * Get the last number in this array. + * + * @return the last number. + * @throws IllegalStateException if this array is empty. + */ + int last(); + + /** + * Find index of the last equal number in this array. + * + * @param element the checked number. + * @return the found index or -1. + */ + default int lastIndexOf(int element) { + + var array = array(); + var last = -1; + + for (int i = 0, length = size(); i < length; i++) { + if (element == array[i]) { + last = i; + } } - /** - * Get the current count of numbers in this array. - * - * @return the current count of numbers in this array. - */ - int size(); - - /** - * Create new array from this array. - * - * @return the array with data from this array. - */ - default int @NotNull [] toArray() { - return ArrayUtils.copyOfRange(array(), 0, size()); + return last; + } + + /** + * Get the current count of numbers in this array. + * + * @return the current count of numbers in this array. + */ + int size(); + + /** + * Create new array from this array. + * + * @return the array with data from this array. + */ + default int @NotNull [] toArray() { + return ArrayUtils.copyOfRange(array(), 0, size()); + } + + /** + * Copy or create new array from this array. + * + * @param newArray the new array. + * @return the array with data from this array. + */ + default int @NotNull [] toArray(int @NotNull [] newArray) { + + var array = array(); + + if (newArray.length >= size()) { + + for (int i = 0, j = 0, length = array.length, newLength = newArray.length; i < length && j < newLength; i++) { + newArray[j++] = array[i]; + } + + return newArray; } - /** - * Copy or create new array from this array. - * - * @param newArray the new array. - * @return the array with data from this array. - */ - default int @NotNull [] toArray(int @NotNull [] newArray) { - - var array = array(); - - if (newArray.length >= size()) { + return ArrayUtils.copyOfRange(array(), 0, size()); + } - for (int i = 0, j = 0, length = array.length, newLength = newArray.length; i < length && j < newLength; i++) { - newArray[j++] = array[i]; - } - - return newArray; - } - - return ArrayUtils.copyOfRange(array(), 0, size()); - } - - default @NotNull IntStream stream() { - return Arrays.stream(array(), 0, size()); - } + default @NotNull IntStream stream() { + return Arrays.stream(array(), 0, size()); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java index b4dc80b4..b181bff6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java @@ -7,327 +7,337 @@ */ public interface LongArray extends Iterable { - /** - * Add long array. - * - * @param element the element - * @return the long array - */ - LongArray add(long element); - - /** - * Add all long array. - * - * @param array the array - * @return the long array - */ - LongArray addAll(long[] array); - - /** - * Add all long array. - * - * @param array the array - * @return the long array - */ - LongArray addAll(LongArray array); - - /** - * Array long [ ]. - * - * @return the long [ ] - */ - long[] array(); - - /** - * Clear long array. - * - * @return the long array - */ - LongArray clear(); - - /** - * Contains boolean. - * - * @param element the element - * @return the boolean - */ - default boolean contains(final long element) { - - final long[] array = array(); - - for (int i = 0, length = size(); i < length; i++) { - if (array[i] == element) return true; - } - - return false; + /** + * Add long array. + * + * @param element the element + * @return the long array + */ + LongArray add(long element); + + /** + * Add all long array. + * + * @param array the array + * @return the long array + */ + LongArray addAll(long[] array); + + /** + * Add all long array. + * + * @param array the array + * @return the long array + */ + LongArray addAll(LongArray array); + + /** + * Array long [ ]. + * + * @return the long [ ] + */ + long[] array(); + + /** + * Clear long array. + * + * @return the long array + */ + LongArray clear(); + + /** + * Contains boolean. + * + * @param element the element + * @return the boolean + */ + default boolean contains(final long element) { + + final long[] array = array(); + + for (int i = 0, length = size(); i < length; i++) { + if (array[i] == element) { + return true; + } } - /** - * Contains all boolean. - * - * @param array the array - * @return the boolean - */ - default boolean containsAll(final long[] array) { + return false; + } - for (final long val : array) { - if (!contains(val)) return false; - } + /** + * Contains all boolean. + * + * @param array the array + * @return the boolean + */ + default boolean containsAll(final long[] array) { - return true; + for (final long val : array) { + if (!contains(val)) { + return false; + } } - /** - * Contains all boolean. - * - * @param array the array - * @return the boolean - */ - default boolean containsAll(final LongArray array) { - - final long[] elements = array.array(); + return true; + } - for (int i = 0, length = array.size(); i < length; i++) { - if (!contains(elements[i])) { - return false; - } - } + /** + * Contains all boolean. + * + * @param array the array + * @return the boolean + */ + default boolean containsAll(final LongArray array) { - return true; - } + final long[] elements = array.array(); - /** - * Fast remove boolean. - * - * @param index the index - * @return the boolean - */ - boolean fastRemove(int index); - - /** - * Fast remove boolean. - * - * @param element the element - * @return the boolean - */ - default boolean fastRemove(final long element) { - - final int index = indexOf(element); - if (index > -1) fastRemove(index); - - return index > -1; + for (int i = 0, length = array.size(); i < length; i++) { + if (!contains(elements[i])) { + return false; + } } - /** - * First long. - * - * @return the long - */ - long first(); - - /** - * Get long. - * - * @param index the index - * @return the long - */ - long get(int index); - - /** - * Index of int. - * - * @param element the element - * @return the int - */ - default int indexOf(final long element) { - - final long[] array = array(); - - for (int i = 0, length = size(); i < length; i++) { - if (element == array[i]) { - return i; - } - } - - return -1; + return true; + } + + /** + * Fast remove boolean. + * + * @param index the index + * @return the boolean + */ + boolean fastRemove(int index); + + /** + * Fast remove boolean. + * + * @param element the element + * @return the boolean + */ + default boolean fastRemove(final long element) { + + final int index = indexOf(element); + if (index > -1) { + fastRemove(index); } - /** - * Is empty boolean. - * - * @return the boolean - */ - boolean isEmpty(); - - @Override - ArrayIterator iterator(); - - /** - * Last long. - * - * @return the long - */ - long last(); - - /** - * Last index of int. - * - * @param element the element - * @return the int - */ - default int lastIndexOf(final long element) { - - final long[] array = array(); - - int last = -1; - - for (int i = 0, length = size(); i < length; i++) { - if (element == array[i]) { - last = i; - } - } - - return last; + return index > -1; + } + + /** + * First long. + * + * @return the long + */ + long first(); + + /** + * Get long. + * + * @param index the index + * @return the long + */ + long get(int index); + + /** + * Index of int. + * + * @param element the element + * @return the int + */ + default int indexOf(final long element) { + + final long[] array = array(); + + for (int i = 0, length = size(); i < length; i++) { + if (element == array[i]) { + return i; + } } - /** - * Poll long. - * - * @return the long - */ - long poll(); - - /** - * Pop long. - * - * @return the long - */ - long pop(); - - /** - * Read lock. - */ - default void readLock() { + return -1; + } + + /** + * Is empty boolean. + * + * @return the boolean + */ + boolean isEmpty(); + + @Override + ArrayIterator iterator(); + + /** + * Last long. + * + * @return the long + */ + long last(); + + /** + * Last index of int. + * + * @param element the element + * @return the int + */ + default int lastIndexOf(final long element) { + + final long[] array = array(); + + int last = -1; + + for (int i = 0, length = size(); i < length; i++) { + if (element == array[i]) { + last = i; + } } - /** - * Read unlock. - */ - default void readUnlock() { + return last; + } + + /** + * Poll long. + * + * @return the long + */ + long poll(); + + /** + * Pop long. + * + * @return the long + */ + long pop(); + + /** + * Read lock. + */ + default void readLock() { + } + + /** + * Read unlock. + */ + default void readUnlock() { + } + + /** + * Remove all boolean. + * + * @param target the target + * @return the boolean + */ + default boolean removeAll(final LongArray target) { + if (target.isEmpty()) { + return true; } - /** - * Remove all boolean. - * - * @param target the target - * @return the boolean - */ - default boolean removeAll(final LongArray target) { - if (target.isEmpty()) return true; - - final long[] array = target.array(); + final long[] array = target.array(); - for (int i = 0, length = target.size(); i < length; i++) { - fastRemove(array[i]); - } - - return true; + for (int i = 0, length = target.size(); i < length; i++) { + fastRemove(array[i]); } - /** - * Retain all boolean. - * - * @param target the target - * @return the boolean - */ - default boolean retainAll(final LongArray target) { + return true; + } - final long[] array = array(); + /** + * Retain all boolean. + * + * @param target the target + * @return the boolean + */ + default boolean retainAll(final LongArray target) { - for (int i = 0, length = size(); i < length; i++) { - if (!target.contains(array[i])) { - fastRemove(i--); - length--; - } - } + final long[] array = array(); - return true; + for (int i = 0, length = size(); i < length; i++) { + if (!target.contains(array[i])) { + fastRemove(i--); + length--; + } } - /** - * Size int. - * - * @return the int - */ - int size(); - - /** - * Slow remove boolean. - * - * @param index the index - * @return the boolean - */ - boolean slowRemove(int index); - - /** - * Slow remove boolean. - * - * @param element the element - * @return the boolean - */ - default boolean slowRemove(final long element) { - - final int index = indexOf(element); - if (index > -1) slowRemove(index); - - return index > -1; + return true; + } + + /** + * Size int. + * + * @return the int + */ + int size(); + + /** + * Slow remove boolean. + * + * @param index the index + * @return the boolean + */ + boolean slowRemove(int index); + + /** + * Slow remove boolean. + * + * @param element the element + * @return the boolean + */ + default boolean slowRemove(final long element) { + + final int index = indexOf(element); + if (index > -1) { + slowRemove(index); } - /** - * Sort long array. - * - * @return the long array - */ - LongArray sort(); - - /** - * To array long [ ]. - * - * @param newArray the new array - * @return the long [ ] - */ - default long[] toArray(final long[] newArray) { + return index > -1; + } - final long[] array = array(); + /** + * Sort long array. + * + * @return the long array + */ + LongArray sort(); - if (newArray.length >= size()) { + /** + * To array long [ ]. + * + * @param newArray the new array + * @return the long [ ] + */ + default long[] toArray(final long[] newArray) { - for (int i = 0, j = 0, length = array.length, newLength = newArray.length; i < length && j < newLength; i++) { - newArray[j++] = array[i]; - } + final long[] array = array(); - return newArray; - } + if (newArray.length >= size()) { - return ArrayUtils.copyOf(array, 0); - } + for (int i = 0, j = 0, length = array.length, newLength = newArray.length; i < length && j < newLength; i++) { + newArray[j++] = array[i]; + } - /** - * Trim to size long array. - * - * @return the long array - */ - LongArray trimToSize(); - - /** - * Write lock. - */ - default void writeLock() { + return newArray; } - /** - * Write unlock. - */ - default void writeUnlock() { - } + return ArrayUtils.copyOf(array, 0); + } + + /** + * Trim to size long array. + * + * @return the long array + */ + LongArray trimToSize(); + + /** + * Write lock. + */ + default void writeLock() { + } + + /** + * Write unlock. + */ + default void writeUnlock() { + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java index 1101f5c9..a582c1f8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java @@ -4,160 +4,160 @@ public interface MutableIntegerArray extends IntegerArray { - /** - * Add a new number to this array. - * - * @param number the new integer. - * @return this array. - */ - @NotNull IntegerArray add(int number); - - /** - * Add new numbers to this array. - * - * @param numbers the new numbers. - * @return this array. - */ - @NotNull IntegerArray addAll(int @NotNull [] numbers); - - /** - * Add new numbers to this array. - * - * @param numbers the new numbers. - * @return this array. - */ - @NotNull IntegerArray addAll(@NotNull IntegerArray numbers); - - /** - * Clear this array. - * - * @return this array. - */ - @NotNull IntegerArray clear(); - - /** - * Remove the first equal number in array with putting last number to position of removed number. - * - * @param number the number to remove. - * @return true if the number was removed. - */ - default boolean fastRemove(int number) { - - var index = indexOf(number); - - if (index > -1){ - fastRemoveByIndex(index); - } - - return index > -1; + /** + * Add a new number to this array. + * + * @param number the new integer. + * @return this array. + */ + @NotNull IntegerArray add(int number); + + /** + * Add new numbers to this array. + * + * @param numbers the new numbers. + * @return this array. + */ + @NotNull IntegerArray addAll(int @NotNull [] numbers); + + /** + * Add new numbers to this array. + * + * @param numbers the new numbers. + * @return this array. + */ + @NotNull IntegerArray addAll(@NotNull IntegerArray numbers); + + /** + * Clear this array. + * + * @return this array. + */ + @NotNull IntegerArray clear(); + + /** + * Remove the first equal number in array with putting last number to position of removed number. + * + * @param number the number to remove. + * @return true if the number was removed. + */ + default boolean fastRemove(int number) { + + var index = indexOf(number); + + if (index > -1) { + fastRemoveByIndex(index); } - /** - * Remove a number by the index from this array with putting last number to position of removed number. - * - * @param index the index of number to remove. - * @return true if the number was removed. - */ - boolean fastRemoveByIndex(int index); - - /** - * Get and remove the first number from this array. - * - * @return the first number. - * @throws IllegalStateException if this array is empty. - */ - int poll(); - - /** - * Get and remove the last number from this array. - * - * @return the last number. - * @throws IllegalStateException if this array is empty. - */ - int pop(); - - /** - * Remove the numbers from this array. - * - * @param numbers the array of numbers to remove. - * @return true if at least one number was removed from this array. - */ - default boolean removeAll(@NotNull IntegerArray numbers) { - - if (numbers.isEmpty()) { - return false; - } - - var array = numbers.array(); - var count = 0; - - for (int i = 0, length = numbers.size(); i < length; i++) { - if(fastRemove(array[i])) { - count++; - } - } - - return count > 0; + return index > -1; + } + + /** + * Remove a number by the index from this array with putting last number to position of removed number. + * + * @param index the index of number to remove. + * @return true if the number was removed. + */ + boolean fastRemoveByIndex(int index); + + /** + * Get and remove the first number from this array. + * + * @return the first number. + * @throws IllegalStateException if this array is empty. + */ + int poll(); + + /** + * Get and remove the last number from this array. + * + * @return the last number. + * @throws IllegalStateException if this array is empty. + */ + int pop(); + + /** + * Remove the numbers from this array. + * + * @param numbers the array of numbers to remove. + * @return true if at least one number was removed from this array. + */ + default boolean removeAll(@NotNull IntegerArray numbers) { + + if (numbers.isEmpty()) { + return false; } - /** - * Remove numbers from this array which is not exist in the target array. - * - * @param numbers the array of numbers. - * @return true if at least one number was removed from this array. - */ - default boolean retainAll(@NotNull IntegerArray numbers) { - - var array = array(); - var count = 0; - - for (int i = 0, length = size(); i < length; i++) { - if (!numbers.contains(array[i])) { - removeByIndex(i--); - length--; - count++; - } - } - - return count > 0; + var array = numbers.array(); + var count = 0; + + for (int i = 0, length = numbers.size(); i < length; i++) { + if (fastRemove(array[i])) { + count++; + } + } + + return count > 0; + } + + /** + * Remove numbers from this array which is not exist in the target array. + * + * @param numbers the array of numbers. + * @return true if at least one number was removed from this array. + */ + default boolean retainAll(@NotNull IntegerArray numbers) { + + var array = array(); + var count = 0; + + for (int i = 0, length = size(); i < length; i++) { + if (!numbers.contains(array[i])) { + removeByIndex(i--); + length--; + count++; + } } - /** - * Remove the first equal number in array. - * - * @param number the number to remove. - * @return true if the number was removed. - */ - default boolean remove(int number) { + return count > 0; + } - var index = indexOf(number); + /** + * Remove the first equal number in array. + * + * @param number the number to remove. + * @return true if the number was removed. + */ + default boolean remove(int number) { - if (index > -1) { - removeByIndex(index); - } + var index = indexOf(number); - return index > -1; + if (index > -1) { + removeByIndex(index); } - /** - * Remove a number by the index from this array. - * - * @param index the index. - * @return true if the number was removed. - */ - boolean removeByIndex(int index); - - /** - * Sort this array. - * - * @return this array. - */ - @NotNull IntegerArray sort(); - - /** - * Resize wrapped array to the relevant size. - * - * @return this array. - */ - @NotNull IntegerArray trimToSize(); + return index > -1; + } + + /** + * Remove a number by the index from this array. + * + * @param index the index. + * @return true if the number was removed. + */ + boolean removeByIndex(int index); + + /** + * Sort this array. + * + * @return this array. + */ + @NotNull IntegerArray sort(); + + /** + * Resize wrapped array to the relevant size. + * + * @return this array. + */ + @NotNull IntegerArray trimToSize(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java index 1e1ba3b9..ac6219b3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java @@ -13,63 +13,63 @@ */ public interface ReadOnlyArray extends Array { - @Override - @Deprecated - void apply(@NotNull Function function); + @Override + @Deprecated + void apply(@NotNull Function function); - @Override - @Deprecated - boolean add(E e); + @Override + @Deprecated + boolean add(E e); - @Override - @Deprecated - boolean addAll(@NotNull E[] array); + @Override + @Deprecated + boolean addAll(@NotNull E[] array); - @Override - @Deprecated - boolean addAll(@NotNull Array array); + @Override + @Deprecated + boolean addAll(@NotNull Array array); - @Override - @Deprecated - boolean addAll(@NotNull Collection c); + @Override + @Deprecated + boolean addAll(@NotNull Collection c); - @Override - @Deprecated - boolean fastRemove(@NotNull Object object); + @Override + @Deprecated + boolean fastRemove(@NotNull Object object); - @Override - @Deprecated - @NotNull E remove(int index); + @Override + @Deprecated + @NotNull E remove(int index); - @Override - @Deprecated - boolean removeIf(@NotNull Predicate filter); + @Override + @Deprecated + boolean removeIf(@NotNull Predicate filter); - @Override - @Deprecated - boolean retainAll(@NotNull Collection target) ; + @Override + @Deprecated + boolean retainAll(@NotNull Collection target); - @Override - @Deprecated - boolean retainAll(@NotNull Array target); + @Override + @Deprecated + boolean retainAll(@NotNull Array target); - @Override - @Deprecated - boolean removeAll(@NotNull Collection target); + @Override + @Deprecated + boolean removeAll(@NotNull Collection target); - @Override - @Deprecated - boolean removeAll(@NotNull Array target); + @Override + @Deprecated + boolean removeAll(@NotNull Array target); - @Override - @Deprecated - boolean remove(@NotNull Object object); + @Override + @Deprecated + boolean remove(@NotNull Object object); - @Override - @Deprecated - void clear(); + @Override + @Deprecated + void clear(); - @Override - @Deprecated - @NotNull Array sort(@NotNull ArrayComparator comparator); + @Override + @Deprecated + @NotNull Array sort(@NotNull ArrayComparator comparator); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java index 215dcfe8..b79b573b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java @@ -11,49 +11,49 @@ */ public interface UnsafeArray extends Array { - /** - * Prepare this array for the target size. - * - * @param size the size. - */ - default void prepareForSize(int size) { - throw new UnsupportedOperationException(); - } + /** + * Prepare this array for the target size. + * + * @param size the size. + */ + default void prepareForSize(int size) { + throw new UnsupportedOperationException(); + } - /** - * Add the new element without any checks. - * - * @param object the new element. - * @return true if this array was changed. - */ - default boolean unsafeAdd(@NotNull E object) { - throw new UnsupportedOperationException(); - } + /** + * Add the new element without any checks. + * + * @param object the new element. + * @return true if this array was changed. + */ + default boolean unsafeAdd(@NotNull E object) { + throw new UnsupportedOperationException(); + } - /** - * Get the element for the index without any checks. - * - * @param index the index. - * @return the element or null. - */ - default @Nullable E unsafeGet(int index) { - throw new UnsupportedOperationException(); - } + /** + * Get the element for the index without any checks. + * + * @param index the index. + * @return the element or null. + */ + default @Nullable E unsafeGet(int index) { + throw new UnsupportedOperationException(); + } - /** - * Set the element for the index without any checks. - * - * @param index the index. - * @param element the element. - */ - default void unsafeSet(int index, @NotNull E element) { - throw new UnsupportedOperationException(); - } + /** + * Set the element for the index without any checks. + * + * @param index the index. + * @param element the element. + */ + default void unsafeSet(int index, @NotNull E element) { + throw new UnsupportedOperationException(); + } - /** - * Reduce wrapped array to size of this array. - * - * @return the array - */ - @NotNull Array trimToSize(); + /** + * Reduce wrapped array to size of this array. + * + * @return the array + */ + @NotNull Array trimToSize(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java index 40b04c76..0e143ab3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java @@ -17,83 +17,82 @@ */ public abstract class AbstractArray implements Array { - private static final long serialVersionUID = 2113052245369887690L; + private static final long serialVersionUID = 2113052245369887690L; - /** - * The default size of new backend array. - */ - protected static final int DEFAULT_CAPACITY = 10; + /** + * The default size of new backend array. + */ + protected static final int DEFAULT_CAPACITY = 10; - public AbstractArray(@NotNull Class type) { - this(type, DEFAULT_CAPACITY); - } - - public AbstractArray(@NotNull Class type, int capacity) { - super(); + public AbstractArray(@NotNull Class type) { + this(type, DEFAULT_CAPACITY); + } - if (capacity < 0) { - throw new IllegalArgumentException("Negative capacity"); - } + public AbstractArray(@NotNull Class type, int capacity) { + super(); - setArray(ArrayUtils.create(type, capacity)); + if (capacity < 0) { + throw new IllegalArgumentException("Negative capacity"); } - public AbstractArray(@NotNull E[] array) { - super(); - setArray(array); - setSize(array.length); - } + setArray(ArrayUtils.create(type, capacity)); + } - @Override - public void clear() { - if (!isEmpty()) { - ArrayUtils.clear(array()); - setSize(0); - } - } + public AbstractArray(@NotNull E[] array) { + super(); + setArray(array); + setSize(array.length); + } - @Override - public void free() { - clear(); + @Override + public void clear() { + if (!isEmpty()) { + ArrayUtils.clear(array()); + setSize(0); } + } - @Override - public @NotNull AbstractArray clone() throws CloneNotSupportedException { - return ClassUtils.unsafeNNCast(super.clone()); - } + @Override + public void free() { + clear(); + } - protected abstract void setArray(E @NotNull [] array); - protected abstract void setSize(int size); + @Override + public @NotNull AbstractArray clone() throws CloneNotSupportedException { + return ClassUtils.unsafeNNCast(super.clone()); + } - @Override - public String toString() { - return getClass().getSimpleName() + " size = " + size() + - " :\n " + ArrayUtils.toString(this); - } + protected abstract void setArray(E @NotNull [] array); - @Override - public @NotNull String toString(@NotNull Function toString) { - return getClass().getSimpleName() + " size = " + size() + - " :\n " + ArrayUtils.toString(this, toString); - } + protected abstract void setSize(int size); - @Override - public boolean equals(@Nullable Object another) { + @Override + public String toString() { + return getClass().getSimpleName() + " size = " + size() + " :\n " + ArrayUtils.toString(this); + } - if (this == another) { - return true; - } else if (!(another instanceof Array)) { - return false; - } + @Override + public @NotNull String toString(@NotNull Function toString) { + return getClass().getSimpleName() + " size = " + size() + " :\n " + ArrayUtils.toString(this, toString); + } - var array = (Array) another; - return size() == array.size() && Arrays.equals(array(), 0, size(), array.array(), 0, array.size()); - } + @Override + public boolean equals(@Nullable Object another) { - @Override - public int hashCode() { - int result = Objects.hash(size()); - result = 31 * result + Arrays.hashCode(array()); - return result; + if (this == another) { + return true; + } else if (!(another instanceof Array)) { + return false; } + + var array = (Array) another; + return size() == array.size() && Arrays.equals(array(), 0, size(), array.array(), 0, array.size()); + } + + @Override + public int hashCode() { + int result = Objects.hash(size()); + result = 31 * result + Arrays.hashCode(array()); + return result; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java index d20d9e3c..75602526 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java @@ -4,7 +4,7 @@ import java.util.Collection; import java.util.NoSuchElementException; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayIterator; @@ -19,263 +19,264 @@ * @author JavaSaBr */ @SuppressWarnings("NonAtomicOperationOnVolatileField") -public abstract class AbstractConcurrentArray extends AbstractArray implements ConcurrentArray, UnsafeArray { +public abstract class AbstractConcurrentArray extends AbstractArray implements ConcurrentArray, + UnsafeArray { - private static final long serialVersionUID = -6291504312637658721L; + private static final long serialVersionUID = -6291504312637658721L; - /** - * The count of elements in this array. - */ - private final AtomicInteger size; + /** + * The count of elements in this array. + */ + private final ReusableAtomicInteger size; - /** - * The unsafe array. - */ - @SuppressWarnings("NullableProblems") - private volatile E @NotNull [] array; + /** + * The unsafe array. + */ + @SuppressWarnings("NullableProblems") + private volatile E @NotNull [] array; - public AbstractConcurrentArray(@NotNull Class type) { - this(type, 10); - } - - public AbstractConcurrentArray(@NotNull Class type, int size) { - super(type, size); - this.size = new AtomicInteger(); - } + public AbstractConcurrentArray(@NotNull Class type) { + this(type, 10); + } - @Override - public boolean add(@NotNull E element) { + public AbstractConcurrentArray(@NotNull Class type, int size) { + super(type, size); + this.size = new ReusableAtomicInteger(); + } - if (size() == array.length) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(array.length >> 1, 1)); - } + @Override + public boolean add(@NotNull E element) { - array[size.getAndIncrement()] = element; - return true; + if (size() == array.length) { + array = ArrayUtils.copyOfAndExtend(array, Math.max(array.length >> 1, 1)); } - @Override - public final boolean addAll(@NotNull Array elements) { - - if (elements.isEmpty()) { - return false; - } + array[size.getAndIncrement()] = element; + return true; + } - var current = array.length; - var selfSize = size(); - var targetSize = elements.size(); - var diff = selfSize + targetSize - current; + @Override + public final boolean addAll(@NotNull Array elements) { - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; + if (elements.isEmpty()) { + return false; } - @Override - public boolean addAll(@NotNull Collection collection) { - - if (collection.isEmpty()) { - return false; - } + var current = array.length; + var selfSize = size(); + var targetSize = elements.size(); + var diff = selfSize + targetSize - current; - var current = array.length; - var diff = size() + collection.size() - current; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); + } - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); - } + processAdd(elements, selfSize, targetSize); + return true; + } - for (var element : collection) { - unsafeAdd(element); - } + @Override + public boolean addAll(@NotNull Collection collection) { - return true; + if (collection.isEmpty()) { + return false; } - @Override - public final boolean addAll(@NotNull E[] elements) { + var current = array.length; + var diff = size() + collection.size() - current; - if (elements.length < 1) { - return false; - } + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); + } - var current = array.length; - var selfSize = size(); - var targetSize = elements.length; - var diff = selfSize + targetSize - current; + for (var element : collection) { + unsafeAdd(element); + } - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } + return true; + } - processAdd(elements, selfSize, targetSize); - return true; - } + @Override + public final boolean addAll(@NotNull E[] elements) { - @Override - public final @NotNull E[] array() { - return array; + if (elements.length < 1) { + return false; } - @Override - public void prepareForSize(int size) { + var current = array.length; + var selfSize = size(); + var targetSize = elements.length; + var diff = selfSize + targetSize - current; - var current = array.length; - var selfSize = size(); - var diff = selfSize + size - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); - } + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); } - @Override - public final @NotNull E fastRemove(int index) { + processAdd(elements, selfSize, targetSize); + return true; + } - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } + @Override + public final @NotNull E[] array() { + return array; + } - var newSize = size.decrementAndGet(); - var old = array[index]; + @Override + public void prepareForSize(int size) { - array[index] = array[newSize]; - array[newSize] = null; + var current = array.length; + var selfSize = size(); + var diff = selfSize + size - current; - return old; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); } + } - @Override - public final @NotNull E get(int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } + @Override + public final @NotNull E fastRemove(int index) { - return array[index]; + if (index < 0 || index >= size()) { + throw new NoSuchElementException(); } - @Override - public final @NotNull ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } + var newSize = size.decrementAndGet(); + var old = array[index]; - @Override - public void replace(int index, @NotNull E element) { + array[index] = array[newSize]; + array[newSize] = null; - if (index < 0 || index >= size()) { - throw new ArrayIndexOutOfBoundsException(); - } + return old; + } - array[index] = element; - } + @Override + public final @NotNull E get(int index) { - @Override - protected final void setArray(E @NotNull [] array) { - this.array = array; + if (index < 0 || index >= size()) { + throw new NoSuchElementException(); } - @Override - protected final void setSize(final int size) { - this.size.getAndSet(size); - } + return array[index]; + } + + @Override + public final @NotNull ArrayIterator iterator() { + return new DefaultArrayIterator<>(this); + } + + @Override + public void replace(int index, @NotNull E element) { - @Override - public final int size() { - return size.get(); + if (index < 0 || index >= size()) { + throw new ArrayIndexOutOfBoundsException(); } - @Override - public @NotNull E remove(int index) { + array[index] = element; + } - if (index < 0 || index >= size()) { - throw new ArrayIndexOutOfBoundsException(); - } + @Override + protected final void setArray(E @NotNull [] array) { + this.array = array; + } - var length = size(); - var numMoved = length - index - 1; + @Override + protected final void setSize(final int size) { + this.size.getAndSet(size); + } - var old = array[index]; + @Override + public final int size() { + return size.get(); + } - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } + @Override + public @NotNull E remove(int index) { - array[size.decrementAndGet()] = null; - return old; + if (index < 0 || index >= size()) { + throw new ArrayIndexOutOfBoundsException(); } - @Override - public final @NotNull AbstractConcurrentArray trimToSize() { + var length = size(); + var numMoved = length - index - 1; - var size = size(); + var old = array[index]; - if (size == array.length) { - return this; - } - - array = ArrayUtils.copyOfRange(array, 0, size); - return this; + if (numMoved > 0) { + System.arraycopy(array, index + 1, array, index, numMoved); } - @Override - public boolean unsafeAdd(@NotNull E object) { - array[size.getAndIncrement()] = object; - return true; - } + array[size.decrementAndGet()] = null; + return old; + } - @Override - public @NotNull E unsafeGet(int index) { - return array[index]; - } + @Override + public final @NotNull AbstractConcurrentArray trimToSize() { - @Override - public void unsafeSet(final int index, @NotNull final E element) { + var size = size(); - if (array[index] != null) { - size.decrementAndGet(); - } - - array[index] = element; - size.incrementAndGet(); + if (size == array.length) { + return this; } - /** - * Process of adding the elements. - * - * @param elements the elements - * @param selfSize the self size - * @param targetSize the target size - */ - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { - System.arraycopy(elements.array(), 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } + array = ArrayUtils.copyOfRange(array, 0, size); + return this; + } - /** - * Process of adding the elements. - * - * @param elements the elements - * @param selfSize the self size - * @param targetSize the target size - */ - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { - System.arraycopy(elements, 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } + @Override + public boolean unsafeAdd(@NotNull E object) { + array[size.getAndIncrement()] = object; + return true; + } - @Override - public @NotNull UnsafeArray asUnsafe() { - return this; - } + @Override + public @NotNull E unsafeGet(int index) { + return array[index]; + } + + @Override + public void unsafeSet(final int index, @NotNull final E element) { - @Override - public @NotNull AbstractConcurrentArray clone() throws CloneNotSupportedException { - var clone = (AbstractConcurrentArray) super.clone(); - clone.array = ArrayUtils.copyOfAndExtend(array, size()); - return clone; + if (array[index] != null) { + size.decrementAndGet(); } + + array[index] = element; + size.incrementAndGet(); + } + + /** + * Process of adding the elements. + * + * @param elements the elements + * @param selfSize the self size + * @param targetSize the target size + */ + protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + System.arraycopy(elements.array(), 0, array, selfSize, targetSize); + size.set(selfSize + targetSize); + } + + /** + * Process of adding the elements. + * + * @param elements the elements + * @param selfSize the self size + * @param targetSize the target size + */ + protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + System.arraycopy(elements, 0, array, selfSize, targetSize); + size.set(selfSize + targetSize); + } + + @Override + public @NotNull UnsafeArray asUnsafe() { + return this; + } + + @Override + public @NotNull AbstractConcurrentArray clone() throws CloneNotSupportedException { + var clone = (AbstractConcurrentArray) super.clone(); + clone.array = ArrayUtils.copyOfAndExtend(array, size()); + return clone; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java index b9e60430..80822c2f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java @@ -6,46 +6,46 @@ import org.jetbrains.annotations.NotNull; /** - * The concurrent implementation of the array using {@link LockFactory#newReentrantARSWLock()} for {@link - * ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. + * The concurrent implementation of the array using {@link LockFactory#newReentrantARSWLock()} for + * {@link ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. * * @param the array's element type. * @author JavaSaBr */ public class ConcurrentAtomicARSWLockArray extends AbstractConcurrentArray { - private static final long serialVersionUID = -6291504312637658721L; + private static final long serialVersionUID = -6291504312637658721L; - private final @NotNull AsyncReadSyncWriteLock lock; + private final @NotNull AsyncReadSyncWriteLock lock; - public ConcurrentAtomicARSWLockArray(@NotNull Class type) { - this(type, 10); - } + public ConcurrentAtomicARSWLockArray(@NotNull Class type) { + this(type, 10); + } - public ConcurrentAtomicARSWLockArray(@NotNull Class type, int size) { - super(type, size); - this.lock = LockFactory.newAtomicARSWLock(); - } + public ConcurrentAtomicARSWLockArray(@NotNull Class type, int size) { + super(type, size); + this.lock = LockFactory.newAtomicARSWLock(); + } - @Override - public final long readLock() { - lock.asyncLock(); - return 1; - } + @Override + public final long readLock() { + lock.asyncLock(); + return 1; + } - @Override - public void readUnlock(long stamp) { - lock.asyncUnlock(); - } + @Override + public void readUnlock(long stamp) { + lock.asyncUnlock(); + } - @Override - public final long writeLock() { - lock.syncLock(); - return 1; - } + @Override + public final long writeLock() { + lock.syncLock(); + return 1; + } - @Override - public void writeUnlock(long stamp) { - lock.syncUnlock(); - } + @Override + public void writeUnlock(long stamp) { + lock.syncUnlock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java index 7b50e819..3e7b0ec5 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java @@ -14,38 +14,38 @@ */ public class ConcurrentAtomicARSWLockArraySet extends ConcurrentAtomicARSWLockArray { - private static final long serialVersionUID = -3394386864246350866L; - - public ConcurrentAtomicARSWLockArraySet(@NotNull Class type) { - super(type); - } - - public ConcurrentAtomicARSWLockArraySet(@NotNull Class type, int size) { - super(type, size); - } - - @Override - public boolean add(@NotNull E element) { - return !contains(element) && super.add(element); - } - - @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } + private static final long serialVersionUID = -3394386864246350866L; + + public ConcurrentAtomicARSWLockArraySet(@NotNull Class type) { + super(type); + } + + public ConcurrentAtomicARSWLockArraySet(@NotNull Class type, int size) { + super(type, size); + } + + @Override + public boolean add(@NotNull E element) { + return !contains(element) && super.add(element); + } + + @Override + protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + var array = elements.array(); + for (int i = 0, length = elements.size(); i < length; i++) { + E element = array[i]; + if (!contains(element)) { + unsafeAdd(element); + } } - - @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } + } + + @Override + protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + for (E element : elements) { + if (!contains(element)) { + unsafeAdd(element); + } } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java index 3927fd87..1a948dec 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java @@ -7,49 +7,49 @@ import org.jetbrains.annotations.NotNull; /** - * The concurrent implementation of the array using {@link ReentrantReadWriteLock} for {@link - * ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. + * The concurrent implementation of the array using {@link ReentrantReadWriteLock} for + * {@link ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. * * @param the array's element type. * @author JavaSaBr */ public class ConcurrentReentrantRWLockArray extends AbstractConcurrentArray { - private static final long serialVersionUID = -7985171224116955303L; - - private final @NotNull Lock readLock; - private final @NotNull Lock writeLock; - - public ConcurrentReentrantRWLockArray(@NotNull Class type) { - this(type, 10); - } - - public ConcurrentReentrantRWLockArray(@NotNull Class type, int size) { - super(type, size); - var readWriteLock = LockFactory.newReentrantRWLock(); - this.readLock = readWriteLock.readLock(); - this.writeLock = readWriteLock.writeLock(); - } - - @Override - public final long readLock() { - readLock.lock(); - return 1; - } - - @Override - public final void readUnlock(long stamp) { - readLock.unlock(); - } - - @Override - public final long writeLock() { - writeLock.lock(); - return 1; - } - - @Override - public final void writeUnlock(long stamp) { - writeLock.unlock(); - } + private static final long serialVersionUID = -7985171224116955303L; + + private final @NotNull Lock readLock; + private final @NotNull Lock writeLock; + + public ConcurrentReentrantRWLockArray(@NotNull Class type) { + this(type, 10); + } + + public ConcurrentReentrantRWLockArray(@NotNull Class type, int size) { + super(type, size); + var readWriteLock = LockFactory.newReentrantRWLock(); + this.readLock = readWriteLock.readLock(); + this.writeLock = readWriteLock.writeLock(); + } + + @Override + public final long readLock() { + readLock.lock(); + return 1; + } + + @Override + public final void readUnlock(long stamp) { + readLock.unlock(); + } + + @Override + public final long writeLock() { + writeLock.lock(); + return 1; + } + + @Override + public final void writeUnlock(long stamp) { + writeLock.unlock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java index 5b5f2e4d..19cb2dd4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java @@ -6,46 +6,46 @@ import org.jetbrains.annotations.NotNull; /** - * The concurrent implementation of the array without duplications using {@link ReentrantReadWriteLock} for {@link - * ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. + * The concurrent implementation of the array without duplications using {@link ReentrantReadWriteLock} for + * {@link ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. * * @param the array's element type. * @author JavaSaBr */ public class ConcurrentReentrantRWLockArraySet extends ConcurrentReentrantRWLockArray { - private static final long serialVersionUID = -3394386864246350866L; - - public ConcurrentReentrantRWLockArraySet(@NotNull Class type) { - super(type); - } - - public ConcurrentReentrantRWLockArraySet(@NotNull Class type, int size) { - super(type, size); - } - - @Override - public boolean add(@NotNull E element) { - return !contains(element) && super.add(element); - } - - @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } + private static final long serialVersionUID = -3394386864246350866L; + + public ConcurrentReentrantRWLockArraySet(@NotNull Class type) { + super(type); + } + + public ConcurrentReentrantRWLockArraySet(@NotNull Class type, int size) { + super(type, size); + } + + @Override + public boolean add(@NotNull E element) { + return !contains(element) && super.add(element); + } + + @Override + protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + var array = elements.array(); + for (int i = 0, length = elements.size(); i < length; i++) { + E element = array[i]; + if (!contains(element)) { + unsafeAdd(element); + } } - - @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } + } + + @Override + protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + for (E element : elements) { + if (!contains(element)) { + unsafeAdd(element); + } } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java index 4e5a1966..7133be80 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java @@ -14,46 +14,46 @@ */ public class ConcurrentStampedLockArray extends AbstractConcurrentArray { - private static final long serialVersionUID = -6291504312637658721L; - - private final @NotNull StampedLock lock; - - public ConcurrentStampedLockArray(@NotNull Class type) { - this(type, 10); - } - - public ConcurrentStampedLockArray(@NotNull Class type, int size) { - super(type, size); - this.lock = LockFactory.newStampedLock(); - } - - @Override - public final long readLock() { - return lock.readLock(); - } - - @Override - public final long tryOptimisticRead() { - return lock.tryOptimisticRead(); - } - - @Override - public final boolean validate(long stamp) { - return lock.validate(stamp); - } - - @Override - public final void readUnlock(long stamp) { - lock.unlockRead(stamp); - } - - @Override - public final long writeLock() { - return lock.writeLock(); - } - - @Override - public final void writeUnlock(long stamp) { - lock.unlockWrite(stamp); - } + private static final long serialVersionUID = -6291504312637658721L; + + private final @NotNull StampedLock lock; + + public ConcurrentStampedLockArray(@NotNull Class type) { + this(type, 10); + } + + public ConcurrentStampedLockArray(@NotNull Class type, int size) { + super(type, size); + this.lock = LockFactory.newStampedLock(); + } + + @Override + public final long readLock() { + return lock.readLock(); + } + + @Override + public final long tryOptimisticRead() { + return lock.tryOptimisticRead(); + } + + @Override + public final boolean validate(long stamp) { + return lock.validate(stamp); + } + + @Override + public final void readUnlock(long stamp) { + lock.unlockRead(stamp); + } + + @Override + public final long writeLock() { + return lock.writeLock(); + } + + @Override + public final void writeUnlock(long stamp) { + lock.unlockWrite(stamp); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java index 13d1605c..0f84d420 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java @@ -6,46 +6,46 @@ import org.jetbrains.annotations.NotNull; /** - * The concurrent implementation of the array without duplications using {@link StampedLock} for {@link - * ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. + * The concurrent implementation of the array without duplications using {@link StampedLock} for + * {@link ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. * * @param the array's element type. * @author JavaSaBr */ public class ConcurrentStampedLockArraySet extends ConcurrentStampedLockArray { - private static final long serialVersionUID = -6291504312637658721L; - - public ConcurrentStampedLockArraySet(@NotNull Class type) { - this(type, 10); - } - - public ConcurrentStampedLockArraySet(@NotNull Class type, int size) { - super(type, size); - } - - @Override - public boolean add(@NotNull E element) { - return !contains(element) && super.add(element); - } - - @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } + private static final long serialVersionUID = -6291504312637658721L; + + public ConcurrentStampedLockArraySet(@NotNull Class type) { + this(type, 10); + } + + public ConcurrentStampedLockArraySet(@NotNull Class type, int size) { + super(type, size); + } + + @Override + public boolean add(@NotNull E element) { + return !contains(element) && super.add(element); + } + + @Override + protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + var array = elements.array(); + for (int i = 0, length = elements.size(); i < length; i++) { + E element = array[i]; + if (!contains(element)) { + unsafeAdd(element); + } } - - @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } + } + + @Override + protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + for (E element : elements) { + if (!contains(element)) { + unsafeAdd(element); + } } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java index 4517e86b..8564f860 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java @@ -3,7 +3,7 @@ import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; -import javasabr.rlib.common.concurrent.atomic.AtomicReference; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicReference; import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayComparator; @@ -11,265 +11,264 @@ import org.jetbrains.annotations.NotNull; /** - * The implementation of the array which create a new back-end array for each modification. - * Thread-safe. + * The implementation of the array which create a new back-end array for each modification. Thread-safe. * * @param the array's element type. * @author JavaSaBr */ public class CopyOnModifyArray extends AbstractArray { - private static final long serialVersionUID = -8477384427415127978L; + private static final long serialVersionUID = -8477384427415127978L; - @SuppressWarnings("NullableProblems") - protected volatile @NotNull AtomicReference array; + @SuppressWarnings("NullableProblems") + protected volatile @NotNull ReusableAtomicReference array; - public CopyOnModifyArray(@NotNull Class type, int size) { - super(type, size); - } - - @Override - public boolean add(@NotNull E object) { + public CopyOnModifyArray(@NotNull Class type, int size) { + super(type, size); + } - var current = array.get(); - var newArray = ArrayUtils.copyOfAndExtend(current, 1); - newArray[current.length] = object; + @Override + public boolean add(@NotNull E object) { - if (!array.compareAndSet(current, newArray)) { - return add(object); - } + var current = array.get(); + var newArray = ArrayUtils.copyOfAndExtend(current, 1); + newArray[current.length] = object; - return true; + if (!array.compareAndSet(current, newArray)) { + return add(object); } - @Override - public boolean addAll(@NotNull Array elements) { + return true; + } - if (elements.isEmpty()) { - return false; - } + @Override + public boolean addAll(@NotNull Array elements) { - var current = array.get(); - var newArray = ArrayUtils.copyOfAndExtend(current, elements.size()); + if (elements.isEmpty()) { + return false; + } - for (int i = current.length, g = 0; i < newArray.length; i++, g++) { - newArray[i] = elements.get(g); - } + var current = array.get(); + var newArray = ArrayUtils.copyOfAndExtend(current, elements.size()); - if (!array.compareAndSet(current, newArray)) { - return addAll(elements); - } + for (int i = current.length, g = 0; i < newArray.length; i++, g++) { + newArray[i] = elements.get(g); + } - return true; + if (!array.compareAndSet(current, newArray)) { + return addAll(elements); } - @Override - public boolean addAll(@NotNull Collection collection) { + return true; + } - if (collection.isEmpty()) { - return false; - } + @Override + public boolean addAll(@NotNull Collection collection) { - var current = array.get(); - var newArray = ArrayUtils.copyOfAndExtend(current, collection.size()); + if (collection.isEmpty()) { + return false; + } - Iterator iterator = collection.iterator(); + var current = array.get(); + var newArray = ArrayUtils.copyOfAndExtend(current, collection.size()); - for (int i = current.length; i < newArray.length; i++) { - newArray[i] = iterator.next(); - } + Iterator iterator = collection.iterator(); - if (!array.compareAndSet(current, newArray)) { - return addAll(collection); - } - - return true; + for (int i = current.length; i < newArray.length; i++) { + newArray[i] = iterator.next(); } - @Override - public boolean addAll(@NotNull E[] elements) { - - if (elements.length < 1) { - return false; - } + if (!array.compareAndSet(current, newArray)) { + return addAll(collection); + } - var current = array.get(); - var newArray = ArrayUtils.combine(current, elements); + return true; + } - if (!array.compareAndSet(current, newArray)) { - return addAll(elements); - } + @Override + public boolean addAll(@NotNull E[] elements) { - return true; + if (elements.length < 1) { + return false; } - @Override - public final @NotNull E[] array() { - return array.get(); - } + var current = array.get(); + var newArray = ArrayUtils.combine(current, elements); - @Override - public @NotNull E remove(int index) { - throw new UnsupportedOperationException(); + if (!array.compareAndSet(current, newArray)) { + return addAll(elements); } - @Override - public boolean removeAll(@NotNull Array target) { + return true; + } - if (target.isEmpty()) { - return false; - } + @Override + public final @NotNull E[] array() { + return array.get(); + } - var current = array(); - var modifiable = ArrayFactory.asArray(current); + @Override + public @NotNull E remove(int index) { + throw new UnsupportedOperationException(); + } - if(!modifiable.removeAll(target)) { - return false; - } + @Override + public boolean removeAll(@NotNull Array target) { - var newArray = modifiable.toArray(); + if (target.isEmpty()) { + return false; + } - if (!array.compareAndSet(current, newArray)) { - return removeAll(target); - } + var current = array(); + var modifiable = ArrayFactory.asArray(current); - return true; + if (!modifiable.removeAll(target)) { + return false; } - @Override - public boolean removeAll(@NotNull Collection target) { + var newArray = modifiable.toArray(); - if (target.isEmpty()) { - return false; - } + if (!array.compareAndSet(current, newArray)) { + return removeAll(target); + } - var current = array(); - var modifiable = ArrayFactory.asArray(current); + return true; + } - if(!modifiable.removeAll(target)) { - return false; - } + @Override + public boolean removeAll(@NotNull Collection target) { - var newArray = modifiable.toArray(); + if (target.isEmpty()) { + return false; + } - if (!array.compareAndSet(current, newArray)) { - return removeAll(target); - } + var current = array(); + var modifiable = ArrayFactory.asArray(current); - return true; + if (!modifiable.removeAll(target)) { + return false; } - @Override - public boolean remove(@NotNull Object object) { + var newArray = modifiable.toArray(); - var current = array.get(); - var index = ArrayUtils.indexOf(current, object); + if (!array.compareAndSet(current, newArray)) { + return removeAll(target); + } - if (index == -1) { - return false; - } + return true; + } - var newArray = ArrayUtils.create(current, current.length - 1); + @Override + public boolean remove(@NotNull Object object) { - for (int i = 0, j = 0; i < current.length; i++, j++) { + var current = array.get(); + var index = ArrayUtils.indexOf(current, object); - if (i == index) { - i++; - if (i >= current.length) { - break; - } - } + if (index == -1) { + return false; + } - newArray[j] = current[i]; - } + var newArray = ArrayUtils.create(current, current.length - 1); + + for (int i = 0, j = 0; i < current.length; i++, j++) { - if (!array.compareAndSet(current, newArray)) { - return fastRemove(object); + if (i == index) { + i++; + if (i >= current.length) { + break; } + } - return true; + newArray[j] = current[i]; } - @Override - public boolean fastRemove(@NotNull Object object) { - return remove(object); + if (!array.compareAndSet(current, newArray)) { + return fastRemove(object); } - @Override - public @NotNull E fastRemove(int index) { - throw new UnsupportedOperationException(); - } + return true; + } - @Override - public void clear() { + @Override + public boolean fastRemove(@NotNull Object object) { + return remove(object); + } - var current = array.get(); + @Override + public @NotNull E fastRemove(int index) { + throw new UnsupportedOperationException(); + } - if (current.length < 1) { - return; - } + @Override + public void clear() { - var newArray = ArrayUtils.create(current, 0); + var current = array.get(); - if (!array.compareAndSet(current, newArray)) { - clear(); - } + if (current.length < 1) { + return; } - @Override - public final @NotNull E get(int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } + var newArray = ArrayUtils.create(current, 0); - return array.get()[index]; + if (!array.compareAndSet(current, newArray)) { + clear(); } + } - @Override - public void replace(int index, @NotNull E element) { - throw new UnsupportedOperationException(); + @Override + public final @NotNull E get(int index) { + + if (index < 0 || index >= size()) { + throw new NoSuchElementException(); } - @Override - protected final void setArray(E @NotNull [] array) { + return array.get()[index]; + } - //noinspection ConstantConditions - if (this.array == null) { - this.array = new AtomicReference<>(); - } + @Override + public void replace(int index, @NotNull E element) { + throw new UnsupportedOperationException(); + } - this.array.set(array); - } + @Override + protected final void setArray(E @NotNull [] array) { - @Override - protected final void setSize(int size) { + //noinspection ConstantConditions + if (this.array == null) { + this.array = new ReusableAtomicReference<>(); } - @Override - public final int size() { - return array().length; - } + this.array.set(array); + } - @Override - public @NotNull Array sort(@NotNull ArrayComparator comparator) { + @Override + protected final void setSize(int size) { + } - var current = array(); - var newArray = ArrayUtils.copyOfAndExtend(current, 0); + @Override + public final int size() { + return array().length; + } - ArrayUtils.sort(newArray, 0, newArray.length, comparator); + @Override + public @NotNull Array sort(@NotNull ArrayComparator comparator) { - if (!array.compareAndSet(current, newArray)) { - return sort(comparator); - } + var current = array(); + var newArray = ArrayUtils.copyOfAndExtend(current, 0); - return this; - } + ArrayUtils.sort(newArray, 0, newArray.length, comparator); - @Override - public @NotNull CopyOnModifyArray clone() throws CloneNotSupportedException { - var clone = (CopyOnModifyArray) super.clone(); - clone.array = new AtomicReference<>(ArrayUtils.copyOf(array())); - return clone; + if (!array.compareAndSet(current, newArray)) { + return sort(comparator); } + + return this; + } + + @Override + public @NotNull CopyOnModifyArray clone() throws CloneNotSupportedException { + var clone = (CopyOnModifyArray) super.clone(); + clone.array = new ReusableAtomicReference<>(ArrayUtils.copyOf(array())); + return clone; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java index 9cbc10f5..ef776179 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java @@ -12,56 +12,53 @@ */ public class DefaultArrayIterator implements ArrayIterator { - /** - * The array for iteration. - */ - private final @NotNull Array array; + /** + * The array for iteration. + */ + private final @NotNull Array array; - /** - * The unsafe array for directly access. - */ - private final @NotNull E[] unsafeArray; + /** + * The unsafe array for directly access. + */ + private final @NotNull E[] unsafeArray; - /** - * The current position in the array. - */ - private int ordinal; + /** + * The current position in the array. + */ + private int ordinal; - public DefaultArrayIterator(@NotNull Array array) { - this.array = array; - this.unsafeArray = array.array(); - } + public DefaultArrayIterator(@NotNull Array array) { + this.array = array; + this.unsafeArray = array.array(); + } - @Override - public void fastRemove() { - array.fastRemove(--ordinal); - } + @Override + public void fastRemove() { + array.fastRemove(--ordinal); + } - @Override - public boolean hasNext() { - return ordinal < array.size(); - } + @Override + public boolean hasNext() { + return ordinal < array.size(); + } - @Override - public int index() { - return ordinal - 1; - } + @Override + public int index() { + return ordinal - 1; + } - @Override - public @NotNull E next() { - return ordinal >= unsafeArray.length ? null : unsafeArray[ordinal++]; - } + @Override + public @NotNull E next() { + return ordinal >= unsafeArray.length ? null : unsafeArray[ordinal++]; + } - @Override - public void remove() { - array.remove(--ordinal); - } + @Override + public void remove() { + array.remove(--ordinal); + } - @Override - public String toString() { - return "ArrayIteratorImpl{" + - "array=" + array + - ", ordinal=" + ordinal + - '}'; - } + @Override + public String toString() { + return "ArrayIteratorImpl{" + "array=" + array + ", ordinal=" + ordinal + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java index 0db54e25..21ce823d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java @@ -16,242 +16,241 @@ */ public class DefaultIntegerArray implements MutableIntegerArray { - protected int[] array; - protected int size; + protected int[] array; + protected int size; - public DefaultIntegerArray() { - this(10); - } + public DefaultIntegerArray() { + this(10); + } - public DefaultIntegerArray(int size) { - this.array = new int[size]; - this.size = 0; - } + public DefaultIntegerArray(int size) { + this.array = new int[size]; + this.size = 0; + } - public DefaultIntegerArray(int @NotNull [] numbers) { - this.array = numbers; - this.size = numbers.length; - } + public DefaultIntegerArray(int @NotNull [] numbers) { + this.array = numbers; + this.size = numbers.length; + } - @Override - public @NotNull DefaultIntegerArray add(int number) { + @Override + public @NotNull DefaultIntegerArray add(int number) { - if (size == array.length) { - array = ArrayUtils.copyOf(array, Math.max(array.length >> 1, 1)); - } - - array[size++] = number; - - return this; + if (size == array.length) { + array = ArrayUtils.copyOf(array, Math.max(array.length >> 1, 1)); } - @Override - public @NotNull DefaultIntegerArray addAll(int @NotNull [] numbers) { + array[size++] = number; - if (numbers.length < 1) { - return this; - } + return this; + } - var current = array.length; - var diff = size() + numbers.length - current; + @Override + public @NotNull DefaultIntegerArray addAll(int @NotNull [] numbers) { - if (diff > 0) { - array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); - } + if (numbers.length < 1) { + return this; + } - for (var value : numbers) { - add(value); - } + var current = array.length; + var diff = size() + numbers.length - current; - return this; + if (diff > 0) { + array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); } - @Override - public final @NotNull DefaultIntegerArray addAll(@NotNull IntegerArray numbers) { - - if (numbers.isEmpty()) { - return this; - } + for (var value : numbers) { + add(value); + } - var current = array.length; - var diff = size() + numbers.size() - current; + return this; + } - if (diff > 0) { - array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); - } + @Override + public final @NotNull DefaultIntegerArray addAll(@NotNull IntegerArray numbers) { - var array = numbers.array(); + if (numbers.isEmpty()) { + return this; + } - for (int i = 0, length = numbers.size(); i < length; i++) { - add(array[i]); - } + var current = array.length; + var diff = size() + numbers.size() - current; - return this; + if (diff > 0) { + array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); } - @Override - public final @NotNull int[] array() { - return array; - } + var array = numbers.array(); - @Override - public final @NotNull DefaultIntegerArray clear() { - size = 0; - return this; + for (int i = 0, length = numbers.size(); i < length; i++) { + add(array[i]); } - @Override - public final boolean fastRemoveByIndex(int index) { - - if (index < 0 || size < 1 || index >= size) { - return false; - } + return this; + } - var array = array(); + @Override + public final @NotNull int[] array() { + return array; + } - size -= 1; + @Override + public final @NotNull DefaultIntegerArray clear() { + size = 0; + return this; + } - array[index] = array[size]; - array[size] = 0; + @Override + public final boolean fastRemoveByIndex(int index) { - return true; + if (index < 0 || size < 1 || index >= size) { + return false; } - @Override - public int first() { - if (isEmpty()) { - throw new IllegalStateException("Array is empty."); - } else { - return array[0]; - } - } + var array = array(); - @Override - public final int get(int index) { - if (index >= size) { - throw new IndexOutOfBoundsException(index); - } else { - return array[index]; - } - } + size -= 1; - @Override - public final @NotNull ArrayIterator iterator() { - return new DefaultIterator(); - } + array[index] = array[size]; + array[size] = 0; - @Override - public final int last() { - if (isEmpty()) { - throw new IllegalStateException("Array is empty."); - } else { - return array.length < 1 ? -1 : array[array.length - 1]; - } - } + return true; + } - @Override - public final int poll() { - var val = first(); - return removeByIndex(0) ? val : -1; + @Override + public int first() { + if (isEmpty()) { + throw new IllegalStateException("Array is empty."); + } else { + return array[0]; } - - @Override - public final int pop() { - var last = last(); - return fastRemoveByIndex(size - 1) ? last : -1; + } + + @Override + public final int get(int index) { + if (index >= size) { + throw new IndexOutOfBoundsException(index); + } else { + return array[index]; + } + } + + @Override + public final @NotNull ArrayIterator iterator() { + return new DefaultIterator(); + } + + @Override + public final int last() { + if (isEmpty()) { + throw new IllegalStateException("Array is empty."); + } else { + return array.length < 1 ? -1 : array[array.length - 1]; + } + } + + @Override + public final int poll() { + var val = first(); + return removeByIndex(0) ? val : -1; + } + + @Override + public final int pop() { + var last = last(); + return fastRemoveByIndex(size - 1) ? last : -1; + } + + @Override + public final int size() { + return size; + } + + @Override + public final boolean removeByIndex(int index) { + + if (index < 0 || size < 1) { + return false; } - @Override - public final int size() { - return size; + var array = array(); + var numMoved = size - index - 1; + + if (numMoved > 0) { + System.arraycopy(array, index + 1, array, index, numMoved); } - @Override - public final boolean removeByIndex(int index) { + array[--size] = 0; + return true; + } - if (index < 0 || size < 1) { - return false; - } + @Override + public final @NotNull DefaultIntegerArray sort() { + ArrayUtils.sort(array, 0, size); + return this; + } - var array = array(); - var numMoved = size - index - 1; + @Override + public final @NotNull DefaultIntegerArray trimToSize() { - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } + var array = array(); - array[--size] = 0; - return true; + if (size == array.length) { + return this; } - @Override - public final @NotNull DefaultIntegerArray sort() { - ArrayUtils.sort(array, 0, size); - return this; - } + this.array = ArrayUtils.copyOfRange(array, 0, size); + return this; + } - @Override - public final @NotNull DefaultIntegerArray trimToSize() { + @Override + public boolean equals(@Nullable Object another) { - var array = array(); + if (this == another) { + return true; + } else if (!(another instanceof IntegerArray)) { + return false; + } - if (size == array.length) { - return this; - } + var array = (IntegerArray) another; - this.array = ArrayUtils.copyOfRange(array, 0, size); - return this; - } + return size == array.size() && Arrays.equals(this.array, 0, size, array.array(), 0, size); + } - @Override - public boolean equals(@Nullable Object another) { + @Override + public int hashCode() { + var result = Objects.hash(size); + result = 31 * result + Arrays.hashCode(array); + return result; + } - if (this == another) { - return true; - } else if (!(another instanceof IntegerArray)) { - return false; - } + private final class DefaultIterator implements ArrayIterator { - var array = (IntegerArray) another; + private int ordinal = 0; - return size == array.size() && - Arrays.equals(this.array, 0, size, array.array(), 0, size); + @Override + public void fastRemove() { + DefaultIntegerArray.this.fastRemove(--ordinal); } @Override - public int hashCode() { - var result = Objects.hash(size); - result = 31 * result + Arrays.hashCode(array); - return result; + public boolean hasNext() { + return ordinal < size; } - private final class DefaultIterator implements ArrayIterator { - - private int ordinal = 0; - - @Override - public void fastRemove() { - DefaultIntegerArray.this.fastRemove(--ordinal); - } - - @Override - public boolean hasNext() { - return ordinal < size; - } - - @Override - public int index() { - return ordinal - 1; - } + @Override + public int index() { + return ordinal - 1; + } - @Override - public @NotNull Integer next() { - return array[ordinal++]; - } + @Override + public @NotNull Integer next() { + return array[ordinal++]; + } - @Override - public void remove() { - DefaultIntegerArray.this.fastRemove(--ordinal); - } + @Override + public void remove() { + DefaultIntegerArray.this.fastRemove(--ordinal); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java index 45369f29..33023f0b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java @@ -18,261 +18,263 @@ */ public class FastArray extends AbstractArray implements UnsafeArray { - private static final long serialVersionUID = -8477384427415127978L; + private static final long serialVersionUID = -8477384427415127978L; - /** - * The unsafe array. - */ - @SuppressWarnings("NullableProblems") - protected E @NotNull [] array; + /** + * The unsafe array. + */ + @SuppressWarnings("NullableProblems") + protected E @NotNull [] array; - /** - * The current size of this array. - */ - protected int size; + /** + * The current size of this array. + */ + protected int size; - public FastArray(@NotNull Class type) { - super(type); - } - - public FastArray(@NotNull Class type, final int size) { - super(type, size); - } + public FastArray(@NotNull Class type) { + super(type); + } - public FastArray(@NotNull E[] array) { - super(array); - } + public FastArray(@NotNull Class type, final int size) { + super(type, size); + } - @Override - public boolean add(@NotNull E object) { + public FastArray(@NotNull E[] array) { + super(array); + } - if (size == array.length) { - array = ArrayUtils.copyOfAndExtend(array, max(array.length >> 1, 1)); - } + @Override + public boolean add(@NotNull E object) { - return unsafeAdd(object); + if (size == array.length) { + array = ArrayUtils.copyOfAndExtend(array, max(array.length >> 1, 1)); } - @Override - public boolean addAll(@NotNull Array elements) { + return unsafeAdd(object); + } - if (elements.isEmpty()) { - return false; - } + @Override + public boolean addAll(@NotNull Array elements) { - int current = array.length; - int selfSize = size(); - int targetSize = elements.size(); - int diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; + if (elements.isEmpty()) { + return false; } - @Override - public boolean addAll(@NotNull Collection collection) { - - if (collection.isEmpty()) { - return false; - } + int current = array.length; + int selfSize = size(); + int targetSize = elements.size(); + int diff = selfSize + targetSize - current; - int current = array.length; - int selfSize = size(); - int targetSize = collection.size(); - int diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - for (E element : collection) { - unsafeAdd(element); - } - - return true; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); } - @Override - public boolean addAll(@NotNull E[] elements) { + processAdd(elements, selfSize, targetSize); + return true; + } - if (elements.length < 1) { - return false; - } + @Override + public boolean addAll(@NotNull Collection collection) { - int current = array.length; - int selfSize = size(); - int targetSize = elements.length; - int diff = selfSize + targetSize - current; + if (collection.isEmpty()) { + return false; + } - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } + int current = array.length; + int selfSize = size(); + int targetSize = collection.size(); + int diff = selfSize + targetSize - current; - processAdd(elements, selfSize, targetSize); - return true; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); } - @Override - public final @NotNull E[] array() { - return array; + for (E element : collection) { + unsafeAdd(element); } - @Override - public void prepareForSize(int size) { + return true; + } - int current = array.length; - int selfSize = size(); - int diff = selfSize + size - current; + @Override + public boolean addAll(@NotNull E[] elements) { - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } + if (elements.length < 1) { + return false; } - @Override - public @NotNull E fastRemove(int index) { - - if (index < 0 || index >= size) { - throw new NoSuchElementException(); - } - - size -= 1; + int current = array.length; + int selfSize = size(); + int targetSize = elements.length; + int diff = selfSize + targetSize - current; - E old = array[index]; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); + } - array[index] = array[size]; - array[size] = null; + processAdd(elements, selfSize, targetSize); + return true; + } - return old; - } + @Override + public final @NotNull E[] array() { + return array; + } - @Override - public final @NotNull E get(int index) { + @Override + public void prepareForSize(int size) { - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } + int current = array.length; + int selfSize = size(); + int diff = selfSize + size - current; - return array[index]; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); } + } - @Override - public final @NotNull ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } + @Override + public @NotNull E fastRemove(int index) { - /** - * The process of adding the array. - * - * @param elements the elements. - * @param selfSize the self size. - * @param targetSize the target size. - */ - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { - System.arraycopy(elements.array(), 0, array, selfSize, targetSize); - size = selfSize + targetSize; + if (index < 0 || index >= size) { + throw new NoSuchElementException(); } - /** - * The process of adding the array. - * - * @param elements the elements. - * @param selfSize the self size. - * @param targetSize the target size. - */ - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { - System.arraycopy(elements, 0, array, selfSize, targetSize); - size = selfSize + targetSize; - } + size -= 1; - @Override - public void replace(int index, @NotNull E element) { + E old = array[index]; - if (index < 0 || index >= size) { - throw new ArrayIndexOutOfBoundsException(); - } + array[index] = array[size]; + array[size] = null; - array[index] = element; - } + return old; + } - @Override - protected final void setArray(E @NotNull [] array) { - this.array = array; - } + @Override + public final @NotNull E get(int index) { - @Override - protected final void setSize(int size) { - this.size = size; + if (index < 0 || index >= size()) { + throw new NoSuchElementException(); } - @Override - public final int size() { - return size; + return array[index]; + } + + @Override + public final @NotNull ArrayIterator iterator() { + return new DefaultArrayIterator<>(this); + } + + /** + * The process of adding the array. + * + * @param elements the elements. + * @param selfSize the self size. + * @param targetSize the target size. + */ + protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + System.arraycopy(elements.array(), 0, array, selfSize, targetSize); + size = selfSize + targetSize; + } + + /** + * The process of adding the array. + * + * @param elements the elements. + * @param selfSize the self size. + * @param targetSize the target size. + */ + protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + System.arraycopy(elements, 0, array, selfSize, targetSize); + size = selfSize + targetSize; + } + + @Override + public void replace(int index, @NotNull E element) { + + if (index < 0 || index >= size) { + throw new ArrayIndexOutOfBoundsException(); } - @Override - public @NotNull E remove(int index) { + array[index] = element; + } - if (index < 0 || index >= size) { - throw new NoSuchElementException(); - } + @Override + protected final void setArray(E @NotNull [] array) { + this.array = array; + } - int numMoved = size - index - 1; - E old = array[index]; + @Override + protected final void setSize(int size) { + this.size = size; + } - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } + @Override + public final int size() { + return size; + } - size -= 1; - array[size] = null; + @Override + public @NotNull E remove(int index) { - return old; + if (index < 0 || index >= size) { + throw new NoSuchElementException(); } - @Override - public @NotNull FastArray trimToSize() { + int numMoved = size - index - 1; + E old = array[index]; - if (size == array.length) { - return this; - } + if (numMoved > 0) { + System.arraycopy(array, index + 1, array, index, numMoved); + } - array = ArrayUtils.copyOfRange(array, 0, size); + size -= 1; + array[size] = null; - return this; - } + return old; + } - @Override - public boolean unsafeAdd(@NotNull E object) { - array[size++] = object; - return true; - } + @Override + public @NotNull FastArray trimToSize() { - @Override - public void unsafeSet(int index, @NotNull E element) { - if (array[index] != null) size -= 1; - array[index] = element; - size += 1; + if (size == array.length) { + return this; } - @Override - public E unsafeGet(int index) { - return array[index]; - } + array = ArrayUtils.copyOfRange(array, 0, size); - @Override - public @NotNull UnsafeArray asUnsafe() { - return this; - } + return this; + } + + @Override + public boolean unsafeAdd(@NotNull E object) { + array[size++] = object; + return true; + } - @Override - public @NotNull FastArray clone() throws CloneNotSupportedException { - var clone = (FastArray) super.clone(); - clone.array = ArrayUtils.copyOfAndExtend(array, size()); - return clone; + @Override + public void unsafeSet(int index, @NotNull E element) { + if (array[index] != null) { + size -= 1; } + array[index] = element; + size += 1; + } + + @Override + public E unsafeGet(int index) { + return array[index]; + } + + @Override + public @NotNull UnsafeArray asUnsafe() { + return this; + } + + @Override + public @NotNull FastArray clone() throws CloneNotSupportedException { + var clone = (FastArray) super.clone(); + clone.array = ArrayUtils.copyOfAndExtend(array, size()); + return clone; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java index ead1f08b..002779e5 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java @@ -11,38 +11,38 @@ */ public class FastArraySet extends FastArray { - private static final long serialVersionUID = 1L; - - public FastArraySet(@NotNull Class type) { - super(type); - } - - public FastArraySet(@NotNull Class type, int size) { - super(type, size); - } - - @Override - public boolean add(@NotNull E element) { - return !contains(element) && super.add(element); - } - - @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } + private static final long serialVersionUID = 1L; + + public FastArraySet(@NotNull Class type) { + super(type); + } + + public FastArraySet(@NotNull Class type, int size) { + super(type, size); + } + + @Override + public boolean add(@NotNull E element) { + return !contains(element) && super.add(element); + } + + @Override + protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + var array = elements.array(); + for (int i = 0, length = elements.size(); i < length; i++) { + E element = array[i]; + if (!contains(element)) { + unsafeAdd(element); + } } - - @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } + } + + @Override + protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + for (E element : elements) { + if (!contains(element)) { + unsafeAdd(element); + } } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java index a917bf85..07c979b7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java @@ -11,249 +11,259 @@ */ public class FastLongArray implements LongArray { - /** - * Массив элементов. - */ - protected long[] array; - - /** - * Кол-во элементов в колекции. - */ - protected int size; - - /** - * Instantiates a new Fast long array. - */ - public FastLongArray() { - this(10); + /** + * Массив элементов. + */ + protected long[] array; + + /** + * Кол-во элементов в колекции. + */ + protected int size; + + /** + * Instantiates a new Fast long array. + */ + public FastLongArray() { + this(10); + } + + /** + * Instantiates a new Fast long array. + * + * @param size the size + */ + public FastLongArray(final int size) { + this.array = new long[size]; + this.size = 0; + } + + @Override + public FastLongArray add(final long element) { + + if (size == array.length) { + array = ArrayUtils.copyOf(array, Math.max(array.length >> 1, 1)); } - /** - * Instantiates a new Fast long array. - * - * @param size the size - */ - public FastLongArray(final int size) { - this.array = new long[size]; - this.size = 0; - } + array[size++] = element; + return this; + } - @Override - public FastLongArray add(final long element) { + @Override + public final FastLongArray addAll(final long[] elements) { + if (elements == null || elements.length < 1) { + return this; + } - if (size == array.length) { - array = ArrayUtils.copyOf(array, Math.max(array.length >> 1, 1)); - } + final int current = array.length; + final int diff = size() + elements.length - current; - array[size++] = element; - return this; + if (diff > 0) { + array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); } - @Override - public final FastLongArray addAll(final long[] elements) { - if (elements == null || elements.length < 1) return this; + for (final long element : elements) { + add(element); + } - final int current = array.length; - final int diff = size() + elements.length - current; + return this; + } - if (diff > 0) { - array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); - } + @Override + public final FastLongArray addAll(final LongArray elements) { + if (elements == null || elements.isEmpty()) { + return this; + } - for (final long element : elements) { - add(element); - } + final int current = array.length; + final int diff = size() + elements.size() - current; - return this; + if (diff > 0) { + array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); } - @Override - public final FastLongArray addAll(final LongArray elements) { - if (elements == null || elements.isEmpty()) return this; + final long[] array = elements.array(); - final int current = array.length; - final int diff = size() + elements.size() - current; + for (int i = 0, length = elements.size(); i < length; i++) { + add(array[i]); + } - if (diff > 0) { - array = ArrayUtils.copyOf(array, Math.max(current >> 1, diff)); - } + return this; + } - final long[] array = elements.array(); + @Override + public final long[] array() { + return array; + } - for (int i = 0, length = elements.size(); i < length; i++) { - add(array[i]); - } + @Override + public final FastLongArray clear() { + size = 0; + return this; + } - return this; - } + @Override + public final boolean fastRemove(final int index) { - @Override - public final long[] array() { - return array; + if (index < 0 || size < 1 || index >= size) { + return false; } - @Override - public final FastLongArray clear() { - size = 0; - return this; - } + final long[] array = array(); - @Override - public final boolean fastRemove(final int index) { + size -= 1; - if (index < 0 || size < 1 || index >= size) { - return false; - } + array[index] = array[size]; + array[size] = 0; - final long[] array = array(); + return true; + } - size -= 1; + @Override + public final long first() { + return size < 1 ? -1 : array[0]; + } - array[index] = array[size]; - array[size] = 0; + @Override + public final long get(final int index) { + return array[index]; + } - return true; - } + @Override + public final int indexOf(final long element) { - @Override - public final long first() { - return size < 1 ? -1 : array[0]; - } + final long[] array = array(); - @Override - public final long get(final int index) { - return array[index]; + for (int i = 0, length = size; i < length; i++) { + final long val = array[i]; + if (element == val) { + return i; + } } - @Override - public final int indexOf(final long element) { + return -1; + } - final long[] array = array(); + @Override + public final boolean isEmpty() { + return size < 1; + } - for (int i = 0, length = size; i < length; i++) { - final long val = array[i]; - if (element == val) return i; - } + @Override + public final ArrayIterator iterator() { + return new FastIterator(); + } - return -1; + @Override + public final long last() { + if (size < 1) { + return 0; } - - @Override - public final boolean isEmpty() { - return size < 1; + return array[size - 1]; + } + + @Override + public final long poll() { + final long val = first(); + return slowRemove(0) ? val : -1; + } + + @Override + public final long pop() { + final long last = last(); + return fastRemove(size - 1) ? last : -1; + } + + @Override + public final int size() { + return size; + } + + @Override + public final boolean slowRemove(final int index) { + if (index < 0 || size < 1) { + return false; } - @Override - public final ArrayIterator iterator() { - return new FastIterator(); - } + final long[] array = array(); + final int numMoved = size - index - 1; - @Override - public final long last() { - if (size < 1) return 0; - return array[size - 1]; + if (numMoved > 0) { + System.arraycopy(array, index + 1, array, index, numMoved); } - @Override - public final long poll() { - final long val = first(); - return slowRemove(0) ? val : -1; - } + size -= 1; + array[size] = 0; - @Override - public final long pop() { - final long last = last(); - return fastRemove(size - 1) ? last : -1; - } + return true; + } - @Override - public final int size() { - return size; - } + @Override + public final FastLongArray sort() { + ArrayUtils.sort(array, 0, size); + return this; + } - @Override - public final boolean slowRemove(final int index) { - if (index < 0 || size < 1) return false; + @Override + public String toString() { + return ArrayUtils.toString(this); + } + + @Override + public final FastLongArray trimToSize() { - final long[] array = array(); - final int numMoved = size - index - 1; + long[] array = array(); - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } + if (size == array.length) { + return this; + } - size -= 1; - array[size] = 0; + this.array = ArrayUtils.copyOfRange(array, 0, size); + return this; + } - return true; + /** + * Быстрый итератор массива. + * + * @author JavaSaBr + */ + private final class FastIterator implements ArrayIterator { + + /** + * текущая позиция в массиве + */ + private int ordinal; + + /** + * Instantiates a new Fast iterator. + */ + public FastIterator() { + ordinal = 0; } @Override - public final FastLongArray sort() { - ArrayUtils.sort(array, 0, size); - return this; + public void fastRemove() { + FastLongArray.this.fastRemove(--ordinal); } @Override - public String toString() { - return ArrayUtils.toString(this); + public boolean hasNext() { + return ordinal < size; } @Override - public final FastLongArray trimToSize() { - - long[] array = array(); - - if (size == array.length) { - return this; - } + public int index() { + return ordinal - 1; + } - this.array = ArrayUtils.copyOfRange(array, 0, size); - return this; + @Override + public Long next() { + return array[ordinal++]; } - /** - * Быстрый итератор массива. - * - * @author JavaSaBr - */ - private final class FastIterator implements ArrayIterator { - - /** - * текущая позиция в массиве - */ - private int ordinal; - - /** - * Instantiates a new Fast iterator. - */ - public FastIterator() { - ordinal = 0; - } - - @Override - public void fastRemove() { - FastLongArray.this.fastRemove(--ordinal); - } - - @Override - public boolean hasNext() { - return ordinal < size; - } - - @Override - public int index() { - return ordinal - 1; - } - - @Override - public Long next() { - return array[ordinal++]; - } - - @Override - public void remove() { - FastLongArray.this.fastRemove(--ordinal); - } + @Override + public void remove() { + FastLongArray.this.fastRemove(--ordinal); } + } } \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java index 028e50c4..80e378a7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java @@ -17,107 +17,107 @@ */ public final class ReadOnlyFastArray extends FastArray implements ReadOnlyArray { - public ReadOnlyFastArray(@NotNull E[] array) { - super(array); - } - - @Override - public void apply(@NotNull Function function) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean add(@NotNull E object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean addAll(@NotNull Collection collection) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean fastRemove(@NotNull Object object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public @NotNull E remove(int index) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean addAll(@NotNull Array elements) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean addAll(@NotNull E[] elements) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public @NotNull E fastRemove(int index) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean unsafeAdd(@NotNull E object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public E unsafeGet(int index) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public void unsafeSet(int index, @NotNull E element) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public void replace(int index, @NotNull E element) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public void clear() { - throw new IllegalStateException("This array is read only."); - } - - @Override - public @NotNull Array sort(@NotNull ArrayComparator comparator) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean remove(@Nullable Object object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean removeAll(@NotNull Array target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean removeAll(@NotNull Collection target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean retainAll(@NotNull Array target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean retainAll(@NotNull Collection target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean removeIf(@NotNull Predicate filter) { - throw new IllegalStateException("This array is read only."); - } + public ReadOnlyFastArray(@NotNull E[] array) { + super(array); + } + + @Override + public void apply(@NotNull Function function) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean add(@NotNull E object) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean addAll(@NotNull Collection collection) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean fastRemove(@NotNull Object object) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public @NotNull E remove(int index) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean addAll(@NotNull Array elements) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean addAll(@NotNull E[] elements) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public @NotNull E fastRemove(int index) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean unsafeAdd(@NotNull E object) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public E unsafeGet(int index) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public void unsafeSet(int index, @NotNull E element) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public void replace(int index, @NotNull E element) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public void clear() { + throw new IllegalStateException("This array is read only."); + } + + @Override + public @NotNull Array sort(@NotNull ArrayComparator comparator) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean remove(@Nullable Object object) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean removeAll(@NotNull Array target) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean removeAll(@NotNull Collection target) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean retainAll(@NotNull Array target) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean retainAll(@NotNull Collection target) { + throw new IllegalStateException("This array is read only."); + } + + @Override + public boolean removeIf(@NotNull Predicate filter) { + throw new IllegalStateException("This array is read only."); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java index 47987911..36d36087 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java @@ -14,100 +14,99 @@ */ public class ReadOnlyIntegerArray implements IntegerArray { - protected final int[] array; - - public ReadOnlyIntegerArray(int @NotNull [] array) { - this.array = array; + protected final int[] array; + + public ReadOnlyIntegerArray(int @NotNull [] array) { + this.array = array; + } + + @Override + public final @NotNull int[] array() { + return array; + } + + @Override + public int first() { + if (isEmpty()) { + throw new IllegalStateException("Array is empty."); + } else { + return array[0]; } - - @Override - public final @NotNull int[] array() { - return array; + } + + @Override + public final int get(int index) { + return array[index]; + } + + @Override + public final @NotNull ArrayIterator iterator() { + return new ReadOnlyIterator(); + } + + @Override + public final int last() { + if (isEmpty()) { + throw new IllegalStateException("Array is empty."); + } else { + return array.length < 1 ? -1 : array[array.length - 1]; } + } - @Override - public int first() { - if (isEmpty()) { - throw new IllegalStateException("Array is empty."); - } else { - return array[0]; - } - } + @Override + public final int size() { + return array.length; + } - @Override - public final int get(int index) { - return array[index]; - } + @Override + public boolean equals(@Nullable Object another) { - @Override - public final @NotNull ArrayIterator iterator() { - return new ReadOnlyIterator(); + if (this == another) { + return true; + } else if (!(another instanceof IntegerArray)) { + return false; } - @Override - public final int last() { - if (isEmpty()) { - throw new IllegalStateException("Array is empty."); - } else { - return array.length < 1 ? -1 : array[array.length - 1]; - } - } + var array = (IntegerArray) another; + var size = this.array.length; - @Override - public final int size() { - return array.length; - } + return size == array.size() && Arrays.equals(this.array, 0, size, array.array(), 0, size); + } - @Override - public boolean equals(@Nullable Object another) { + @Override + public int hashCode() { + var result = Objects.hash(array.length); + result = 31 * result + Arrays.hashCode(array); + return result; + } - if (this == another) { - return true; - } else if (!(another instanceof IntegerArray)) { - return false; - } + private final class ReadOnlyIterator implements ArrayIterator { - var array = (IntegerArray) another; - var size = this.array.length; + private int ordinal = 0; - return size == array.size() && - Arrays.equals(this.array, 0, size, array.array(), 0, size); + @Override + public void fastRemove() { + throw new UnsupportedOperationException(); } @Override - public int hashCode() { - var result = Objects.hash(array.length); - result = 31 * result + Arrays.hashCode(array); - return result; + public boolean hasNext() { + return ordinal < array.length; } - private final class ReadOnlyIterator implements ArrayIterator { - - private int ordinal = 0; - - @Override - public void fastRemove() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean hasNext() { - return ordinal < array.length; - } - - @Override - public int index() { - return ordinal - 1; - } + @Override + public int index() { + return ordinal - 1; + } - @Override - public @NotNull Integer next() { - return array[ordinal++]; - } + @Override + public @NotNull Integer next() { + return array[ordinal++]; + } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java index 7ab7a183..8113d72a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java @@ -12,74 +12,74 @@ */ public class SortedFastArray> extends FastArray { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public SortedFastArray(@NotNull Class type) { - super(type); - } - - public SortedFastArray(@NotNull Class type, int size) { - super(type, size); - } + public SortedFastArray(@NotNull Class type) { + super(type); + } - @Override - public boolean add(@NotNull E element) { + public SortedFastArray(@NotNull Class type, int size) { + super(type, size); + } - if (size == array.length) { - array = ArrayUtils.copyOfAndExtend(array, array.length * 3 / 2 + 1); - } + @Override + public boolean add(@NotNull E element) { - return unsafeAdd(element); + if (size == array.length) { + array = ArrayUtils.copyOfAndExtend(array, array.length * 3 / 2 + 1); } - @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } + return unsafeAdd(element); + } + + @Override + protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + var array = elements.array(); + for (int i = 0, length = elements.size(); i < length; i++) { + E element = array[i]; + if (!contains(element)) { + unsafeAdd(element); + } } - - @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } + } + + @Override + protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + for (E element : elements) { + if (!contains(element)) { + unsafeAdd(element); + } } + } - @Override - public boolean unsafeAdd(@NotNull E element) { + @Override + public boolean unsafeAdd(@NotNull E element) { - E[] array = array(); + E[] array = array(); - for (int i = 0, length = array.length; i < length; i++) { + for (int i = 0, length = array.length; i < length; i++) { - E old = array[i]; + E old = array[i]; - if (old == null) { - array[i] = element; - size++; - return true; - } - - if (element.compareTo(old) < 0) { + if (old == null) { + array[i] = element; + size++; + return true; + } - size++; + if (element.compareTo(old) < 0) { - int numMoved = size - i - 1; + size++; - System.arraycopy(array, i, array, i + 1, numMoved); + int numMoved = size - i - 1; - array[i] = element; - return true; - } - } + System.arraycopy(array, i, array, i + 1, numMoved); + array[i] = element; return true; + } } + + return true; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java index 8e75498a..fe73af1b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java @@ -4,7 +4,7 @@ import java.util.Collection; import java.util.NoSuchElementException; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayIterator; @@ -19,194 +19,196 @@ */ public class SynchronizedArray extends AbstractArray implements UnsafeArray { - private static final long serialVersionUID = -7288153859732883548L; + private static final long serialVersionUID = -7288153859732883548L; - /** - * The count of elements in this array. - */ - private final AtomicInteger size; + /** + * The count of elements in this array. + */ + private final ReusableAtomicInteger size; - /** - * The unsafe array. - */ - private volatile E[] array; + /** + * The unsafe array. + */ + private volatile E[] array; + public SynchronizedArray(@NotNull Class type) { + this(type, 10); + } - public SynchronizedArray(@NotNull Class type) { - this(type, 10); - } - - public SynchronizedArray(@NotNull Class type, int size) { - super(type, size); - this.size = new AtomicInteger(); - } + public SynchronizedArray(@NotNull Class type, int size) { + super(type, size); + this.size = new ReusableAtomicInteger(); + } - @Override - public synchronized boolean add(@NotNull E element) { + @Override + public synchronized boolean add(@NotNull E element) { - if (size() == array.length) { - array = ArrayUtils.copyOfAndExtend(array, array.length >> 1); - } - - array[size.getAndIncrement()] = element; - return true; + if (size() == array.length) { + array = ArrayUtils.copyOfAndExtend(array, array.length >> 1); } - @Override - public synchronized final boolean addAll(@NotNull Array elements) { + array[size.getAndIncrement()] = element; + return true; + } - if (elements.isEmpty()) { - return true; - } + @Override + public synchronized final boolean addAll(@NotNull Array elements) { - final int current = array.length; - final int selfSize = size(); - final int targetSize = elements.size(); - final int diff = selfSize + targetSize - current; + if (elements.isEmpty()) { + return true; + } - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } + final int current = array.length; + final int selfSize = size(); + final int targetSize = elements.size(); + final int diff = selfSize + targetSize - current; - processAdd(elements, selfSize, targetSize); - return true; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); } - @Override - public synchronized boolean addAll(@NotNull final Collection collection) { - if (collection.isEmpty()) return true; + processAdd(elements, selfSize, targetSize); + return true; + } - final int current = array.length; - final int diff = size() + collection.size() - current; + @Override + public synchronized boolean addAll(@NotNull final Collection collection) { + if (collection.isEmpty()) { + return true; + } - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); - } + final int current = array.length; + final int diff = size() + collection.size() - current; - for (final E element : collection) unsafeAdd(element); - return true; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); } - @Override - public synchronized final boolean addAll(@NotNull final E[] elements) { + for (final E element : collection) + unsafeAdd(element); + return true; + } - final int current = array.length; - final int selfSize = size(); - final int targetSize = elements.length; - final int diff = selfSize + targetSize - current; + @Override + public synchronized final boolean addAll(@NotNull final E[] elements) { - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } + final int current = array.length; + final int selfSize = size(); + final int targetSize = elements.length; + final int diff = selfSize + targetSize - current; - processAdd(elements, selfSize, targetSize); - return true; + if (diff > 0) { + array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); } - @NotNull - @Override - public final E[] array() { - return array; - } + processAdd(elements, selfSize, targetSize); + return true; + } - @NotNull - @Override - public synchronized final E fastRemove(final int index) { + @NotNull + @Override + public final E[] array() { + return array; + } - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } + @NotNull + @Override + public synchronized final E fastRemove(final int index) { - final int newSize = size.decrementAndGet(); - final E old = array[index]; + if (index < 0 || index >= size()) { + throw new NoSuchElementException(); + } - array[index] = array[newSize]; - array[newSize] = null; + final int newSize = size.decrementAndGet(); + final E old = array[index]; - return old; - } + array[index] = array[newSize]; + array[newSize] = null; - @NotNull - @Override - public synchronized final E get(final int index) { + return old; + } - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } + @NotNull + @Override + public synchronized final E get(final int index) { - return array[index]; + if (index < 0 || index >= size()) { + throw new NoSuchElementException(); } - @Override - public synchronized @NotNull ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } + return array[index]; + } - @Override - public void replace(int index, @NotNull E element) { + @Override + public synchronized @NotNull ArrayIterator iterator() { + return new DefaultArrayIterator<>(this); + } - if (index < 0 || index >= size()) { - throw new ArrayIndexOutOfBoundsException(); - } + @Override + public void replace(int index, @NotNull E element) { - array[index] = element; + if (index < 0 || index >= size()) { + throw new ArrayIndexOutOfBoundsException(); } - @Override - protected final void setArray(@NotNull final E[] array) { - this.array = array; - } + array[index] = element; + } - @Override - protected final void setSize(final int size) { - this.size.getAndSet(size); - } + @Override + protected final void setArray(@NotNull final E[] array) { + this.array = array; + } - @Override - public final int size() { - return size.get(); - } + @Override + protected final void setSize(final int size) { + this.size.getAndSet(size); + } - @Override - public synchronized @NotNull E remove(int index) { + @Override + public final int size() { + return size.get(); + } - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } + @Override + public synchronized @NotNull E remove(int index) { - var length = size(); - var numMoved = length - index - 1; + if (index < 0 || index >= size()) { + throw new NoSuchElementException(); + } - var old = array[index]; + var length = size(); + var numMoved = length - index - 1; - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } + var old = array[index]; - array[size.decrementAndGet()] = null; - return old; + if (numMoved > 0) { + System.arraycopy(array, index + 1, array, index, numMoved); } - @Override - public synchronized @NotNull SynchronizedArray trimToSize() { + array[size.decrementAndGet()] = null; + return old; + } - var size = size(); + @Override + public synchronized @NotNull SynchronizedArray trimToSize() { - if (size == array.length) { - return this; - } + var size = size(); - array = ArrayUtils.copyOfRange(array, 0, size); - return this; + if (size == array.length) { + return this; } - protected void processAdd(@NotNull final Array elements, final int selfSize, final int targetSize) { - System.arraycopy(elements.array(), 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } + array = ArrayUtils.copyOfRange(array, 0, size); + return this; + } - protected void processAdd(@NotNull final E[] elements, final int selfSize, final int targetSize) { - System.arraycopy(elements, 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } + protected void processAdd(@NotNull final Array elements, final int selfSize, final int targetSize) { + System.arraycopy(elements.array(), 0, array, selfSize, targetSize); + size.set(selfSize + targetSize); + } + + protected void processAdd(@NotNull final E[] elements, final int selfSize, final int targetSize) { + System.arraycopy(elements, 0, array, selfSize, targetSize); + size.set(selfSize + targetSize); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java index 5c1e0841..e80b86cc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java @@ -18,97 +18,97 @@ */ public class SymmetryCrypt { - /** - * The crypter. - */ - @NotNull - private final Cipher ecipher; - - /** - * The encrypter. - */ - @NotNull - private final Cipher dcipher; - - /** - * THe secret key. - */ - @NotNull - private final SecretKey secretKey; - - /** - * Instantiates a new Symmetry crypt. - * - * @param key the key. - * @throws NoSuchAlgorithmException the no such algorithm exception - * @throws NoSuchPaddingException the no such padding exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws InvalidKeyException the invalid key exception - */ - public SymmetryCrypt(@NotNull final String key) - throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException { - - final Cipher ecipher = Cipher.getInstance("RC4"); - final Cipher dcipher = Cipher.getInstance("RC4"); - - final byte[] bytes = key.getBytes("UTF-8"); - - secretKey = new SecretKey() { - - private static final long serialVersionUID = -8907627571317506056L; - - @Override - public String getAlgorithm() { - return "RC4"; - } - - @Override - public byte[] getEncoded() { - return bytes; - } - - @Override - public String getFormat() { - return "RAW"; - } - }; - - ecipher.init(Cipher.ENCRYPT_MODE, secretKey); - dcipher.init(Cipher.DECRYPT_MODE, secretKey); - - this.ecipher = ecipher; - this.dcipher = dcipher; - } - - /** - * Decrypt data. - * - * @param in the encrypted data. - * @param offset the offset. - * @param length the length. - * @param out the buffer to store decrypted data. - * @throws ShortBufferException the short buffer exception - * @throws IllegalBlockSizeException the illegal block size exception - * @throws BadPaddingException the bad padding exception - */ - public void decrypt(@NotNull final byte[] in, final int offset, final int length, @NotNull final byte[] out) - throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { - dcipher.doFinal(in, offset, length, out, offset); - } - - /** - * Encrypt data. - * - * @param in the decrypted data. - * @param offset the offset. - * @param length the length. - * @param out the buffer to store encrypted data. - * @throws ShortBufferException the short buffer exception - * @throws IllegalBlockSizeException the illegal block size exception - * @throws BadPaddingException the bad padding exception - */ - public void encrypt(@NotNull final byte[] in, final int offset, final int length, @NotNull final byte[] out) - throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { - ecipher.doFinal(in, offset, length, out, offset); - } + /** + * The crypter. + */ + @NotNull + private final Cipher ecipher; + + /** + * The encrypter. + */ + @NotNull + private final Cipher dcipher; + + /** + * THe secret key. + */ + @NotNull + private final SecretKey secretKey; + + /** + * Instantiates a new Symmetry crypt. + * + * @param key the key. + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws NoSuchPaddingException the no such padding exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws InvalidKeyException the invalid key exception + */ + public SymmetryCrypt(@NotNull final String key) + throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException { + + final Cipher ecipher = Cipher.getInstance("RC4"); + final Cipher dcipher = Cipher.getInstance("RC4"); + + final byte[] bytes = key.getBytes("UTF-8"); + + secretKey = new SecretKey() { + + private static final long serialVersionUID = -8907627571317506056L; + + @Override + public String getAlgorithm() { + return "RC4"; + } + + @Override + public byte[] getEncoded() { + return bytes; + } + + @Override + public String getFormat() { + return "RAW"; + } + }; + + ecipher.init(Cipher.ENCRYPT_MODE, secretKey); + dcipher.init(Cipher.DECRYPT_MODE, secretKey); + + this.ecipher = ecipher; + this.dcipher = dcipher; + } + + /** + * Decrypt data. + * + * @param in the encrypted data. + * @param offset the offset. + * @param length the length. + * @param out the buffer to store decrypted data. + * @throws ShortBufferException the short buffer exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + */ + public void decrypt(@NotNull final byte[] in, final int offset, final int length, @NotNull final byte[] out) + throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + dcipher.doFinal(in, offset, length, out, offset); + } + + /** + * Encrypt data. + * + * @param in the decrypted data. + * @param offset the offset. + * @param length the length. + * @param out the buffer to store encrypted data. + * @throws ShortBufferException the short buffer exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + */ + public void encrypt(@NotNull final byte[] in, final int offset, final int length, @NotNull final byte[] out) + throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { + ecipher.doFinal(in, offset, length, out, offset); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java index bd409cb0..13eaa669 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.util.dictionary; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; import org.jetbrains.annotations.NotNull; @@ -13,67 +13,67 @@ public abstract class AbstractConcurrentIntegerDictionary extends AbstractIntegerDictionary implements ConcurrentIntegerDictionary { - private final @NotNull AtomicInteger size; - - private volatile @NotNull IntegerEntry[] entries; - - private volatile int threshold; - - protected AbstractConcurrentIntegerDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentIntegerDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentIntegerDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractConcurrentIntegerDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - this.size = new AtomicInteger(0); - } - - @Override - public void setEntries(@NotNull IntegerEntry[] entries) { - this.entries = entries; - } - - @Override - public IntegerEntry @NotNull [] entries() { - return entries; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected void setSize(int size) { - this.size.set(size); - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - protected int decrementSizeAndGet() { - return size.decrementAndGet(); - } - - @Override - protected int incrementSizeAndGet() { - return size.incrementAndGet(); - } - - @Override - public final int size() { - return size.get(); - } + private final @NotNull ReusableAtomicInteger size; + + private volatile @NotNull IntegerEntry[] entries; + + private volatile int threshold; + + protected AbstractConcurrentIntegerDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractConcurrentIntegerDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractConcurrentIntegerDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected AbstractConcurrentIntegerDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.entries = ArrayUtils.create(getEntryType(), initCapacity); + this.size = new ReusableAtomicInteger(0); + } + + @Override + public void setEntries(@NotNull IntegerEntry[] entries) { + this.entries = entries; + } + + @Override + public IntegerEntry @NotNull [] entries() { + return entries; + } + + @Override + public int getThreshold() { + return threshold; + } + + @Override + protected void setSize(int size) { + this.size.set(size); + } + + @Override + public void setThreshold(int threshold) { + this.threshold = threshold; + } + + @Override + protected int decrementSizeAndGet() { + return size.decrementAndGet(); + } + + @Override + protected int incrementSizeAndGet() { + return size.incrementAndGet(); + } + + @Override + public final int size() { + return size.get(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java index 889f3629..342532f7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.util.dictionary; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; import org.jetbrains.annotations.NotNull; @@ -13,67 +13,67 @@ public abstract class AbstractConcurrentLongDictionary extends AbstractLongDictionary implements ConcurrentLongDictionary { - private final @NotNull AtomicInteger size; - - private volatile @NotNull LongEntry[] entries; - - private volatile int threshold; - - protected AbstractConcurrentLongDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentLongDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentLongDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractConcurrentLongDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - this.size = new AtomicInteger(0); - } - - @Override - protected void setEntries(@NotNull LongEntry[] entries) { - this.entries = entries; - } - - @Override - public LongEntry @NotNull [] entries() { - return entries; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected void setSize(int size) { - this.size.set(size); - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - protected int decrementSizeAndGet() { - return size.decrementAndGet(); - } - - @Override - protected int incrementSizeAndGet() { - return size.incrementAndGet(); - } - - @Override - public final int size() { - return size.get(); - } + private final @NotNull ReusableAtomicInteger size; + + private volatile @NotNull LongEntry[] entries; + + private volatile int threshold; + + protected AbstractConcurrentLongDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractConcurrentLongDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractConcurrentLongDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected AbstractConcurrentLongDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.entries = ArrayUtils.create(getEntryType(), initCapacity); + this.size = new ReusableAtomicInteger(0); + } + + @Override + protected void setEntries(@NotNull LongEntry[] entries) { + this.entries = entries; + } + + @Override + public LongEntry @NotNull [] entries() { + return entries; + } + + @Override + public int getThreshold() { + return threshold; + } + + @Override + protected void setSize(int size) { + this.size.set(size); + } + + @Override + public void setThreshold(int threshold) { + this.threshold = threshold; + } + + @Override + protected int decrementSizeAndGet() { + return size.decrementAndGet(); + } + + @Override + protected int incrementSizeAndGet() { + return size.incrementAndGet(); + } + + @Override + public final int size() { + return size.get(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java index a20f424f..4f66ce53 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.util.dictionary; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; import org.jetbrains.annotations.NotNull; @@ -14,67 +14,67 @@ public abstract class AbstractConcurrentObjectDictionary extends AbstractObjectDictionary implements ConcurrentObjectDictionary { - private final @NotNull AtomicInteger size; - - private volatile @NotNull ObjectEntry[] entries; - - private volatile int threshold; - - protected AbstractConcurrentObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractConcurrentObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - this.size = new AtomicInteger(0); - } - - @Override - public void setEntries(@NotNull ObjectEntry[] entries) { - this.entries = entries; - } - - @Override - public ObjectEntry @NotNull [] entries() { - return entries; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected void setSize(int size) { - this.size.set(size); - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - protected int decrementSizeAndGet() { - return size.decrementAndGet(); - } - - @Override - protected int incrementSizeAndGet() { - return size.incrementAndGet(); - } - - @Override - public final int size() { - return size.get(); - } + private final @NotNull ReusableAtomicInteger size; + + private volatile @NotNull ObjectEntry[] entries; + + private volatile int threshold; + + protected AbstractConcurrentObjectDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractConcurrentObjectDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractConcurrentObjectDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected AbstractConcurrentObjectDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.entries = ArrayUtils.create(getEntryType(), initCapacity); + this.size = new ReusableAtomicInteger(0); + } + + @Override + public void setEntries(@NotNull ObjectEntry[] entries) { + this.entries = entries; + } + + @Override + public ObjectEntry @NotNull [] entries() { + return entries; + } + + @Override + public int getThreshold() { + return threshold; + } + + @Override + protected void setSize(int size) { + this.size.set(size); + } + + @Override + public void setThreshold(int threshold) { + this.threshold = threshold; + } + + @Override + protected int decrementSizeAndGet() { + return size.decrementAndGet(); + } + + @Override + protected int incrementSizeAndGet() { + return size.incrementAndGet(); + } + + @Override + public final int size() { + return size.get(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java index fa70e014..f8115191 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java @@ -19,245 +19,245 @@ */ public abstract class AbstractDictionary> implements Dictionary { - /** - * The default size of table in the {@link Dictionary}. - */ - protected static final int DEFAULT_INITIAL_CAPACITY = 16; - - /** - * The max size of the {@link Dictionary}. - */ - protected static final int DEFAULT_MAXIMUM_CAPACITY = 1 << 30; - - /** - * The load factor of the {@link Dictionary}. - */ - protected static final float DEFAULT_LOAD_FACTOR = 0.75f; - - /** - * Calculate a hash of the hashcode. - * - * @param hashcode the hashcode. - * @return the hash. - */ - protected static int hash(int hashcode) { - hashcode ^= hashcode >>> 20 ^ hashcode >>> 12; - return hashcode ^ hashcode >>> 7 ^ hashcode >>> 4; + /** + * The default size of table in the {@link Dictionary}. + */ + protected static final int DEFAULT_INITIAL_CAPACITY = 16; + + /** + * The max size of the {@link Dictionary}. + */ + protected static final int DEFAULT_MAXIMUM_CAPACITY = 1 << 30; + + /** + * The load factor of the {@link Dictionary}. + */ + protected static final float DEFAULT_LOAD_FACTOR = 0.75f; + + /** + * Calculate a hash of the hashcode. + * + * @param hashcode the hashcode. + * @return the hash. + */ + protected static int hash(int hashcode) { + hashcode ^= hashcode >>> 20 ^ hashcode >>> 12; + return hashcode ^ hashcode >>> 7 ^ hashcode >>> 4; + } + + /** + * Calculate a hash of the long key. + * + * @param key the long key. + * @return the hash. + */ + protected static int hash(long key) { + int hash = (int) (key ^ key >>> 32); + hash ^= hash >>> 20 ^ hash >>> 12; + return hash ^ hash >>> 7 ^ hash >>> 4; + } + + /** + * Get an index of table in the {@link Dictionary}. + * + * @param hash the hash of a key. + * @param length the length of a table in the {@link Dictionary}. + * @return the index in the table. + */ + protected static int indexFor(int hash, int length) { + return hash & length - 1; + } + + /** + * The pool with entries. + */ + protected final ReusablePool entryPool; + + /** + * The load factor. + */ + protected final float loadFactor; + + protected AbstractDictionary(float loadFactor, int initCapacity) { + this.loadFactor = loadFactor; + this.entryPool = PoolFactory.newReusablePool(getEntryType()); + setThreshold((int) (initCapacity * loadFactor)); + } + + @Override + public final void apply(@NotNull NotNullFunction function) { + for (var entry : entries()) { + while (entry != null) { + entry.setValue(function.apply(entry.getValue())); + entry = entry.getNext(); + } } + } - /** - * Calculate a hash of the long key. - * - * @param key the long key. - * @return the hash. - */ - protected static int hash(long key) { - int hash = (int) (key ^ key >>> 32); - hash ^= hash >>> 20 ^ hash >>> 12; - return hash ^ hash >>> 7 ^ hash >>> 4; - } - - /** - * Get an index of table in the {@link Dictionary}. - * - * @param hash the hash of a key. - * @param length the length of a table in the {@link Dictionary}. - * @return the index in the table. - */ - protected static int indexFor(int hash, int length) { - return hash & length - 1; - } + @Override + public void clear() { - /** - * The pool with entries. - */ - protected final ReusablePool entryPool; + var entries = entries(); - /** - * The load factor. - */ - protected final float loadFactor; - - protected AbstractDictionary(float loadFactor, int initCapacity) { - this.loadFactor = loadFactor; - this.entryPool = PoolFactory.newReusablePool(getEntryType()); - setThreshold((int) (initCapacity * loadFactor)); - } + E next; - @Override - public final void apply(@NotNull NotNullFunction function) { - for (var entry : entries()) { - while (entry != null) { - entry.setValue(function.apply(entry.getValue())); - entry = entry.getNext(); - } - } + for (E entry : entries) { + while (entry != null) { + next = entry.getNext(); + entryPool.put(entry); + entry = next; + } } - @Override - public void clear() { + ArrayUtils.clear(entries); - var entries = entries(); + setSize(0); + } - E next; + @Override + public final boolean containsValue(@Nullable V value) { - for (E entry : entries) { - while (entry != null) { - next = entry.getNext(); - entryPool.put(entry); - entry = next; - } + for (var entry : entries()) { + for (var nextEntry = entry; nextEntry != null; nextEntry = nextEntry.getNext()) { + if (Objects.equals(value, nextEntry.getValue())) { + return true; } - - ArrayUtils.clear(entries); - - setSize(0); + } } - @Override - public final boolean containsValue(@Nullable V value) { - - for (var entry : entries()) { - for (var nextEntry = entry; nextEntry != null; nextEntry = nextEntry.getNext()) { - if (Objects.equals(value, nextEntry.getValue())) { - return true; - } - } - } + return false; + } - return false; + @Override + public final void forEach(@NotNull Consumer consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(entry.getValue()); + entry = entry.getNext(); + } } + } - @Override - public final void forEach(@NotNull Consumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getValue()); - entry = entry.getNext(); - } - } - } + /** + * Resize the array of buckets of this dictionary. + * + * @param newLength the new size. + */ + protected final void resize(int newLength) { - /** - * Resize the array of buckets of this dictionary. - * - * @param newLength the new size. - */ - protected final void resize(int newLength) { + var prevEntries = entries(); + var oldLength = prevEntries.length; - var prevEntries = entries(); - var oldLength = prevEntries.length; + if (oldLength >= DEFAULT_MAXIMUM_CAPACITY) { + setThreshold(Integer.MAX_VALUE); + return; + } - if (oldLength >= DEFAULT_MAXIMUM_CAPACITY) { - setThreshold(Integer.MAX_VALUE); - return; - } + var newEntries = ArrayUtils.create(getEntryType(), newLength); - var newEntries = ArrayUtils.create(getEntryType(), newLength); + transfer(newEntries); + setEntries(newEntries); + setThreshold((int) (newLength * loadFactor)); + } - transfer(newEntries); - setEntries(newEntries); - setThreshold((int) (newLength * loadFactor)); - } + /** + * Transfer current entries to new entries. + * + * @param newEntries the new array of entries. + */ + private void transfer(@NotNull E[] newEntries) { - /** - * Transfer current entries to new entries. - * - * @param newEntries the new array of entries. - */ - private void transfer(@NotNull E[] newEntries) { + var entries = entries(); + var newCapacity = newEntries.length; - var entries = entries(); - var newCapacity = newEntries.length; + for (var entry : entries) { - for (var entry : entries) { + if (entry == null) { + continue; + } - if (entry == null) { - continue; - } + do { - do { + var nextEntry = entry.getNext(); + var i = indexFor(entry.getHash(), newCapacity); - var nextEntry = entry.getNext(); - var i = indexFor(entry.getHash(), newCapacity); + entry.setNext(newEntries[i]); + newEntries[i] = entry; + entry = nextEntry; - entry.setNext(newEntries[i]); - newEntries[i] = entry; - entry = nextEntry; - - } while (entry != null); - } + } while (entry != null); } + } - @Override - public final @NotNull Array values(@NotNull Array container) { + @Override + public final @NotNull Array values(@NotNull Array container) { - var unsafeArray = container.asUnsafe(); - unsafeArray.prepareForSize(container.size() + size()); - - for (var entry : entries()) { - while (entry != null) { - unsafeArray.unsafeAdd(entry.getValue()); - entry = entry.getNext(); - } - } + var unsafeArray = container.asUnsafe(); + unsafeArray.prepareForSize(container.size() + size()); - return container; + for (var entry : entries()) { + while (entry != null) { + unsafeArray.unsafeAdd(entry.getValue()); + entry = entry.getNext(); + } } - /** - * Get the entries type. - * - * @return the entries type. - */ - protected abstract @NotNull Class getEntryType(); - - /** - * Set new array of entries of this {@link Dictionary}. - * - * @param entries the new array of entries. - */ - protected abstract void setEntries(@NotNull E[] entries); - - /** - * Get an array of all entries in this dictionary.. - * - * @return the array of entries. - */ - protected abstract E @NotNull [] entries(); - - /** - * Set the next size value at which to resize (capacity * load factor). - * - * @param threshold the next size. - */ - protected abstract void setThreshold(int threshold); - - /** - * Get the threshold. - * - * @return the current next size. - */ - protected abstract int getThreshold(); - - /** - * Set the new size of this {@link Dictionary}. - * - * @param size the new size. - */ - protected abstract void setSize(int size); - - /** - * Decrement and get the size of this {@link Dictionary}. - * - * @return the new size of this {@link Dictionary}. - */ - protected abstract int decrementSizeAndGet(); - - /** - * Increment and get the size of this {@link Dictionary}. - * - * @return the new size of this {@link Dictionary}. - */ - protected abstract int incrementSizeAndGet(); + return container; + } + + /** + * Get the entries type. + * + * @return the entries type. + */ + protected abstract @NotNull Class getEntryType(); + + /** + * Set new array of entries of this {@link Dictionary}. + * + * @param entries the new array of entries. + */ + protected abstract void setEntries(@NotNull E[] entries); + + /** + * Get an array of all entries in this dictionary.. + * + * @return the array of entries. + */ + protected abstract E @NotNull [] entries(); + + /** + * Set the next size value at which to resize (capacity * load factor). + * + * @param threshold the next size. + */ + protected abstract void setThreshold(int threshold); + + /** + * Get the threshold. + * + * @return the current next size. + */ + protected abstract int getThreshold(); + + /** + * Set the new size of this {@link Dictionary}. + * + * @param size the new size. + */ + protected abstract void setSize(int size); + + /** + * Decrement and get the size of this {@link Dictionary}. + * + * @return the new size of this {@link Dictionary}. + */ + protected abstract int decrementSizeAndGet(); + + /** + * Increment and get the size of this {@link Dictionary}. + * + * @return the new size of this {@link Dictionary}. + */ + protected abstract int incrementSizeAndGet(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java index bda8d0f2..cabe22e8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java @@ -21,289 +21,283 @@ public abstract class AbstractIntegerDictionary extends AbstractDictionary> implements UnsafeIntegerDictionary { - protected AbstractIntegerDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + protected AbstractIntegerDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractIntegerDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + } + + @Override + protected @NotNull Class> getEntryType() { + return IntegerEntry.class; + } + + /** + * Add a new entry to this dictionary. + * + * @param hash the hash of the key. + * @param key the key. + * @param value the value of the key. + * @param index the index of bucket. + */ + protected final void addEntry(int hash, int key, @NotNull V value, int index) { + + var entries = entries(); + var entry = entries[index]; + + var newEntry = entryPool.take(IntegerEntry::new); + newEntry.set(hash, key, value, entry); + + entries[index] = newEntry; + + if (incrementSizeAndGet() >= getThreshold()) { + resize(2 * entries.length); } - - protected AbstractIntegerDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); + } + + @Override + public final boolean containsKey(int key) { + return getEntry(key) != null; + } + + @Override + public void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } } - - @Override - protected @NotNull Class> getEntryType() { - return IntegerEntry.class; + } + + @Override + public void forEach( + @NotNull T argument, + @NotNull IntBiObjectConsumer<@NotNull ? super V, @NotNull ? super T> consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(entry.getKey(), entry.getValue(), argument); + entry = entry.getNext(); + } } + } - /** - * Add a new entry to this dictionary. - * - * @param hash the hash of the key. - * @param key the key. - * @param value the value of the key. - * @param index the index of bucket. - */ - protected final void addEntry(int hash, int key, @NotNull V value, int index) { - - var entries = entries(); - var entry = entries[index]; + @Override + public final @Nullable V get(int key) { + var entry = getEntry(key); + return entry == null ? null : entry.getValue(); + } - var newEntry = entryPool.take(IntegerEntry::new); - newEntry.set(hash, key, value, entry); + @Override + public @NotNull V getOrCompute(int key, @NotNull Supplier<@NotNull V> factory) { - entries[index] = newEntry; + var entry = getEntry(key); - if (incrementSizeAndGet() >= getThreshold()) { - resize(2 * entries.length); - } + if (entry == null) { + put(key, factory.get()); + entry = getEntry(key); } - @Override - public final boolean containsKey(int key) { - return getEntry(key) != null; + if (entry == null) { + throw new IllegalStateException("The factory " + factory + " returned a null value."); } - @Override - public void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } + return entry.getValue(); + } - @Override - public void forEach( - @NotNull T argument, - @NotNull IntBiObjectConsumer<@NotNull ? super V, @NotNull ? super T> consumer - ) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue(), argument); - entry = entry.getNext(); - } - } + @Override + public @NotNull V getOrCompute(int key, @NotNull IntFunction<@NotNull V> factory) { + + var entry = getEntry(key); + + if (entry == null) { + put(key, factory.apply(key)); + entry = getEntry(key); } - @Override - public final @Nullable V get(int key) { - var entry = getEntry(key); - return entry == null ? null : entry.getValue(); + if (entry == null) { + throw new IllegalStateException("The factory " + factory + " returned a null value."); } - @Override - public @NotNull V getOrCompute(int key, @NotNull Supplier<@NotNull V> factory) { + return entry.getValue(); + } - var entry = getEntry(key); + @Override + public @Nullable V getOrCompute(int key, @NotNull T argument, @NotNull Function<@NotNull T, @NotNull V> factory) { - if (entry == null) { - put(key, factory.get()); - entry = getEntry(key); - } + var entry = getEntry(key); - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } + if (entry == null) { + put(key, factory.apply(argument)); + entry = getEntry(key); + } - return entry.getValue(); + if (entry == null) { + throw new IllegalStateException("The factory " + factory + " returned a null value."); } - @Override - public @NotNull V getOrCompute(int key, @NotNull IntFunction<@NotNull V> factory) { + return entry.getValue(); + } - var entry = getEntry(key); + /** + * Get the entry with value for the key. + * + * @param key the key. + * @return the entry or null. + */ - if (entry == null) { - put(key, factory.apply(key)); - entry = getEntry(key); - } + private @Nullable IntegerEntry getEntry(int key) { - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } + var entries = entries(); + var index = indexFor(hash(key), entries.length); - return entry.getValue(); + for (IntegerEntry entry = entries[index]; entry != null; entry = entry.getNext()) { + if (key == entry.getKey()) { + return entry; + } } - @Override - public @Nullable V getOrCompute( - int key, - @NotNull T argument, - @NotNull Function<@NotNull T, @NotNull V> factory - ) { + return null; + } - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(argument)); - entry = getEntry(key); - } + @Override + public final @NotNull Iterator iterator() { + return new IntegerDictionaryIterator<>(this); + } - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } + @Override + public @NotNull IntegerArray keyArray(@NotNull MutableIntegerArray container) { - return entry.getValue(); + for (var entry : entries()) { + while (entry != null) { + container.add(entry.getKey()); + entry = entry.getNext(); + } } - /** - * Get the entry with value for the key. - * - * @param key the key. - * @return the entry or null. - */ - - private @Nullable IntegerEntry getEntry(int key) { - - var entries = entries(); - var index = indexFor(hash(key), entries.length); - - for (IntegerEntry entry = entries[index]; entry != null; entry = entry.getNext()) { - if (key == entry.getKey()) { - return entry; - } - } + return container; + } - return null; - } + @Override + public void copyTo(@NotNull Dictionary dictionary) { - @Override - public final @NotNull Iterator iterator() { - return new IntegerDictionaryIterator<>(this); + if (isEmpty() || !(dictionary instanceof IntegerDictionary)) { + return; } - @Override - public @NotNull IntegerArray keyArray(@NotNull MutableIntegerArray container) { - - for (var entry : entries()) { - while (entry != null) { - container.add(entry.getKey()); - entry = entry.getNext(); - } - } + IntegerDictionary target = ClassUtils.unsafeNNCast(dictionary); - return container; + for (IntegerEntry entry : entries()) { + while (entry != null) { + target.put(entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } } + } - @Override - public void copyTo(@NotNull Dictionary dictionary) { + @Override + public final @Nullable V put(int key, @NotNull V value) { - if (isEmpty() || !(dictionary instanceof IntegerDictionary)) { - return; - } + var entries = entries(); - IntegerDictionary target = ClassUtils.unsafeNNCast(dictionary); + var hash = hash(key); + var entryIndex = indexFor(hash, entries.length); - for (IntegerEntry entry : entries()) { - while (entry != null) { - target.put(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } + for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { + if (entry.getHash() == hash && key == entry.getKey()) { + return entry.setValue(value); + } } - @Override - public final @Nullable V put(int key, @NotNull V value) { + addEntry(hash, key, value, entryIndex); + return null; + } - var entries = entries(); + @Override + public @Nullable V remove(int key) { - var hash = hash(key); - var entryIndex = indexFor(hash, entries.length); + var old = removeEntryForKey(key); - for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key == entry.getKey()) { - return entry.setValue(value); - } - } - - addEntry(hash, key, value, entryIndex); - return null; + if (old == null) { + return null; } + var value = old.getValue(); - @Override - public @Nullable V remove(int key) { - - var old = removeEntryForKey(key); + entryPool.put(old); - if (old == null) { - return null; - } + return value; + } - var value = old.getValue(); + /** + * Remove the entry for the key. + * + * @param key the key of the entry. + * @return removed entry or null. + */ + @Override + public final @Nullable IntegerEntry removeEntryForKey(int key) { - entryPool.put(old); - - return value; - } + var entries = entries(); - /** - * Remove the entry for the key. - * - * @param key the key of the entry. - * @return removed entry or null. - */ - @Override - public final @Nullable IntegerEntry removeEntryForKey(int key) { + int i = indexFor(hash(key), entries.length); - var entries = entries(); + var prev = entries[i]; + var entry = prev; - int i = indexFor(hash(key), entries.length); + while (entry != null) { - var prev = entries[i]; - var entry = prev; + var next = entry.getNext(); - while (entry != null) { + if (key == entry.getKey()) { + decrementSizeAndGet(); - var next = entry.getNext(); + if (prev == entry) { + entries[i] = next; + } else { + prev.setNext(next); + } - if (key == entry.getKey()) { - decrementSizeAndGet(); + return entry; + } - if (prev == entry) { - entries[i] = next; - } else { - prev.setNext(next); - } + prev = entry; + entry = next; + } - return entry; - } + return null; + } - prev = entry; - entry = next; - } - - return null; - } + @Override + public final String toString() { - @Override - public final String toString() { + var size = size(); - var size = size(); + var builder = new StringBuilder(getClass().getSimpleName()); + builder + .append(" size = ") + .append(size) + .append(" : "); - var builder = new StringBuilder(getClass().getSimpleName()); + for (var entry : entries()) { + while (entry != null) { builder - .append(" size = ") - .append(size) - .append(" : "); - - for (var entry : entries()) { - while (entry != null) { - builder - .append("[") - .append(entry.getKey()) - .append(" - ") - .append(entry.getValue()) - .append("]") - .append("\n"); - entry = entry.getNext(); - } - } - - if (size > 0) { - builder.replace(builder.length() - 1, builder.length(), "."); - } + .append("[") + .append(entry.getKey()) + .append(" - ") + .append(entry.getValue()) + .append("]") + .append("\n"); + entry = entry.getNext(); + } + } - return builder.toString(); + if (size > 0) { + builder.replace(builder.length() - 1, builder.length(), "."); } + + return builder.toString(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java index f5169b46..56f4a8a6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java @@ -17,291 +17,290 @@ * @param the value's type. * @author JavaSaBr */ -public abstract class AbstractLongDictionary extends AbstractDictionary> - implements UnsafeLongDictionary { - - protected AbstractLongDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractLongDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractLongDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractLongDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - } - - @Override - protected @NotNull Class> getEntryType() { - return LongEntry.class; +public abstract class AbstractLongDictionary extends AbstractDictionary> implements + UnsafeLongDictionary { + + protected AbstractLongDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractLongDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractLongDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected AbstractLongDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + } + + @Override + protected @NotNull Class> getEntryType() { + return LongEntry.class; + } + + /** + * Add new entry to this dictionary. + * + * @param hash the hash of the key. + * @param key the key. + * @param value the value of the key. + * @param index the index of bucket. + */ + private void addEntry(int hash, long key, @NotNull V value, int index) { + + var entries = entries(); + var entry = entries[index]; + + var newEntry = entryPool.take(LongEntry::new); + newEntry.set(hash, key, value, entry); + + entries[index] = newEntry; + + if (incrementSizeAndGet() >= getThreshold()) { + resize(2 * entries.length); } + } - /** - * Add new entry to this dictionary. - * - * @param hash the hash of the key. - * @param key the key. - * @param value the value of the key. - * @param index the index of bucket. - */ - private void addEntry(int hash, long key, @NotNull V value, int index) { + @Override + public final boolean containsKey(long key) { + return getEntry(key) != null; + } - var entries = entries(); - var entry = entries[index]; + @Override + public final @Nullable V get(long key) { + var entry = getEntry(key); + return entry == null ? null : entry.getValue(); + } - var newEntry = entryPool.take(LongEntry::new); - newEntry.set(hash, key, value, entry); + @Override + public @NotNull V getOrCompute(long key, @NotNull Supplier<@NotNull V> factory) { - entries[index] = newEntry; + var entry = getEntry(key); - if (incrementSizeAndGet() >= getThreshold()) { - resize(2 * entries.length); - } + if (entry == null) { + put(key, factory.get()); + entry = getEntry(key); } - @Override - public final boolean containsKey(long key) { - return getEntry(key) != null; + if (entry == null) { + throw new IllegalStateException("The factory " + factory + " returned a null value."); } - @Override - public final @Nullable V get(long key) { - var entry = getEntry(key); - return entry == null ? null : entry.getValue(); - } + return entry.getValue(); + } - @Override - public @NotNull V getOrCompute(long key, @NotNull Supplier<@NotNull V> factory) { + @Override + public @NotNull V getOrCompute(long key, @NotNull LongFunction<@NotNull V> factory) { - var entry = getEntry(key); + var entry = getEntry(key); - if (entry == null) { - put(key, factory.get()); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); + if (entry == null) { + put(key, factory.apply(key)); + entry = getEntry(key); } - @Override - public @NotNull V getOrCompute(long key, @NotNull LongFunction<@NotNull V> factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(key)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); + if (entry == null) { + throw new IllegalStateException("The factory " + factory + " returned a null value."); } - @Override - public @Nullable V getOrCompute( - long key, - @NotNull T argument, - @NotNull Function<@NotNull T, @NotNull V> factory - ) { + return entry.getValue(); + } - var entry = getEntry(key); + @Override + public @Nullable V getOrCompute( + long key, + @NotNull T argument, + @NotNull Function<@NotNull T, @NotNull V> factory) { - if (entry == null) { - put(key, factory.apply(argument)); - entry = getEntry(key); - } + var entry = getEntry(key); - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } + if (entry == null) { + put(key, factory.apply(argument)); + entry = getEntry(key); + } - return entry.getValue(); + if (entry == null) { + throw new IllegalStateException("The factory " + factory + " returned a null value."); } - /** - * Get the entry with value for the key. - * - * @param key the key. - * @return the entry or null. - */ - private @Nullable LongEntry getEntry(long key) { + return entry.getValue(); + } - var entries = entries(); + /** + * Get the entry with value for the key. + * + * @param key the key. + * @return the entry or null. + */ + private @Nullable LongEntry getEntry(long key) { - int hash = hash(key); - int index = indexFor(hash, entries.length); + var entries = entries(); - for (var entry = entries[index]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key == entry.getKey()) { - return entry; - } - } + int hash = hash(key); + int index = indexFor(hash, entries.length); - return null; + for (var entry = entries[index]; entry != null; entry = entry.getNext()) { + if (entry.getHash() == hash && key == entry.getKey()) { + return entry; + } } - @Override - public final Iterator iterator() { - return new LongDictionaryIterator<>(this); - } + return null; + } - @Override - public @NotNull LongArray keyArray(@NotNull LongArray container) { + @Override + public final Iterator iterator() { + return new LongDictionaryIterator<>(this); + } - for (var entry : entries()) { - while (entry != null) { - container.add(entry.getKey()); - entry = entry.getNext(); - } - } + @Override + public @NotNull LongArray keyArray(@NotNull LongArray container) { - return container; + for (var entry : entries()) { + while (entry != null) { + container.add(entry.getKey()); + entry = entry.getNext(); + } } - @Override - public void copyTo(@NotNull Dictionary dictionary) { - - if (isEmpty() || !(dictionary instanceof LongDictionary)) { - return; - } + return container; + } - var targetDictionary = ClassUtils.>unsafeNNCast(dictionary); + @Override + public void copyTo(@NotNull Dictionary dictionary) { - for (var entry : entries()) { - while (entry != null) { - targetDictionary.put(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } + if (isEmpty() || !(dictionary instanceof LongDictionary)) { + return; } - @Override - public V put(long key, @NotNull V value) { + var targetDictionary = ClassUtils.>unsafeNNCast(dictionary); - var entries = entries(); - var hash = hash(key); - var i = indexFor(hash, entries.length); + for (var entry : entries()) { + while (entry != null) { + targetDictionary.put(entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } + } + } - for (var entry = entries[i]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key == entry.getKey()) { - return entry.setValue(value); - } - } + @Override + public V put(long key, @NotNull V value) { - addEntry(hash, key, value, i); + var entries = entries(); + var hash = hash(key); + var i = indexFor(hash, entries.length); - return null; + for (var entry = entries[i]; entry != null; entry = entry.getNext()) { + if (entry.getHash() == hash && key == entry.getKey()) { + return entry.setValue(value); + } } - @Override - public @Nullable V remove(long key) { + addEntry(hash, key, value, i); - var oldEntry = removeEntryForKey(key); + return null; + } - V value = oldEntry == null ? null : oldEntry.getValue(); + @Override + public @Nullable V remove(long key) { - if (oldEntry != null) { - entryPool.put(oldEntry); - } + var oldEntry = removeEntryForKey(key); - return value; - } + V value = oldEntry == null ? null : oldEntry.getValue(); - @Override - public @Nullable LongEntry removeEntryForKey(long key) { + if (oldEntry != null) { + entryPool.put(oldEntry); + } - var entries = entries(); - var hash = hash(key); - var i = indexFor(hash, entries.length); + return value; + } - var prevEntry = entries[i]; - var entry = prevEntry; + @Override + public @Nullable LongEntry removeEntryForKey(long key) { - while (entry != null) { + var entries = entries(); + var hash = hash(key); + var i = indexFor(hash, entries.length); - var nextEntry = entry.getNext(); + var prevEntry = entries[i]; + var entry = prevEntry; - if (entry.getHash() == hash && key == entry.getKey()) { - decrementSizeAndGet(); + while (entry != null) { - if (prevEntry == entry) { - entries[i] = nextEntry; - } else { - prevEntry.setNext(nextEntry); - } + var nextEntry = entry.getNext(); - return entry; - } + if (entry.getHash() == hash && key == entry.getKey()) { + decrementSizeAndGet(); - prevEntry = entry; - entry = nextEntry; + if (prevEntry == entry) { + entries[i] = nextEntry; + } else { + prevEntry.setNext(nextEntry); } - return null; + return entry; + } + + prevEntry = entry; + entry = nextEntry; } - @Override - public final String toString() { + return null; + } - var size = size(); + @Override + public final String toString() { - var builder = new StringBuilder(getClass().getSimpleName()); - builder - .append(" size = ") - .append(size) - .append(" :\n"); - - var entries = entries(); - - for (var entry : entries) { - while (entry != null) { - builder - .append("[") - .append(entry.getKey()) - .append(" - ") - .append(entry.getValue()) - .append("]") - .append("\n"); - entry = entry.getNext(); - } - } + var size = size(); - if (size > 0) { - builder.delete(builder.length() - 1, builder.length()); - } + var builder = new StringBuilder(getClass().getSimpleName()); + builder + .append(" size = ") + .append(size) + .append(" :\n"); + + var entries = entries(); - return builder.toString(); + for (var entry : entries) { + while (entry != null) { + builder + .append("[") + .append(entry.getKey()) + .append(" - ") + .append(entry.getValue()) + .append("]") + .append("\n"); + entry = entry.getNext(); + } } - @Override - public void forEach(@NotNull T argument, @NotNull LongBiObjectConsumer<@NotNull V, @NotNull T> consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue(), argument); - entry = entry.getNext(); - } - } + if (size > 0) { + builder.delete(builder.length() - 1, builder.length()); } - @Override - public void forEach(@NotNull LongObjectConsumer<@NotNull V> consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } + return builder.toString(); + } + + @Override + public void forEach(@NotNull T argument, @NotNull LongBiObjectConsumer<@NotNull V, @NotNull T> consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(entry.getKey(), entry.getValue(), argument); + entry = entry.getNext(); + } + } + } + + @Override + public void forEach(@NotNull LongObjectConsumer<@NotNull V> consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java index ea178506..096e514a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java @@ -19,335 +19,329 @@ * @param the value's type. * @author JavaSaBr */ -public abstract class AbstractObjectDictionary extends AbstractDictionary> - implements UnsafeObjectDictionary { - - protected AbstractObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); +public abstract class AbstractObjectDictionary extends AbstractDictionary> implements + UnsafeObjectDictionary { + + protected AbstractObjectDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractObjectDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected AbstractObjectDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected AbstractObjectDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + } + + @Override + protected @NotNull Class> getEntryType() { + return ObjectEntry.class; + } + + /** + * Add new entry to this dictionary. + * + * @param hash the hash of the key. + * @param key the key. + * @param value the value of the key. + * @param index the index of bucket. + */ + private void addEntry(int hash, K key, V value, int index) { + + var entries = entries(); + var entry = entries[index]; + + var newEntry = entryPool.take(ObjectEntry::new); + newEntry.set(hash, key, value, entry); + + entries[index] = newEntry; + + if (incrementSizeAndGet() >= getThreshold()) { + resize(2 * entries.length); } + } - protected AbstractObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } + @Override + public final boolean containsKey(@NotNull K key) { + return getEntry(key) != null; + } - protected AbstractObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } + @Override + public @Nullable V get(@NotNull K key) { + var entry = getEntry(key); + return entry == null ? null : entry.getValue(); + } - protected AbstractObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - } + @Override + public @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullSupplier factory) { - @Override - protected @NotNull Class> getEntryType() { - return ObjectEntry.class; + var entry = getEntry(key); + + if (entry == null) { + put(key, factory.get()); + entry = getEntry(key); } - /** - * Add new entry to this dictionary. - * - * @param hash the hash of the key. - * @param key the key. - * @param value the value of the key. - * @param index the index of bucket. - */ - private void addEntry(int hash, K key, V value, int index) { + if (entry == null) { + throw new IllegalStateException("Factory " + factory + " returned a null value."); + } - var entries = entries(); - var entry = entries[index]; + //noinspection ConstantConditions + return entry.getValue(); + } - var newEntry = entryPool.take(ObjectEntry::new); - newEntry.set(hash, key, value, entry); + @Override + public @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullFunction factory) { - entries[index] = newEntry; + var entry = getEntry(key); - if (incrementSizeAndGet() >= getThreshold()) { - resize(2 * entries.length); - } + if (entry == null) { + put(key, factory.apply(key)); + entry = getEntry(key); } - @Override - public final boolean containsKey(@NotNull K key) { - return getEntry(key) != null; + if (entry == null) { + throw new IllegalStateException("Factory " + factory + " returned a null value."); } - @Override - public @Nullable V get(@NotNull K key) { - var entry = getEntry(key); - return entry == null ? null : entry.getValue(); - } - - @Override - public @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullSupplier factory) { + //noinspection ConstantConditions + return entry.getValue(); + } - var entry = getEntry(key); + @Override + public @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullFunction factory) { - if (entry == null) { - put(key, factory.get()); - entry = getEntry(key); - } + var entry = getEntry(key); - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } + if (entry == null) { + put(key, factory.apply(argument)); + entry = getEntry(key); + } - //noinspection ConstantConditions - return entry.getValue(); + if (entry == null) { + throw new IllegalStateException("Factory " + factory + " returned a null value."); } - @Override - public @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullFunction factory) { + //noinspection ConstantConditions + return entry.getValue(); + } - var entry = getEntry(key); + @Override + public @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullBiFunction factory) { - if (entry == null) { - put(key, factory.apply(key)); - entry = getEntry(key); - } + var entry = getEntry(key); - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } + if (entry == null) { + put(key, factory.apply(key, argument)); + entry = getEntry(key); + } - //noinspection ConstantConditions - return entry.getValue(); + if (entry == null) { + throw new IllegalStateException("Factory " + factory + " returned a null value."); } - @Override - public @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullFunction factory) { + //noinspection ConstantConditions + return entry.getValue(); + } - var entry = getEntry(key); + /** + * Get an entry for the key. + * + * @param key the key. + * @return the entry or null. + */ + private @Nullable ObjectEntry getEntry(K key) { - if (entry == null) { - put(key, factory.apply(argument)); - entry = getEntry(key); - } + var entries = entries(); - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } + var hash = hash(key.hashCode()); + var entryIndex = indexFor(hash, entries.length); - //noinspection ConstantConditions - return entry.getValue(); + for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { + if (entry.getHash() == hash && key.equals(entry.getKey())) { + return entry; + } } - @Override - public @NotNull V getOrCompute( - @NotNull K key, - @NotNull T argument, - @NotNull NotNullBiFunction factory - ) { + return null; + } - var entry = getEntry(key); + @Override + public final Iterator iterator() { + return new ObjectDictionaryIterator<>(this); + } - if (entry == null) { - put(key, factory.apply(key, argument)); - entry = getEntry(key); - } + @Override + public final @NotNull Array keyArray(@NotNull Array container) { - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } + var unsafeArray = container.asUnsafe(); + unsafeArray.prepareForSize(container.size() + size()); + for (var entry : entries()) { + while (entry != null) { //noinspection ConstantConditions - return entry.getValue(); + unsafeArray.unsafeAdd(entry.getKey()); + entry = entry.getNext(); + } } - /** - * Get an entry for the key. - * - * @param key the key. - * @return the entry or null. - */ - private @Nullable ObjectEntry getEntry(K key) { - - var entries = entries(); - - var hash = hash(key.hashCode()); - var entryIndex = indexFor(hash, entries.length); - - for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key.equals(entry.getKey())) { - return entry; - } - } + return container; + } - return null; - } + @Override + public void copyTo(@NotNull Dictionary dictionary) { - @Override - public final Iterator iterator() { - return new ObjectDictionaryIterator<>(this); + if (isEmpty() || !(dictionary instanceof ObjectDictionary)) { + return; } - @Override - public final @NotNull Array keyArray(@NotNull Array container) { - - var unsafeArray = container.asUnsafe(); - unsafeArray.prepareForSize(container.size() + size()); - - for (var entry : entries()) { - while (entry != null) { - //noinspection ConstantConditions - unsafeArray.unsafeAdd(entry.getKey()); - entry = entry.getNext(); - } - } + var target = ClassUtils.>unsafeNNCast(dictionary); - return container; + for (var entry : entries()) { + while (entry != null) { + //noinspection ConstantConditions + target.put(entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } } + } - @Override - public void copyTo(@NotNull Dictionary dictionary) { + @Override + public @Nullable V put(@NotNull K key, @NotNull V value) { - if (isEmpty() || !(dictionary instanceof ObjectDictionary)) { - return; - } + var entries = entries(); - var target = ClassUtils.>unsafeNNCast(dictionary); + var hash = hash(key.hashCode()); + var entryIndex = indexFor(hash, entries.length); - for (var entry : entries()) { - while (entry != null) { - //noinspection ConstantConditions - target.put(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } + for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { + if (entry.getHash() == hash && key.equals(entry.getKey())) { + return entry.setValue(value); + } } - @Override - public @Nullable V put(@NotNull K key, @NotNull V value) { + addEntry(hash, key, value, entryIndex); + return null; + } - var entries = entries(); + @Override + public @Nullable V remove(@NotNull K key) { - var hash = hash(key.hashCode()); - var entryIndex = indexFor(hash, entries.length); + var old = removeEntryForKey(key); - for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key.equals(entry.getKey())) { - return entry.setValue(value); - } - } - - addEntry(hash, key, value, entryIndex); - return null; + if (old == null) { + return null; } - @Override - public @Nullable V remove(@NotNull K key) { - - var old = removeEntryForKey(key); - - if (old == null) { - return null; - } - - var value = old.getValue(); + var value = old.getValue(); - entryPool.put(old); + entryPool.put(old); - return value; - } - - @Override - public @Nullable ObjectEntry removeEntryForKey(@NotNull K key) { + return value; + } - var entries = entries(); + @Override + public @Nullable ObjectEntry removeEntryForKey(@NotNull K key) { - var hash = hash(key.hashCode()); - var entryIndex = indexFor(hash, entries.length); + var entries = entries(); - var prev = entries[entryIndex]; - var entry = prev; + var hash = hash(key.hashCode()); + var entryIndex = indexFor(hash, entries.length); - while (entry != null) { + var prev = entries[entryIndex]; + var entry = prev; - var next = entry.getNext(); + while (entry != null) { - if (entry.getHash() == hash && key.equals(entry.getKey())) { - decrementSizeAndGet(); + var next = entry.getNext(); - if (prev == entry) { - entries[entryIndex] = next; - } else { - prev.setNext(next); - } + if (entry.getHash() == hash && key.equals(entry.getKey())) { + decrementSizeAndGet(); - return entry; - } - - prev = entry; - entry = next; + if (prev == entry) { + entries[entryIndex] = next; + } else { + prev.setNext(next); } - return null; - } + return entry; + } - @Override - public final String toString() { + prev = entry; + entry = next; + } - int size = size(); + return null; + } - var builder = new StringBuilder(getClass().getSimpleName()) - .append(" size = ") - .append(size) - .append(" : "); + @Override + public final String toString() { - var entries = entries(); + int size = size(); - for (var entry : entries) { - while (entry != null) { - builder - .append("[") - .append(entry.getKey()) - .append(" - ") - .append(entry.getValue()) - .append("]\n"); - entry = entry.getNext(); - } - } + var builder = new StringBuilder(getClass().getSimpleName()) + .append(" size = ") + .append(size) + .append(" : "); - if (size > 0) { - builder.replace(builder.length() - 1, builder.length(), "."); - } + var entries = entries(); - return builder.toString(); + for (var entry : entries) { + while (entry != null) { + builder + .append("[") + .append(entry.getKey()) + .append(" - ") + .append(entry.getValue()) + .append("]\n"); + entry = entry.getNext(); + } } - @Override - public void forEach(@NotNull NotNullBiConsumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } + if (size > 0) { + builder.replace(builder.length() - 1, builder.length(), "."); } - @Override - public void forEach( - @NotNull T argument, - @NotNull NotNullTripleConsumer consumer - ) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(argument, entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } + return builder.toString(); + } - @Override - public void forEach( - @NotNull F first, - @NotNull S second, - @NotNull FourObjectConsumer<@NotNull ? super F, @NotNull ? super S, @NotNull ? super K, @NotNull ? super V> consumer - ) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(first, second, entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } + @Override + public void forEach(@NotNull NotNullBiConsumer consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } + } + } + + @Override + public void forEach( + @NotNull T argument, + @NotNull NotNullTripleConsumer consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(argument, entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } + } + } + + @Override + public void forEach( + @NotNull F first, + @NotNull S second, + @NotNull FourObjectConsumer<@NotNull ? super F, @NotNull ? super S, @NotNull ? super K, @NotNull ? super V> consumer) { + for (var entry : entries()) { + while (entry != null) { + consumer.accept(first, second, entry.getKey(), entry.getValue()); + entry = entry.getNext(); + } } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java index c54cc384..b6d3d785 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java @@ -5,58 +5,57 @@ import org.jetbrains.annotations.NotNull; /** - * The implementation of the {@link ConcurrentIntegerDictionary} using {@link - * LockFactory#newAtomicARSWLock()}*. + * The implementation of the {@link ConcurrentIntegerDictionary} using {@link LockFactory#newAtomicARSWLock()}*. * * @param the type parameter * @author JavaSaBr */ public class ConcurrentAtomicARSWLockIntegerDictionary extends AbstractConcurrentIntegerDictionary { - /** - * The lock. - */ - @NotNull - private final AsyncReadSyncWriteLock lock; - - public ConcurrentAtomicARSWLockIntegerDictionary() { - this.lock = LockFactory.newAtomicARSWLock(); - } - - public ConcurrentAtomicARSWLockIntegerDictionary(float loadFactor) { - super(loadFactor); - this.lock = LockFactory.newAtomicARSWLock(); - } - - public ConcurrentAtomicARSWLockIntegerDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.lock = LockFactory.newAtomicARSWLock(); - } - - public ConcurrentAtomicARSWLockIntegerDictionary(int initCapacity) { - super(initCapacity); - this.lock = LockFactory.newAtomicARSWLock(); - } - - @Override - public long readLock() { - lock.asyncLock(); - return 0; - } - - @Override - public void readUnlock(long stamp) { - lock.asyncUnlock(); - } - - @Override - public void writeUnlock(long stamp) { - lock.syncUnlock(); - } - - @Override - public long writeLock() { - lock.syncLock(); - return 0; - } + /** + * The lock. + */ + @NotNull + private final AsyncReadSyncWriteLock lock; + + public ConcurrentAtomicARSWLockIntegerDictionary() { + this.lock = LockFactory.newAtomicARSWLock(); + } + + public ConcurrentAtomicARSWLockIntegerDictionary(float loadFactor) { + super(loadFactor); + this.lock = LockFactory.newAtomicARSWLock(); + } + + public ConcurrentAtomicARSWLockIntegerDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.lock = LockFactory.newAtomicARSWLock(); + } + + public ConcurrentAtomicARSWLockIntegerDictionary(int initCapacity) { + super(initCapacity); + this.lock = LockFactory.newAtomicARSWLock(); + } + + @Override + public long readLock() { + lock.asyncLock(); + return 0; + } + + @Override + public void readUnlock(long stamp) { + lock.asyncUnlock(); + } + + @Override + public void writeUnlock(long stamp) { + lock.syncUnlock(); + } + + @Override + public long writeLock() { + lock.syncLock(); + return 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java index b98e851c..a6088201 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java @@ -5,63 +5,62 @@ import org.jetbrains.annotations.NotNull; /** - * The implementation of the {@link ConcurrentLongDictionary} using {@link - * LockFactory#newAtomicARSWLock()}*. + * The implementation of the {@link ConcurrentLongDictionary} using {@link LockFactory#newAtomicARSWLock()}*. * * @param the type parameter * @author JavaSaBr */ public class ConcurrentAtomicARSWLockLongDictionary extends AbstractConcurrentLongDictionary { - /** - * The lock. - */ - @NotNull - private final AsyncReadSyncWriteLock lock; + /** + * The lock. + */ + @NotNull + private final AsyncReadSyncWriteLock lock; - public ConcurrentAtomicARSWLockLongDictionary() { - this.lock = LockFactory.newAtomicARSWLock(); - } + public ConcurrentAtomicARSWLockLongDictionary() { + this.lock = LockFactory.newAtomicARSWLock(); + } - public ConcurrentAtomicARSWLockLongDictionary(float loadFactor) { - super(loadFactor); - this.lock = LockFactory.newAtomicARSWLock(); - } + public ConcurrentAtomicARSWLockLongDictionary(float loadFactor) { + super(loadFactor); + this.lock = LockFactory.newAtomicARSWLock(); + } - public ConcurrentAtomicARSWLockLongDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.lock = LockFactory.newAtomicARSWLock(); - } + public ConcurrentAtomicARSWLockLongDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.lock = LockFactory.newAtomicARSWLock(); + } - /** - * Instantiates a new Concurrent atomic arsw lock long dictionary. - * - * @param initCapacity the init capacity - */ - public ConcurrentAtomicARSWLockLongDictionary(final int initCapacity) { - super(initCapacity); - this.lock = LockFactory.newAtomicARSWLock(); - } + /** + * Instantiates a new Concurrent atomic arsw lock long dictionary. + * + * @param initCapacity the init capacity + */ + public ConcurrentAtomicARSWLockLongDictionary(final int initCapacity) { + super(initCapacity); + this.lock = LockFactory.newAtomicARSWLock(); + } - @Override - public long readLock() { - lock.asyncLock(); - return 0; - } + @Override + public long readLock() { + lock.asyncLock(); + return 0; + } - @Override - public void readUnlock(final long stamp) { - lock.asyncUnlock(); - } + @Override + public void readUnlock(final long stamp) { + lock.asyncUnlock(); + } - @Override - public void writeUnlock(final long stamp) { - lock.syncUnlock(); - } + @Override + public void writeUnlock(final long stamp) { + lock.syncUnlock(); + } - @Override - public long writeLock() { - lock.syncLock(); - return 0; - } + @Override + public long writeLock() { + lock.syncLock(); + return 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java index ff283920..305b0b13 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java @@ -5,8 +5,7 @@ import org.jetbrains.annotations.NotNull; /** - * The implementation of the {@link ConcurrentObjectDictionary} using {@link - * LockFactory#newAtomicARSWLock()}*. + * The implementation of the {@link ConcurrentObjectDictionary} using {@link LockFactory#newAtomicARSWLock()}*. * * @param the key's type. * @param the value's type. @@ -14,50 +13,50 @@ */ public class ConcurrentAtomicARSWLockObjectDictionary extends AbstractConcurrentObjectDictionary { - /** - * The lock. - */ - @NotNull - private final AsyncReadSyncWriteLock lock; - - public ConcurrentAtomicARSWLockObjectDictionary() { - this.lock = LockFactory.newAtomicARSWLock(); - } - - public ConcurrentAtomicARSWLockObjectDictionary(float loadFactor) { - super(loadFactor); - this.lock = LockFactory.newAtomicARSWLock(); - } - - public ConcurrentAtomicARSWLockObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.lock = LockFactory.newAtomicARSWLock(); - } - - public ConcurrentAtomicARSWLockObjectDictionary(int initCapacity) { - super(initCapacity); - this.lock = LockFactory.newAtomicARSWLock(); - } - - @Override - public long readLock() { - lock.asyncLock(); - return 0; - } - - @Override - public void readUnlock(long stamp) { - lock.asyncUnlock(); - } - - @Override - public void writeUnlock(long stamp) { - lock.syncUnlock(); - } - - @Override - public long writeLock() { - lock.syncLock(); - return 0; - } + /** + * The lock. + */ + @NotNull + private final AsyncReadSyncWriteLock lock; + + public ConcurrentAtomicARSWLockObjectDictionary() { + this.lock = LockFactory.newAtomicARSWLock(); + } + + public ConcurrentAtomicARSWLockObjectDictionary(float loadFactor) { + super(loadFactor); + this.lock = LockFactory.newAtomicARSWLock(); + } + + public ConcurrentAtomicARSWLockObjectDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.lock = LockFactory.newAtomicARSWLock(); + } + + public ConcurrentAtomicARSWLockObjectDictionary(int initCapacity) { + super(initCapacity); + this.lock = LockFactory.newAtomicARSWLock(); + } + + @Override + public long readLock() { + lock.asyncLock(); + return 0; + } + + @Override + public void readUnlock(long stamp) { + lock.asyncUnlock(); + } + + @Override + public void writeUnlock(long stamp) { + lock.syncUnlock(); + } + + @Override + public long writeLock() { + lock.syncLock(); + return 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java index faacd348..76550dbd 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java @@ -9,58 +9,58 @@ */ public interface ConcurrentDictionary extends Dictionary { - /** - * Lock this dictionary for reading. - * - * @return the stamp of read lock or 0. - */ - default long readLock() { - throw new UnsupportedOperationException(); - } + /** + * Lock this dictionary for reading. + * + * @return the stamp of read lock or 0. + */ + default long readLock() { + throw new UnsupportedOperationException(); + } - /** - * Unlock the read lock. - * - * @param stamp the stamp of read lock. - */ - default void readUnlock(long stamp) { - throw new UnsupportedOperationException(); - } + /** + * Unlock the read lock. + * + * @param stamp the stamp of read lock. + */ + default void readUnlock(long stamp) { + throw new UnsupportedOperationException(); + } - /** - * Try to optimistic read. - * - * @return the stamp of optimistic read or 0 if it was failed. - */ - default long tryOptimisticRead() { - throw new UnsupportedOperationException(); - } + /** + * Try to optimistic read. + * + * @return the stamp of optimistic read or 0 if it was failed. + */ + default long tryOptimisticRead() { + throw new UnsupportedOperationException(); + } - /** - * Validate this stamp. - * - * @param stamp the stamp. - * @return true is this stamp is valid. - */ - default boolean validate(long stamp) { - throw new UnsupportedOperationException(); - } + /** + * Validate this stamp. + * + * @param stamp the stamp. + * @return true is this stamp is valid. + */ + default boolean validate(long stamp) { + throw new UnsupportedOperationException(); + } - /** - * Lock this array for writing. - * - * @return the stamp of write lock or 0. - */ - default long writeLock() { - throw new UnsupportedOperationException(); - } + /** + * Lock this array for writing. + * + * @return the stamp of write lock or 0. + */ + default long writeLock() { + throw new UnsupportedOperationException(); + } - /** - * Unlock the write lock. - * - * @param stamp the stamp of write lock. - */ - default void writeUnlock(long stamp) { - throw new UnsupportedOperationException(); - } + /** + * Unlock the write lock. + * + * @param stamp the stamp of write lock. + */ + default void writeUnlock(long stamp) { + throw new UnsupportedOperationException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java index ebc16bf6..8aaf2f3f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java @@ -10,14 +10,14 @@ */ public interface ConcurrentIntegerDictionary extends IntegerDictionary, ConcurrentDictionary { - /** - * Create a new concurrent integer dictionary for the value's type. - * - * @param valueType the value's type. - * @param the value's type. - * @return the new concurrent integer dictionary. - */ - static @NotNull ConcurrentIntegerDictionary ofType(@NotNull Class valueType) { - return DictionaryFactory.newConcurrentAtomicIntegerDictionary(); - } + /** + * Create a new concurrent integer dictionary for the value's type. + * + * @param valueType the value's type. + * @param the value's type. + * @return the new concurrent integer dictionary. + */ + static @NotNull ConcurrentIntegerDictionary ofType(@NotNull Class valueType) { + return DictionaryFactory.newConcurrentAtomicIntegerDictionary(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java index f3961140..228a121f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java @@ -10,14 +10,14 @@ */ public interface ConcurrentLongDictionary extends LongDictionary, ConcurrentDictionary { - /** - * Create a new concurrent long dictionary for the value's type. - * - * @param valueType the value's type. - * @param the value's type. - * @return the new concurrent long dictionary. - */ - static @NotNull ConcurrentLongDictionary ofType(@NotNull Class valueType) { - return DictionaryFactory.newConcurrentAtomicLongDictionary(); - } + /** + * Create a new concurrent long dictionary for the value's type. + * + * @param valueType the value's type. + * @param the value's type. + * @return the new concurrent long dictionary. + */ + static @NotNull ConcurrentLongDictionary ofType(@NotNull Class valueType) { + return DictionaryFactory.newConcurrentAtomicLongDictionary(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java index 12daf556..891ada2e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java @@ -17,226 +17,217 @@ */ public interface ConcurrentObjectDictionary extends ObjectDictionary, ConcurrentDictionary { - /** - * Create a new concurrent object dictionary for the key's type and value's type. - * - * @param keyValueType the key's and value's type. - * @param the key's and value's type. - * @return the new concurrent object dictionary. - */ - static @NotNull ObjectDictionary ofType(@NotNull Class keyValueType) { - return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); + /** + * Create a new concurrent object dictionary for the key's type and value's type. + * + * @param keyValueType the key's and value's type. + * @param the key's and value's type. + * @return the new concurrent object dictionary. + */ + static @NotNull ObjectDictionary ofType(@NotNull Class keyValueType) { + return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); + } + + /** + * Create a new concurrent object dictionary for the key's type and value's type. + * + * @param keyType the key's type. + * @param valueType the value's type. + * @param the key's type. + * @param the value's type. + * @return the new concurrent object dictionary. + */ + static @NotNull ConcurrentObjectDictionary ofType( + @NotNull Class keyType, + @NotNull Class valueType) { + return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); + } + + /** + * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. + * + * @param argument the argument. + * @param consumer the function. + * @param the argument's type. + * @return this dictionary. + */ + default @NotNull ConcurrentObjectDictionary runInReadLock( + @NotNull A argument, + @NotNull NotNullBiConsumer, A> consumer) { + + var stamp = readLock(); + try { + consumer.accept(this, argument); + } finally { + readUnlock(stamp); } - /** - * Create a new concurrent object dictionary for the key's type and value's type. - * - * @param keyType the key's type. - * @param valueType the value's type. - * @param the key's type. - * @param the value's type. - * @return the new concurrent object dictionary. - */ - static @NotNull ConcurrentObjectDictionary ofType( - @NotNull Class keyType, - @NotNull Class valueType - ) { - return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); + return this; + } + + /** + * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. + * + * @param consumer the function. + * @return this dictionary. + */ + default @NotNull ConcurrentObjectDictionary runInWriteLock( + @NotNull NotNullConsumer> consumer) { + + var stamp = writeLock(); + try { + consumer.accept(this); + } finally { + writeUnlock(stamp); } - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. - * - * @param argument the argument. - * @param consumer the function. - * @param the argument's type. - * @return this dictionary. - */ - default @NotNull ConcurrentObjectDictionary runInReadLock( - @NotNull A argument, - @NotNull NotNullBiConsumer, A> consumer - ) { - - var stamp = readLock(); - try { - consumer.accept(this, argument); - } finally { - readUnlock(stamp); - } - - return this; + return this; + } + + /** + * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. + * + * @param argument the argument. + * @param consumer the function. + * @param the argument's type. + * @return this dictionary. + */ + default @NotNull ConcurrentObjectDictionary runInWriteLock( + @NotNull A argument, + @NotNull NotNullBiConsumer, A> consumer) { + + var stamp = writeLock(); + try { + consumer.accept(this, argument); + } finally { + writeUnlock(stamp); } - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param consumer the function. - * @return this dictionary. - */ - default @NotNull ConcurrentObjectDictionary runInWriteLock( - @NotNull NotNullConsumer> consumer - ) { - - var stamp = writeLock(); - try { - consumer.accept(this); - } finally { - writeUnlock(stamp); - } - - return this; + return this; + } + + /** + * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the function. + * @param the first argument's type. + * @param the second argument's type. + * @return this dictionary. + */ + default @NotNull ConcurrentObjectDictionary runInWriteLock( + @NotNull F first, + @NotNull S second, + @NotNull NotNullTripleConsumer, F, S> consumer) { + + var stamp = writeLock(); + try { + consumer.accept(this, first, second); + } finally { + writeUnlock(stamp); } - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param argument the argument. - * @param consumer the function. - * @param the argument's type. - * @return this dictionary. - */ - default @NotNull ConcurrentObjectDictionary runInWriteLock( - @NotNull A argument, - @NotNull NotNullBiConsumer, A> consumer - ) { - - var stamp = writeLock(); - try { - consumer.accept(this, argument); - } finally { - writeUnlock(stamp); - } - - return this; + return this; + } + + /** + * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. + * + * @param argument the argument. + * @param function the function. + * @param the argument's type. + * @param the result's type. + * @return the result of the function. + */ + default @Nullable R getInReadLock( + @NotNull A argument, + @NotNull NotNullNullableBiFunction, A, R> function) { + var stamp = readLock(); + try { + return function.apply(this, argument); + } finally { + readUnlock(stamp); } - - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the first argument's type. - * @param the second argument's type. - * @return this dictionary. - */ - default @NotNull ConcurrentObjectDictionary runInWriteLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer, F, S> consumer - ) { - - var stamp = writeLock(); - try { - consumer.accept(this, first, second); - } finally { - writeUnlock(stamp); - } - - return this; - } - - /** - * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result of the function. - */ - default @Nullable R getInReadLock( - @NotNull A argument, - @NotNull NotNullNullableBiFunction, A, R> function - ) { - var stamp = readLock(); - try { - return function.apply(this, argument); - } finally { - readUnlock(stamp); - } - } - - /** - * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result of the function. - */ - default @Nullable R getInReadLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullNullableTripleFunction, F, S, R> function - ) { - var stamp = readLock(); - try { - return function.apply(this, first, second); - } finally { - readUnlock(stamp); - } + } + + /** + * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. + * + * @param first the first argument. + * @param second the second argument. + * @param function the function. + * @param the first argument's type. + * @param the second argument's type. + * @param the result's type. + * @return the result of the function. + */ + default @Nullable R getInReadLock( + @NotNull F first, + @NotNull S second, + @NotNull NotNullNullableTripleFunction, F, S, R> function) { + var stamp = readLock(); + try { + return function.apply(this, first, second); + } finally { + readUnlock(stamp); } - - /** - * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result of the function. - */ - default @Nullable R getInWriteLock( - @NotNull A argument, - @NotNull NotNullNullableBiFunction, A, R> function - ) { - var stamp = writeLock(); - try { - return function.apply(this, argument); - } finally { - writeUnlock(stamp); - } + } + + /** + * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. + * + * @param argument the argument. + * @param function the function. + * @param the argument's type. + * @param the result's type. + * @return the result of the function. + */ + default @Nullable R getInWriteLock( + @NotNull A argument, + @NotNull NotNullNullableBiFunction, A, R> function) { + var stamp = writeLock(); + try { + return function.apply(this, argument); + } finally { + writeUnlock(stamp); } - - /** - * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result of the function. - */ - default @Nullable R getInWriteLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullNullableTripleFunction, F, S, R> function - ) { - var stamp = writeLock(); - try { - return function.apply(this, first, second); - } finally { - writeUnlock(stamp); - } + } + + /** + * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. + * + * @param first the first argument. + * @param second the second argument. + * @param function the function. + * @param the first argument's type. + * @param the second argument's type. + * @param the result's type. + * @return the result of the function. + */ + default @Nullable R getInWriteLock( + @NotNull F first, + @NotNull S second, + @NotNull NotNullNullableTripleFunction, F, S, R> function) { + var stamp = writeLock(); + try { + return function.apply(this, first, second); + } finally { + writeUnlock(stamp); } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param consumer the consumer. - */ - default void forEachInReadLock(@NotNull NotNullBiConsumer consumer) { - var stamp = readLock(); - try { - forEach(consumer); - } finally { - readUnlock(stamp); - } + } + + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param consumer the consumer. + */ + default void forEachInReadLock(@NotNull NotNullBiConsumer consumer) { + var stamp = readLock(); + try { + forEach(consumer); + } finally { + readUnlock(stamp); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java index f36c7d25..4cb9c7d5 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java @@ -5,8 +5,7 @@ import org.jetbrains.annotations.NotNull; /** - * The implementation of the {@link ConcurrentObjectDictionary} using {@link - * LockFactory#newAtomicARSWLock()}*. + * The implementation of the {@link ConcurrentObjectDictionary} using {@link LockFactory#newAtomicARSWLock()}*. * * @param the key's type. * @param the value's type. @@ -14,42 +13,42 @@ */ public class ConcurrentStampedLockObjectDictionary extends AbstractConcurrentObjectDictionary { - private final @NotNull StampedLock lock; + private final @NotNull StampedLock lock; - public ConcurrentStampedLockObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } + public ConcurrentStampedLockObjectDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } - public ConcurrentStampedLockObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } + public ConcurrentStampedLockObjectDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } - public ConcurrentStampedLockObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } + public ConcurrentStampedLockObjectDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } - public ConcurrentStampedLockObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.lock = new StampedLock(); - } + public ConcurrentStampedLockObjectDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.lock = new StampedLock(); + } - @Override - public long readLock() { - return lock.readLock(); - } + @Override + public long readLock() { + return lock.readLock(); + } - @Override - public void readUnlock(long stamp) { - lock.unlockRead(stamp); - } + @Override + public void readUnlock(long stamp) { + lock.unlockRead(stamp); + } - @Override - public void writeUnlock(long stamp) { - lock.unlockWrite(stamp); - } + @Override + public void writeUnlock(long stamp) { + lock.unlockWrite(stamp); + } - @Override - public long writeLock() { - return lock.writeLock(); - } + @Override + public long writeLock() { + return lock.writeLock(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java index 0984634a..f8fcda1f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java @@ -15,88 +15,88 @@ */ public interface Dictionary extends Iterable, Reusable { - /** - * Replace the all values using the function. - * - * @param function the function. - */ - default void apply(@NotNull NotNullFunction function) { - throw new UnsupportedOperationException(); - } + /** + * Replace the all values using the function. + * + * @param function the function. + */ + default void apply(@NotNull NotNullFunction function) { + throw new UnsupportedOperationException(); + } - /** - * Clear this dictionary. - */ - default void clear() { - throw new UnsupportedOperationException(); - } + /** + * Clear this dictionary. + */ + default void clear() { + throw new UnsupportedOperationException(); + } - /** - * Return true if this dictionary contains the value. - * - * @param value the value. - * @return true if this dictionary contains the value. - */ - default boolean containsValue(@NotNull V value) { - throw new UnsupportedOperationException(); - } + /** + * Return true if this dictionary contains the value. + * + * @param value the value. + * @return true if this dictionary contains the value. + */ + default boolean containsValue(@NotNull V value) { + throw new UnsupportedOperationException(); + } - @Override - default void free() { - clear(); - } + @Override + default void free() { + clear(); + } - /** - * Returns true if this dictionary contains no key-value mappings. - * - * @return true if this dictionary contains no key-value mappings - */ - default boolean isEmpty() { - return size() == 0; - } + /** + * Returns true if this dictionary contains no key-value mappings. + * + * @return true if this dictionary contains no key-value mappings + */ + default boolean isEmpty() { + return size() == 0; + } - /** - * Put all data from this dictionary to the dictionary. - * - * @param dictionary the dictionary. - */ - void copyTo(@NotNull Dictionary dictionary); + /** + * Put all data from this dictionary to the dictionary. + * + * @param dictionary the dictionary. + */ + void copyTo(@NotNull Dictionary dictionary); - /** - * Put all data from the dictionary to this dictionary. - * - * @param dictionary the dictionary with new data. - */ - default void put(@NotNull Dictionary dictionary) { - dictionary.copyTo(this); - } + /** + * Put all data from the dictionary to this dictionary. + * + * @param dictionary the dictionary with new data. + */ + default void put(@NotNull Dictionary dictionary) { + dictionary.copyTo(this); + } - /** - * Return the number of key-value mappings in this dictionary. - * - * @return the number of key-value mappings in this dictionary. - */ - default int size() { - throw new UnsupportedOperationException(); - } + /** + * Return the number of key-value mappings in this dictionary. + * + * @return the number of key-value mappings in this dictionary. + */ + default int size() { + throw new UnsupportedOperationException(); + } - /** - * Collect all values from this dictionary. - * - * @param container the container to store the values. - * @return the container with all values from this dictionary. - */ - default @NotNull Array values(@NotNull Array container) { - throw new UnsupportedOperationException(); - } + /** + * Collect all values from this dictionary. + * + * @param container the container to store the values. + * @return the container with all values from this dictionary. + */ + default @NotNull Array values(@NotNull Array container) { + throw new UnsupportedOperationException(); + } - /** - * Collect all values from this dictionary. - * - * @param type the value's type. - * @return the array with all values from this dictionary. - */ - default @NotNull Array values(@NotNull Class type) { - return values(ArrayFactory.newArray(type, size())); - } + /** + * Collect all values from this dictionary. + * + * @param type the value's type. + * @return the array with all values from this dictionary. + */ + default @NotNull Array values(@NotNull Class type) { + return values(ArrayFactory.newArray(type, size())); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java index 8392703a..c9210731 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java @@ -20,165 +20,152 @@ */ public final class DictionaryCollectors { - static final Set CH_ID = - unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); - - /** - * Simple implementation class for {@code Collector}. - * - * @param the type of elements to be collected - * @param the type of the result - */ - static class CollectorImpl implements Collector { - - private final Supplier supplier; - private final BiConsumer accumulator; - private final BinaryOperator combiner; - private final Function finisher; - private final Set characteristics; - - CollectorImpl( - @NotNull Supplier supplier, - @NotNull BiConsumer accumulator, - @NotNull BinaryOperator combiner, - @NotNull Function finisher, - @NotNull Set characteristics - ) { - this.supplier = supplier; - this.accumulator = accumulator; - this.combiner = combiner; - this.finisher = finisher; - this.characteristics = characteristics; - } - - CollectorImpl( - @NotNull Supplier supplier, - @NotNull BiConsumer accumulator, - @NotNull BinaryOperator combiner, - @NotNull Set characteristics - ) { - this(supplier, accumulator, combiner, a -> (R) a, characteristics); - } - - @Override - public BiConsumer accumulator() { - return accumulator; - } - - @Override - public Supplier supplier() { - return supplier; - } - - @Override - public BinaryOperator combiner() { - return combiner; - } - - @Override - public Function finisher() { - return finisher; - } - - @Override - public Set characteristics() { - return characteristics; - } + static final Set CH_ID = unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); + + /** + * Simple implementation class for {@code Collector}. + * + * @param the type of elements to be collected + * @param the type of the result + */ + static class CollectorImpl implements Collector { + + private final Supplier supplier; + private final BiConsumer accumulator; + private final BinaryOperator combiner; + private final Function finisher; + private final Set characteristics; + + CollectorImpl( + @NotNull Supplier supplier, + @NotNull BiConsumer accumulator, + @NotNull BinaryOperator combiner, + @NotNull Function finisher, + @NotNull Set characteristics) { + this.supplier = supplier; + this.accumulator = accumulator; + this.combiner = combiner; + this.finisher = finisher; + this.characteristics = characteristics; } - public static @NotNull Collector> toObjectDictionary( - @NotNull Function keyMapper, - @NotNull Function valueMapper - ) { - return new CollectorImpl<>( - DictionaryFactory::newObjectDictionary, - uniqKeysAccumulator(keyMapper, valueMapper), - ObjectDictionary::append, - CH_ID - ); + CollectorImpl( + @NotNull Supplier supplier, + @NotNull BiConsumer accumulator, + @NotNull BinaryOperator combiner, + @NotNull Set characteristics) { + this(supplier, accumulator, combiner, a -> (R) a, characteristics); } - public static @NotNull Collector> toLongDictionary( - @NotNull Function keyMapper, - @NotNull Function valueMapper - ) { - return new CollectorImpl<>( - DictionaryFactory::newLongDictionary, - uniqLongsAccumulator(keyMapper, valueMapper), - LongDictionary::append, - CH_ID - ); + @Override + public BiConsumer accumulator() { + return accumulator; } - /** - * {@code BiConsumer} that accumulates (key, value) pairs - * extracted from elements into the dictionary, throwing {@code IllegalStateException} - * if duplicate keys are encountered. - * - * @param keyMapper a function that dictionaries an element into a key. - * @param valueMapper a function that dictionaries an element into a value. - * @param type of elements. - * @param type of dictionaries keys. - * @param type of dictionaries values. - * @return an accumulating consumer. - */ - private static BiConsumer, T> uniqKeysAccumulator( - @NotNull Function keyMapper, - @NotNull Function valueMapper - ) { - return (map, element) -> { - - K key = keyMapper.apply(element); - V value = ObjectUtils.notNull(valueMapper.apply(element)); - V prev = map.put(key, value); - - if (prev != null) { - throw duplicateKeyException(key, prev, value); - } - }; + @Override + public Supplier supplier() { + return supplier; } - /** - * {@code BiConsumer} that accumulates (key, value) pairs - * extracted from elements into the dictionary, throwing {@code IllegalStateException} - * if duplicate keys are encountered. - * - * @param keyMapper a function that dictionaries an element into a key. - * @param valueMapper a function that dictionaries an element into a value. - * @param type of elements. - * @param type of dictionaries values. - * @return an accumulating consumer. - */ - private static BiConsumer, T> uniqLongsAccumulator( - @NotNull Function keyMapper, - @NotNull Function valueMapper - ) { - return (map, element) -> { - - var key = keyMapper.apply(element); - var value = ObjectUtils.notNull(valueMapper.apply(element)); - var prevValue = map.put(key.longValue(), value); - - if (prevValue != null) { - throw duplicateKeyException(key, prevValue, value); - } - }; + @Override + public BinaryOperator combiner() { + return combiner; } - /** - * Construct an {@code IllegalStateException} with appropriate message. - * - * @param k the duplicate key - * @param u 1st value to be accumulated/merged - * @param v 2nd value to be accumulated/merged - */ - private static IllegalStateException duplicateKeyException(Object k, Object u, Object v) { - return new IllegalStateException( - String.format("Duplicate key %s (attempted merging values %s and %s)", k, u, v) - ); + @Override + public Function finisher() { + return finisher; } - private DictionaryCollectors() { - throw new IllegalArgumentException(); + @Override + public Set characteristics() { + return characteristics; } + } + + public static @NotNull Collector> toObjectDictionary( + @NotNull Function keyMapper, + @NotNull Function valueMapper) { + return new CollectorImpl<>( + DictionaryFactory::newObjectDictionary, + uniqKeysAccumulator(keyMapper, valueMapper), + ObjectDictionary::append, + CH_ID); + } + + public static @NotNull Collector> toLongDictionary( + @NotNull Function keyMapper, + @NotNull Function valueMapper) { + return new CollectorImpl<>( + DictionaryFactory::newLongDictionary, + uniqLongsAccumulator(keyMapper, valueMapper), + LongDictionary::append, + CH_ID); + } + + /** + * {@code BiConsumer} that accumulates (key, value) pairs extracted from elements into the + * dictionary, throwing {@code IllegalStateException} if duplicate keys are encountered. + * + * @param keyMapper a function that dictionaries an element into a key. + * @param valueMapper a function that dictionaries an element into a value. + * @param type of elements. + * @param type of dictionaries keys. + * @param type of dictionaries values. + * @return an accumulating consumer. + */ + private static BiConsumer, T> uniqKeysAccumulator( + @NotNull Function keyMapper, + @NotNull Function valueMapper) { + return (map, element) -> { + + K key = keyMapper.apply(element); + V value = ObjectUtils.notNull(valueMapper.apply(element)); + V prev = map.put(key, value); + + if (prev != null) { + throw duplicateKeyException(key, prev, value); + } + }; + } + + /** + * {@code BiConsumer} that accumulates (key, value) pairs extracted from elements into the + * dictionary, throwing {@code IllegalStateException} if duplicate keys are encountered. + * + * @param keyMapper a function that dictionaries an element into a key. + * @param valueMapper a function that dictionaries an element into a value. + * @param type of elements. + * @param type of dictionaries values. + * @return an accumulating consumer. + */ + private static BiConsumer, T> uniqLongsAccumulator( + @NotNull Function keyMapper, + @NotNull Function valueMapper) { + return (map, element) -> { + + var key = keyMapper.apply(element); + var value = ObjectUtils.notNull(valueMapper.apply(element)); + var prevValue = map.put(key.longValue(), value); + + if (prevValue != null) { + throw duplicateKeyException(key, prevValue, value); + } + }; + } + + /** + * Construct an {@code IllegalStateException} with appropriate message. + * + * @param k the duplicate key + * @param u 1st value to be accumulated/merged + * @param v 2nd value to be accumulated/merged + */ + private static IllegalStateException duplicateKeyException(Object k, Object u, Object v) { + return new IllegalStateException(String.format("Duplicate key %s (attempted merging values %s and %s)", k, u, v)); + } + + private DictionaryCollectors() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java index a758c67a..7697650a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java @@ -9,86 +9,82 @@ */ public final class DictionaryFactory { - public static final ObjectDictionary EMPTY_OD = new ReadOnlyFastObjectDictionary<>(); - public static final LongDictionary EMPTY_LD = new ReadOnlyFastLongDictionary<>(); - - public static @NotNull ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary() { - return new ConcurrentAtomicARSWLockIntegerDictionary<>(); - } - - public static @NotNull ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary( - float loadFactor, - int initCapacity - ) { - return new ConcurrentAtomicARSWLockIntegerDictionary<>(loadFactor, initCapacity); - } - - public static @NotNull ConcurrentLongDictionary newConcurrentAtomicLongDictionary() { - return new ConcurrentAtomicARSWLockLongDictionary<>(); - } - - public static @NotNull ConcurrentLongDictionary newConcurrentAtomicLongDictionary( - float loadFactor, - int initCapacity - ) { - return new ConcurrentAtomicARSWLockLongDictionary<>(loadFactor, initCapacity); - } - - public static @NotNull ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary() { - return new ConcurrentAtomicARSWLockObjectDictionary<>(); - } - - public static @NotNull ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary( - float loadFactor, - int initCapacity - ) { - return new ConcurrentAtomicARSWLockObjectDictionary<>(loadFactor, initCapacity); - } - - public static @NotNull ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary() { - return new ConcurrentStampedLockObjectDictionary<>(); - } - - public static @NotNull ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary( - float loadFactor, - int initCapacity - ) { - return new ConcurrentStampedLockObjectDictionary<>(loadFactor, initCapacity); - } - - public static @NotNull IntegerDictionary newIntegerDictionary() { - return new FastIntegerDictionary<>(); - } - - public static @NotNull IntegerDictionary newIntegerDictionary(float loadFactor, int initCapacity) { - return new FastIntegerDictionary<>(loadFactor, initCapacity); - } - - public static @NotNull LongDictionary newLongDictionary() { - return new FastLongDictionary<>(); - } - - public static @NotNull LongDictionary newLongDictionary(int initCapacity) { - return new FastLongDictionary<>(initCapacity); - } - - public static @NotNull LongDictionary newLongDictionary(float loadFactor, int initCapacity) { - return new FastLongDictionary<>(loadFactor, initCapacity); - } - - public static @NotNull ObjectDictionary newObjectDictionary() { - return new FastObjectDictionary<>(); - } - - public static @NotNull ObjectDictionary newObjectDictionary(float loadFactor, int initCapacity) { - return new FastObjectDictionary<>(loadFactor, initCapacity); - } - - public static @NotNull ObjectDictionary newReadOnlyObjectDictionary(@NotNull Object... values) { - return new ReadOnlyFastObjectDictionary<>(values); - } - - private DictionaryFactory() { - throw new IllegalArgumentException(); - } + public static final ObjectDictionary EMPTY_OD = new ReadOnlyFastObjectDictionary<>(); + public static final LongDictionary EMPTY_LD = new ReadOnlyFastLongDictionary<>(); + + public static @NotNull ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary() { + return new ConcurrentAtomicARSWLockIntegerDictionary<>(); + } + + public static @NotNull ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary( + float loadFactor, + int initCapacity) { + return new ConcurrentAtomicARSWLockIntegerDictionary<>(loadFactor, initCapacity); + } + + public static @NotNull ConcurrentLongDictionary newConcurrentAtomicLongDictionary() { + return new ConcurrentAtomicARSWLockLongDictionary<>(); + } + + public static @NotNull ConcurrentLongDictionary newConcurrentAtomicLongDictionary( + float loadFactor, + int initCapacity) { + return new ConcurrentAtomicARSWLockLongDictionary<>(loadFactor, initCapacity); + } + + public static @NotNull ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary() { + return new ConcurrentAtomicARSWLockObjectDictionary<>(); + } + + public static @NotNull ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary( + float loadFactor, + int initCapacity) { + return new ConcurrentAtomicARSWLockObjectDictionary<>(loadFactor, initCapacity); + } + + public static @NotNull ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary() { + return new ConcurrentStampedLockObjectDictionary<>(); + } + + public static @NotNull ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary( + float loadFactor, + int initCapacity) { + return new ConcurrentStampedLockObjectDictionary<>(loadFactor, initCapacity); + } + + public static @NotNull IntegerDictionary newIntegerDictionary() { + return new FastIntegerDictionary<>(); + } + + public static @NotNull IntegerDictionary newIntegerDictionary(float loadFactor, int initCapacity) { + return new FastIntegerDictionary<>(loadFactor, initCapacity); + } + + public static @NotNull LongDictionary newLongDictionary() { + return new FastLongDictionary<>(); + } + + public static @NotNull LongDictionary newLongDictionary(int initCapacity) { + return new FastLongDictionary<>(initCapacity); + } + + public static @NotNull LongDictionary newLongDictionary(float loadFactor, int initCapacity) { + return new FastLongDictionary<>(loadFactor, initCapacity); + } + + public static @NotNull ObjectDictionary newObjectDictionary() { + return new FastObjectDictionary<>(); + } + + public static @NotNull ObjectDictionary newObjectDictionary(float loadFactor, int initCapacity) { + return new FastObjectDictionary<>(loadFactor, initCapacity); + } + + public static @NotNull ObjectDictionary newReadOnlyObjectDictionary(@NotNull Object... values) { + return new ReadOnlyFastObjectDictionary<>(values); + } + + private DictionaryFactory() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryUtils.java index c59abf44..e1bb15bc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryUtils.java @@ -3,5 +3,4 @@ /** * @author JavaSaBr */ -public class DictionaryUtils { -} +public class DictionaryUtils {} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java index 9e3e777a..9160b915 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java @@ -6,39 +6,39 @@ public interface Entry extends Reusable { - /** - * Get the next entry. - * - * @return the next entry. - */ - @Nullable T getNext(); + /** + * Get the next entry. + * + * @return the next entry. + */ + @Nullable T getNext(); - /** - * Set the next entry. - * - * @param next the next entry. - */ - void setNext(@Nullable T next); + /** + * Set the next entry. + * + * @param next the next entry. + */ + void setNext(@Nullable T next); - /** - * Get the value. - * - * @return the value. - */ - @NotNull V getValue(); + /** + * Get the value. + * + * @return the value. + */ + @NotNull V getValue(); - /** - * Set the value. - * - * @param value the new value of this entry. - * @return the old value of null. - */ - @NotNull V setValue(@NotNull V value); + /** + * Set the value. + * + * @param value the new value of this entry. + * @return the old value of null. + */ + @NotNull V setValue(@NotNull V value); - /** - * Get the hash. - * - * @return the hash. - */ - int getHash(); + /** + * Get the hash. + * + * @return the hash. + */ + int getHash(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java index 8dc40869..8d02b682 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java @@ -11,65 +11,65 @@ */ public class FastIntegerDictionary extends AbstractIntegerDictionary implements UnsafeIntegerDictionary { - private @NotNull IntegerEntry[] entries; - - private int threshold; - private int size; - - protected FastIntegerDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected FastIntegerDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected FastIntegerDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected FastIntegerDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - } - - @Override - public void setSize(int size) { - this.size = size; - } - - @Override - public void setEntries(@NotNull IntegerEntry[] entries) { - this.entries = entries; - } - - @Override - public IntegerEntry @NotNull [] entries() { - return entries; - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected int decrementSizeAndGet() { - return --size; - } - - @Override - protected int incrementSizeAndGet() { - return ++size; - } - - @Override - public final int size() { - return size; - } + private @NotNull IntegerEntry[] entries; + + private int threshold; + private int size; + + protected FastIntegerDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected FastIntegerDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected FastIntegerDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected FastIntegerDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.entries = ArrayUtils.create(getEntryType(), initCapacity); + } + + @Override + public void setSize(int size) { + this.size = size; + } + + @Override + public void setEntries(@NotNull IntegerEntry[] entries) { + this.entries = entries; + } + + @Override + public IntegerEntry @NotNull [] entries() { + return entries; + } + + @Override + public void setThreshold(int threshold) { + this.threshold = threshold; + } + + @Override + public int getThreshold() { + return threshold; + } + + @Override + protected int decrementSizeAndGet() { + return --size; + } + + @Override + protected int incrementSizeAndGet() { + return ++size; + } + + @Override + public final int size() { + return size; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java index db625f59..bc7d53ff 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java @@ -11,65 +11,65 @@ */ public class FastLongDictionary extends AbstractLongDictionary { - private @NotNull LongEntry[] entries; - - private int threshold; - private int size; - - protected FastLongDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected FastLongDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected FastLongDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected FastLongDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - } - - @Override - public void setSize(int size) { - this.size = size; - } - - @Override - public void setEntries(@NotNull LongEntry[] content) { - this.entries = content; - } - - @Override - public LongEntry @NotNull [] entries() { - return entries; - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected int decrementSizeAndGet() { - return --size; - } - - @Override - protected int incrementSizeAndGet() { - return ++size; - } - - @Override - public final int size() { - return size; - } + private @NotNull LongEntry[] entries; + + private int threshold; + private int size; + + protected FastLongDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected FastLongDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected FastLongDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected FastLongDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.entries = ArrayUtils.create(getEntryType(), initCapacity); + } + + @Override + public void setSize(int size) { + this.size = size; + } + + @Override + public void setEntries(@NotNull LongEntry[] content) { + this.entries = content; + } + + @Override + public LongEntry @NotNull [] entries() { + return entries; + } + + @Override + public void setThreshold(int threshold) { + this.threshold = threshold; + } + + @Override + public int getThreshold() { + return threshold; + } + + @Override + protected int decrementSizeAndGet() { + return --size; + } + + @Override + protected int incrementSizeAndGet() { + return ++size; + } + + @Override + public final int size() { + return size; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java index c11919fd..d168a606 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java @@ -12,65 +12,65 @@ */ public class FastObjectDictionary extends AbstractObjectDictionary { - private @NotNull ObjectEntry[] entries; - - private int threshold; - private int size; - - protected FastObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected FastObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected FastObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected FastObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - } - - @Override - public void setSize(int size) { - this.size = size; - } - - @Override - public void setEntries(@NotNull ObjectEntry[] entries) { - this.entries = entries; - } - - @Override - public ObjectEntry @NotNull [] entries() { - return entries; - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected int decrementSizeAndGet() { - return --size; - } - - @Override - protected int incrementSizeAndGet() { - return ++size; - } - - @Override - public int size() { - return size; - } + private @NotNull ObjectEntry[] entries; + + private int threshold; + private int size; + + protected FastObjectDictionary() { + this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); + } + + protected FastObjectDictionary(float loadFactor) { + this(loadFactor, DEFAULT_INITIAL_CAPACITY); + } + + protected FastObjectDictionary(int initCapacity) { + this(DEFAULT_LOAD_FACTOR, initCapacity); + } + + protected FastObjectDictionary(float loadFactor, int initCapacity) { + super(loadFactor, initCapacity); + this.entries = ArrayUtils.create(getEntryType(), initCapacity); + } + + @Override + public void setSize(int size) { + this.size = size; + } + + @Override + public void setEntries(@NotNull ObjectEntry[] entries) { + this.entries = entries; + } + + @Override + public ObjectEntry @NotNull [] entries() { + return entries; + } + + @Override + public void setThreshold(int threshold) { + this.threshold = threshold; + } + + @Override + public int getThreshold() { + return threshold; + } + + @Override + protected int decrementSizeAndGet() { + return --size; + } + + @Override + protected int incrementSizeAndGet() { + return ++size; + } + + @Override + public int size() { + return size; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntKey.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntKey.java index aa7e3d06..295277b3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntKey.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntKey.java @@ -7,7 +7,7 @@ */ public final class IntKey { - private IntKey() { - throw new IllegalArgumentException(); - } + private IntKey() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java index 85311548..8ef9270f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java @@ -19,178 +19,177 @@ */ public interface IntegerDictionary extends Dictionary { - /** - * Create a new integer dictionary for the value's type. - * - * @param valueType the value's type. - * @param the value's type. - * @return the new integer dictionary. - */ - static @NotNull IntegerDictionary ofType(@NotNull Class valueType) { - return DictionaryFactory.newIntegerDictionary(); + /** + * Create a new integer dictionary for the value's type. + * + * @param valueType the value's type. + * @param the value's type. + * @return the new integer dictionary. + */ + static @NotNull IntegerDictionary ofType(@NotNull Class valueType) { + return DictionaryFactory.newIntegerDictionary(); + } + + /** + * Create a new integer dictionary for the values. + * + * @param values the key-value values. + * @param the value's type. + * @return the new integer dictionary. + */ + static @NotNull IntegerDictionary of(@NotNull Object... values) { + + if (values.length < 2 || values.length % 2 != 0) { + throw new IllegalArgumentException("Incorrect argument's count."); } - /** - * Create a new integer dictionary for the values. - * - * @param values the key-value values. - * @param the value's type. - * @return the new integer dictionary. - */ - static @NotNull IntegerDictionary of(@NotNull Object... values) { + IntegerDictionary dictionary = DictionaryFactory.newIntegerDictionary(); - if (values.length < 2 || values.length % 2 != 0) { - throw new IllegalArgumentException("Incorrect argument's count."); - } - - IntegerDictionary dictionary = DictionaryFactory.newIntegerDictionary(); - - for (int i = 0, length = values.length - 2; i <= length; i += 2) { - dictionary.put((Integer) values[i], (V) values[i + 1]); - } - - return dictionary; - } - - /** - * Return true if this dictionary contains a mapping for the specified key. - * - * @param key key whose presence in this dictionary is to be tested. - * @return true if this dictionary contains a mapping for the specified key. - */ - default boolean containsKey(int key) { - throw new UnsupportedOperationException(); - } - - /** - * Return the value to which the specified key is mapped, or {@code null} if this dictionary - * contains no mapping for the key. - * - * @param key the key whose associated value is to be returned. - * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for the key. - */ - default @Nullable V get(final int key) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute(int key, @NotNull Supplier<@NotNull V> factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute(int key, @NotNull IntFunction<@NotNull V> factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - * @see #getOrCompute(int, Object, Function) - */ - - default @Nullable V get(int key, @Nullable T argument, @NotNull Function factory) { - return getOrCompute(key, argument, factory); + for (int i = 0, length = values.length - 2; i <= length; i += 2) { + dictionary.put((Integer) values[i], (V) values[i + 1]); } - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @Nullable V getOrCompute( - int key, - @NotNull T argument, - @NotNull Function<@NotNull T, @NotNull V> factory - ) { - throw new UnsupportedOperationException(); - } - - /** - * Create an array with all keys of this dictionary. - * - * @return the array with all keys of this dictionary. - */ - default @NotNull IntegerArray keyArray() { - return keyArray(ArrayFactory.newMutableIntegerArray(size())); - } - - /** - * Put to the array all keys of this dictionary. - * - * @param container the container. - * @return the container with all keys. - */ - default @NotNull IntegerArray keyArray(@NotNull MutableIntegerArray container) { - throw new UnsupportedOperationException(); - } - - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the previous value for the key or null. - */ - default @Nullable V put(int key, @NotNull V value) { - throw new UnsupportedOperationException(); - } - - /** - * Remove a mapping of the key. - * - * @param key the key. - * @return the previous value for the key or null. - */ - default @Nullable V remove(int key) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param consumer the consumer. - */ - default void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - default void forEach( - @NotNull T argument, - @NotNull IntBiObjectConsumer<@NotNull ? super V, @NotNull ? super T> consumer - ) { - throw new UnsupportedOperationException(); - } + return dictionary; + } + + /** + * Return true if this dictionary contains a mapping for the specified key. + * + * @param key key whose presence in this dictionary is to be tested. + * @return true if this dictionary contains a mapping for the specified key. + */ + default boolean containsKey(int key) { + throw new UnsupportedOperationException(); + } + + /** + * Return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for + * the key. + * + * @param key the key whose associated value is to be returned. + * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for + * the key. + */ + default @Nullable V get(final int key) { + throw new UnsupportedOperationException(); + } + + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param key the key. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute(int key, @NotNull Supplier<@NotNull V> factory) { + throw new UnsupportedOperationException(); + } + + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param key the key. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute(int key, @NotNull IntFunction<@NotNull V> factory) { + throw new UnsupportedOperationException(); + } + + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param the argument's type. + * @param key the key. + * @param argument the additional argument. + * @param factory the factory. + * @return the stored value by the key or the new value. + * @see #getOrCompute(int, Object, Function) + */ + + default @Nullable V get(int key, @Nullable T argument, @NotNull Function factory) { + return getOrCompute(key, argument, factory); + } + + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param the argument's type. + * @param key the key. + * @param argument the additional argument. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @Nullable V getOrCompute( + int key, + @NotNull T argument, + @NotNull Function<@NotNull T, @NotNull V> factory) { + throw new UnsupportedOperationException(); + } + + /** + * Create an array with all keys of this dictionary. + * + * @return the array with all keys of this dictionary. + */ + default @NotNull IntegerArray keyArray() { + return keyArray(ArrayFactory.newMutableIntegerArray(size())); + } + + /** + * Put to the array all keys of this dictionary. + * + * @param container the container. + * @return the container with all keys. + */ + default @NotNull IntegerArray keyArray(@NotNull MutableIntegerArray container) { + throw new UnsupportedOperationException(); + } + + /** + * Put the value by the key. + * + * @param key the value's key. + * @param value the value. + * @return the previous value for the key or null. + */ + default @Nullable V put(int key, @NotNull V value) { + throw new UnsupportedOperationException(); + } + + /** + * Remove a mapping of the key. + * + * @param key the key. + * @return the previous value for the key or null. + */ + default @Nullable V remove(int key) { + throw new UnsupportedOperationException(); + } + + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param consumer the consumer. + */ + default void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { + throw new UnsupportedOperationException(); + } + + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param argument the argument. + * @param consumer the consumer. + * @param the argument's type. + */ + default void forEach( + @NotNull T argument, + @NotNull IntBiObjectConsumer<@NotNull ? super V, @NotNull ? super T> consumer) { + throw new UnsupportedOperationException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java index c8196089..46cd2dc7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java @@ -13,82 +13,84 @@ */ public class IntegerDictionaryIterator implements Iterator { - /** - * The dictionary. - */ - @NotNull - private final UnsafeIntegerDictionary dictionary; - - /** - * The next entry. - */ - @Nullable - private IntegerEntry next; - - /** - * The current entry. - */ - @Nullable - private IntegerEntry current; - - /** - * The current index. - */ - private int index; - - public IntegerDictionaryIterator(@NotNull UnsafeIntegerDictionary dictionary) { - this.dictionary = dictionary; - - if (dictionary.size() > 0) { - IntegerEntry[] entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null) ; - } + /** + * The dictionary. + */ + @NotNull + private final UnsafeIntegerDictionary dictionary; + + /** + * The next entry. + */ + @Nullable + private IntegerEntry next; + + /** + * The current entry. + */ + @Nullable + private IntegerEntry current; + + /** + * The current index. + */ + private int index; + + public IntegerDictionaryIterator(@NotNull UnsafeIntegerDictionary dictionary) { + this.dictionary = dictionary; + + if (dictionary.size() > 0) { + IntegerEntry[] entries = dictionary.entries(); + while (index < entries.length && (next = entries[index++]) == null) + ; } - - @Override - public boolean hasNext() { - return next != null; + } + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public V next() { + return nextEntry().getValue(); + } + + /** + * Get the next entry. + * + * @return the next entry. + */ + private IntegerEntry nextEntry() { + + IntegerEntry[] content = dictionary.entries(); + IntegerEntry entry = next; + + if (entry == null) { + throw new NoSuchElementException(); } - @Override - public V next() { - return nextEntry().getValue(); + if ((next = entry.getNext()) == null) { + while (index < content.length && (next = content[index++]) == null) + ; } - /** - * Get the next entry. - * - * @return the next entry. - */ - private IntegerEntry nextEntry() { - - IntegerEntry[] content = dictionary.entries(); - IntegerEntry entry = next; - - if (entry == null) { - throw new NoSuchElementException(); - } + current = entry; - if ((next = entry.getNext()) == null) { - while (index < content.length && (next = content[index++]) == null) ; - } + return entry; + } - current = entry; + @Override + public void remove() { - return entry; + if (current == null) { + throw new IllegalStateException(); } - @Override - public void remove() { + int key = current.getKey(); - if (current == null) { - throw new IllegalStateException(); - } + current = null; - int key = current.getKey(); - - current = null; - - dictionary.removeEntryForKey(key); - } + dictionary.removeEntryForKey(key); + } } \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java index 5196faaf..154d3b75 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java @@ -12,114 +12,114 @@ */ public class IntegerEntry implements Entry, V> { - /** - * The next entry. - */ - @Nullable - private IntegerEntry next; - - /** - * The value of this entry. - */ - @NotNull - private V value; - - /** - * The key of this entry. - */ - private int key; - - /** - * The hash of the key. - */ - private int hash; - - @Override - public boolean equals(@Nullable Object object) { - - if (object == null || object.getClass() != IntegerEntry.class) { - return false; - } - - IntegerEntry entry = (IntegerEntry) object; - - int firstKey = getKey(); - int secondKey = entry.getKey(); - - if (firstKey != secondKey) { - return false; - } - - Object firstValue = getValue(); - Object secondValue = entry.getValue(); - - return Objects.equals(firstValue, secondValue); + /** + * The next entry. + */ + @Nullable + private IntegerEntry next; + + /** + * The value of this entry. + */ + @NotNull + private V value; + + /** + * The key of this entry. + */ + private int key; + + /** + * The hash of the key. + */ + private int hash; + + @Override + public boolean equals(@Nullable Object object) { + + if (object == null || object.getClass() != IntegerEntry.class) { + return false; } - @Override - public void free() { - value = null; - next = null; - } + IntegerEntry entry = (IntegerEntry) object; - @Override - public int getHash() { - return hash; - } + int firstKey = getKey(); + int secondKey = entry.getKey(); - /** - * Get the key. - * - * @return the key. - */ - public int getKey() { - return key; + if (firstKey != secondKey) { + return false; } - @Override - public @Nullable IntegerEntry getNext() { - return next; - } - - @Override - public void setNext(@Nullable IntegerEntry next) { - this.next = next; - } - - @Override - public @NotNull V getValue() { - return value; - } - - @Override - public final int hashCode() { - return key ^ value.hashCode(); - } - - /** - * Set all fields of this entry. - * - * @param hash the hash. - * @param key the key. - * @param value the value. - * @param next the next. - */ - public void set(int hash, int key, @NotNull V value, @Nullable IntegerEntry next) { - this.value = value; - this.next = next; - this.key = key; - this.hash = hash; - } - - @Override - public @NotNull V setValue(@NotNull V value) { - V old = getValue(); - this.value = value; - return old; - } - - @Override - public final String toString() { - return "Entry : " + key + " = " + value; - } + Object firstValue = getValue(); + Object secondValue = entry.getValue(); + + return Objects.equals(firstValue, secondValue); + } + + @Override + public void free() { + value = null; + next = null; + } + + @Override + public int getHash() { + return hash; + } + + /** + * Get the key. + * + * @return the key. + */ + public int getKey() { + return key; + } + + @Override + public @Nullable IntegerEntry getNext() { + return next; + } + + @Override + public void setNext(@Nullable IntegerEntry next) { + this.next = next; + } + + @Override + public @NotNull V getValue() { + return value; + } + + @Override + public final int hashCode() { + return key ^ value.hashCode(); + } + + /** + * Set all fields of this entry. + * + * @param hash the hash. + * @param key the key. + * @param value the value. + * @param next the next. + */ + public void set(int hash, int key, @NotNull V value, @Nullable IntegerEntry next) { + this.value = value; + this.next = next; + this.key = key; + this.hash = hash; + } + + @Override + public @NotNull V setValue(@NotNull V value) { + V old = getValue(); + this.value = value; + return old; + } + + @Override + public final String toString() { + return "Entry : " + key + " = " + value; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java index b170805d..dbb3f847 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java @@ -19,177 +19,174 @@ */ public interface LongDictionary extends Dictionary { - /** - * Get an empty read-only long dictionary. - * - * @param the value's type. - * @return the read-only empty dictionary. - */ - static @NotNull LongDictionary empty() { - return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_LD); + /** + * Get an empty read-only long dictionary. + * + * @param the value's type. + * @return the read-only empty dictionary. + */ + static @NotNull LongDictionary empty() { + return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_LD); + } + + /** + * Create a new long dictionary for the value's type. + * + * @param valueType the value's type. + * @param the value's type. + * @return the new long dictionary. + */ + static @NotNull LongDictionary ofType(@NotNull Class valueType) { + return DictionaryFactory.newLongDictionary(); + } + + /** + * Create a new long dictionary for the values. + * + * @param values the key-value values. + * @param the value's type. + * @return the new long dictionary. + */ + static @NotNull LongDictionary of(@NotNull Object... values) { + + if (values.length < 2 || values.length % 2 != 0) { + throw new IllegalArgumentException("Incorrect argument's count."); } - /** - * Create a new long dictionary for the value's type. - * - * @param valueType the value's type. - * @param the value's type. - * @return the new long dictionary. - */ - static @NotNull LongDictionary ofType(@NotNull Class valueType) { - return DictionaryFactory.newLongDictionary(); - } - - /** - * Create a new long dictionary for the values. - * - * @param values the key-value values. - * @param the value's type. - * @return the new long dictionary. - */ - static @NotNull LongDictionary of(@NotNull Object... values) { - - if (values.length < 2 || values.length % 2 != 0) { - throw new IllegalArgumentException("Incorrect argument's count."); - } - - var dictionary = DictionaryFactory.newLongDictionary(); - - for (int i = 0, length = values.length - 2; i <= length; i += 2) { - dictionary.put(((Number) values[i]).longValue(), (V) values[i + 1]); - } - - return dictionary; - } - - static > @NotNull M append( - @NotNull M first, - @NotNull M second - ) { - second.copyTo(first); - return first; - } - - /** - * Return true if this dictionary contains a mapping for the specified key. - * - * @param key key whose presence in this dictionary is to be tested. - * @return true if this dictionary contains a mapping for the specified key. - */ - default boolean containsKey(long key) { - throw new UnsupportedOperationException(); - } - - /** - * Return the value to which the specified key is mapped, or {@code null} if this dictionary - * contains no mapping for the key. - * - * @param key the key whose associated value is to be returned. - * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for the key. - */ - default @Nullable V get(long key) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute(long key, @NotNull Supplier<@NotNull V> factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute(long key, @NotNull LongFunction<@NotNull V> factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @Nullable V getOrCompute( - long key, - @NotNull T argument, - @NotNull Function<@NotNull T, @NotNull V> factory - ) { - throw new UnsupportedOperationException(); - } - - /** - * Create an array with all keys of this dictionary. - * - * @return the array with all keys of this dictionary. - */ - default @NotNull LongArray keyArray() { - return keyArray(ArrayFactory.newLongArray(size())); - } + var dictionary = DictionaryFactory.newLongDictionary(); - /** - * Put to the array all keys of this dictionary. - * - * @param container the container. - * @return the container with all keys. - */ - default @NotNull LongArray keyArray(@NotNull LongArray container) { - throw new UnsupportedOperationException(); + for (int i = 0, length = values.length - 2; i <= length; i += 2) { + dictionary.put(((Number) values[i]).longValue(), (V) values[i + 1]); } - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the previous value for the key or null. - */ - default @Nullable V put(long key, @NotNull V value) { - throw new UnsupportedOperationException(); - } - - /** - * Remove a mapping of the key. - * - * @param key the key. - * @return the previous value for the key or null. - */ - default @Nullable V remove(long key) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param consumer the consumer. - */ - default void forEach(@NotNull LongObjectConsumer<@NotNull V> consumer) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - default void forEach(@NotNull T argument, @NotNull LongBiObjectConsumer<@NotNull V, @NotNull T> consumer) { - throw new UnsupportedOperationException(); - } + return dictionary; + } + + static > @NotNull M append(@NotNull M first, @NotNull M second) { + second.copyTo(first); + return first; + } + + /** + * Return true if this dictionary contains a mapping for the specified key. + * + * @param key key whose presence in this dictionary is to be tested. + * @return true if this dictionary contains a mapping for the specified key. + */ + default boolean containsKey(long key) { + throw new UnsupportedOperationException(); + } + + /** + * Return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for + * the key. + * + * @param key the key whose associated value is to be returned. + * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for + * the key. + */ + default @Nullable V get(long key) { + throw new UnsupportedOperationException(); + } + + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param key the key. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute(long key, @NotNull Supplier<@NotNull V> factory) { + throw new UnsupportedOperationException(); + } + + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param key the key. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute(long key, @NotNull LongFunction<@NotNull V> factory) { + throw new UnsupportedOperationException(); + } + + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param the argument's type. + * @param key the key. + * @param argument the additional argument. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @Nullable V getOrCompute( + long key, + @NotNull T argument, + @NotNull Function<@NotNull T, @NotNull V> factory) { + throw new UnsupportedOperationException(); + } + + /** + * Create an array with all keys of this dictionary. + * + * @return the array with all keys of this dictionary. + */ + default @NotNull LongArray keyArray() { + return keyArray(ArrayFactory.newLongArray(size())); + } + + /** + * Put to the array all keys of this dictionary. + * + * @param container the container. + * @return the container with all keys. + */ + default @NotNull LongArray keyArray(@NotNull LongArray container) { + throw new UnsupportedOperationException(); + } + + /** + * Put the value by the key. + * + * @param key the value's key. + * @param value the value. + * @return the previous value for the key or null. + */ + default @Nullable V put(long key, @NotNull V value) { + throw new UnsupportedOperationException(); + } + + /** + * Remove a mapping of the key. + * + * @param key the key. + * @return the previous value for the key or null. + */ + default @Nullable V remove(long key) { + throw new UnsupportedOperationException(); + } + + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param consumer the consumer. + */ + default void forEach(@NotNull LongObjectConsumer<@NotNull V> consumer) { + throw new UnsupportedOperationException(); + } + + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param argument the argument. + * @param consumer the consumer. + * @param the argument's type. + */ + default void forEach(@NotNull T argument, @NotNull LongBiObjectConsumer<@NotNull V, @NotNull T> consumer) { + throw new UnsupportedOperationException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java index bbb27917..929ed292 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java @@ -13,82 +13,84 @@ */ public class LongDictionaryIterator implements Iterator { - /** - * The dictionary. - */ - @NotNull - private final UnsafeLongDictionary dictionary; - - /** - * The next entry. - */ - @Nullable - private LongEntry next; - - /** - * The current entry. - */ - @Nullable - private LongEntry current; - - /** - * The current index. - */ - private int index; - - public LongDictionaryIterator(@NotNull UnsafeLongDictionary dictionary) { - this.dictionary = dictionary; - - if (dictionary.size() > 0) { - LongEntry[] entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null) ; - } + /** + * The dictionary. + */ + @NotNull + private final UnsafeLongDictionary dictionary; + + /** + * The next entry. + */ + @Nullable + private LongEntry next; + + /** + * The current entry. + */ + @Nullable + private LongEntry current; + + /** + * The current index. + */ + private int index; + + public LongDictionaryIterator(@NotNull UnsafeLongDictionary dictionary) { + this.dictionary = dictionary; + + if (dictionary.size() > 0) { + LongEntry[] entries = dictionary.entries(); + while (index < entries.length && (next = entries[index++]) == null) + ; } - - @Override - public boolean hasNext() { - return next != null; + } + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public V next() { + return nextEntry().getValue(); + } + + /** + * Get the next entry. + * + * @return the next entry. + */ + private LongEntry nextEntry() { + + LongEntry[] entries = dictionary.entries(); + LongEntry entry = next; + + if (entry == null) { + throw new NoSuchElementException(); } - @Override - public V next() { - return nextEntry().getValue(); + if ((next = entry.getNext()) == null) { + while (index < entries.length && (next = entries[index++]) == null) + ; } - /** - * Get the next entry. - * - * @return the next entry. - */ - private LongEntry nextEntry() { - - LongEntry[] entries = dictionary.entries(); - LongEntry entry = next; - - if (entry == null) { - throw new NoSuchElementException(); - } + current = entry; - if ((next = entry.getNext()) == null) { - while (index < entries.length && (next = entries[index++]) == null) ; - } + return entry; + } - current = entry; + @Override + public void remove() { - return entry; + if (current == null) { + throw new IllegalStateException(); } - @Override - public void remove() { + long key = current.getKey(); - if (current == null) { - throw new IllegalStateException(); - } + current = null; - long key = current.getKey(); - - current = null; - - dictionary.removeEntryForKey(key); - } + dictionary.removeEntryForKey(key); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java index d6543e16..dbbc2ff4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java @@ -12,118 +12,113 @@ */ public final class LongEntry implements Entry, V> { - /** - * The next entry. - */ - @Nullable - private LongEntry next; - - /** - * The value of this entry. - */ - @NotNull - private V value; - - /** - * The key of this entry. - */ - private long key; - /** - * The hash of the key. - */ - private int hash; - - @Override - public boolean equals(@Nullable Object object) { - - if (object == null || object.getClass() != LongEntry.class) { - return false; - } - - LongEntry entry = (LongEntry) object; - - long firstKey = getKey(); - long secondKey = entry.getKey(); - - if (firstKey != secondKey) { - return false; - } - - Object firstValue = getValue(); - Object secondValue = entry.getValue(); - - return Objects.equals(firstValue, secondValue); + /** + * The next entry. + */ + @Nullable + private LongEntry next; + + /** + * The value of this entry. + */ + @NotNull + private V value; + + /** + * The key of this entry. + */ + private long key; + /** + * The hash of the key. + */ + private int hash; + + @Override + public boolean equals(@Nullable Object object) { + + if (object == null || object.getClass() != LongEntry.class) { + return false; } - @Override - public void free() { - value = null; - next = null; - } - - @Override - public int getHash() { - return hash; - } - - /** - * Get the key. - * - * @return the key. - */ - public long getKey() { - return key; - } - - @Override - public @Nullable LongEntry getNext() { - return next; - } + LongEntry entry = (LongEntry) object; - @Override - public void setNext(@Nullable LongEntry next) { - this.next = next; - } + long firstKey = getKey(); + long secondKey = entry.getKey(); - @Override - public @NotNull V getValue() { - return value; + if (firstKey != secondKey) { + return false; } - @Override - public final int hashCode() { - return (int) (key ^ value.hashCode()); - } - - /** - * Set all fields of this entry. - * - * @param hash the hash. - * @param key the key. - * @param value the value. - * @param next the next. - */ - public void set(int hash, long key, @NotNull V value, @Nullable LongEntry next) { - this.value = value; - this.next = next; - this.key = key; - this.hash = hash; - } - - @Override - public @NotNull V setValue(@NotNull V value) { - V old = getValue(); - this.value = value; - return old; - } - - @Override - public String toString() { - return "LongEntry{" + - "next=" + next + - ", value=" + value + - ", key=" + key + - ", hash=" + hash + - '}'; - } + Object firstValue = getValue(); + Object secondValue = entry.getValue(); + + return Objects.equals(firstValue, secondValue); + } + + @Override + public void free() { + value = null; + next = null; + } + + @Override + public int getHash() { + return hash; + } + + /** + * Get the key. + * + * @return the key. + */ + public long getKey() { + return key; + } + + @Override + public @Nullable LongEntry getNext() { + return next; + } + + @Override + public void setNext(@Nullable LongEntry next) { + this.next = next; + } + + @Override + public @NotNull V getValue() { + return value; + } + + @Override + public final int hashCode() { + return (int) (key ^ value.hashCode()); + } + + /** + * Set all fields of this entry. + * + * @param hash the hash. + * @param key the key. + * @param value the value. + * @param next the next. + */ + public void set(int hash, long key, @NotNull V value, @Nullable LongEntry next) { + this.value = value; + this.next = next; + this.key = key; + this.hash = hash; + } + + @Override + public @NotNull V setValue(@NotNull V value) { + V old = getValue(); + this.value = value; + return old; + } + + @Override + public String toString() { + return "LongEntry{" + "next=" + next + ", value=" + value + ", key=" + key + ", hash=" + hash + '}'; + } } \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongKey.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongKey.java index 9ba8db10..16fe3098 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongKey.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongKey.java @@ -7,7 +7,7 @@ */ public final class LongKey { - private LongKey() { - throw new IllegalArgumentException(); - } + private LongKey() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java index d8c2e901..250ac14b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java @@ -22,281 +22,276 @@ */ public interface ObjectDictionary extends Dictionary { - /** - * Create a new object dictionary for the key's type and value's type. - * - * @param keyValueType the key's and value's type. - * @param the key's and value's type. - * @return the new object dictionary. - */ - static @NotNull ObjectDictionary ofType(@NotNull Class keyValueType) { - return DictionaryFactory.newObjectDictionary(); - } + /** + * Create a new object dictionary for the key's type and value's type. + * + * @param keyValueType the key's and value's type. + * @param the key's and value's type. + * @return the new object dictionary. + */ + static @NotNull ObjectDictionary ofType(@NotNull Class keyValueType) { + return DictionaryFactory.newObjectDictionary(); + } - /** - * Create a new object dictionary for the key's type and value's type. - * - * @param keyType the key's type. - * @param valueType the value's type. - * @param the key's type. - * @param the value's type. - * @return the new object dictionary. - */ - static @NotNull ObjectDictionary ofType( - @NotNull Class keyType, - @NotNull Class valueType - ) { - return DictionaryFactory.newObjectDictionary(); - } + /** + * Create a new object dictionary for the key's type and value's type. + * + * @param keyType the key's type. + * @param valueType the value's type. + * @param the key's type. + * @param the value's type. + * @return the new object dictionary. + */ + static @NotNull ObjectDictionary ofType( + @NotNull Class keyType, + @NotNull Class valueType) { + return DictionaryFactory.newObjectDictionary(); + } - /** - * Create a new object dictionary for the values. - * - * @param values the key-value values. - * @param the key's type. - * @param the value's type. - * @return the new object dictionary. - */ - static @NotNull ObjectDictionary of(@NotNull Object... values) { - return new ReadOnlyFastObjectDictionary<>(values); - } + /** + * Create a new object dictionary for the values. + * + * @param values the key-value values. + * @param the key's type. + * @param the value's type. + * @return the new object dictionary. + */ + static @NotNull ObjectDictionary of(@NotNull Object... values) { + return new ReadOnlyFastObjectDictionary<>(values); + } - /** - * Get an empty read-only object dictionary. - * - * @param the key's type. - * @param the value's type. - * @return the read-only empty dictionary. - */ - static @NotNull ObjectDictionary empty() { - return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_OD); - } + /** + * Get an empty read-only object dictionary. + * + * @param the key's type. + * @param the value's type. + * @return the read-only empty dictionary. + */ + static @NotNull ObjectDictionary empty() { + return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_OD); + } - static > @NotNull M append( - @NotNull M first, - @NotNull M second - ) { - second.copyTo(first); - return first; - } + static > @NotNull M append(@NotNull M first, @NotNull M second) { + second.copyTo(first); + return first; + } - /** - * Return true if this dictionary contains a mapping for the specified key. - * - * @param key key whose presence in this dictionary is to be tested. - * @return true if this dictionary contains a mapping for the specified key. - */ - default boolean containsKey(@NotNull K key) { - throw new UnsupportedOperationException(); - } + /** + * Return true if this dictionary contains a mapping for the specified key. + * + * @param key key whose presence in this dictionary is to be tested. + * @return true if this dictionary contains a mapping for the specified key. + */ + default boolean containsKey(@NotNull K key) { + throw new UnsupportedOperationException(); + } - /** - * Return the value to which the specified key is mapped, or {@code null} if this dictionary - * contains no mapping for the key. - * - * @param key the key whose associated value is to be returned. - * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for the key. - */ - default @Nullable V get(@NotNull K key) { - throw new UnsupportedOperationException(); - } + /** + * Return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for + * the key. + * + * @param key the key whose associated value is to be returned. + * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for + * the key. + */ + default @Nullable V get(@NotNull K key) { + throw new UnsupportedOperationException(); + } - /** - * Return the value to which the specified key is mapped, or default if this dictionary - * contains no mapping for the key. - * - * @param key the key whose associated value is to be returned. - * @param def the default value if no value in this dictionary. - * @return the value to which the specified key is mapped, or default if this dictionary contains no mapping for the key. - */ - default @Nullable V getOrDefault(@NotNull K key, @NotNull V def) { - var value = get(key); - return value == null ? def : value; - } + /** + * Return the value to which the specified key is mapped, or default if this dictionary contains no mapping for the + * key. + * + * @param key the key whose associated value is to be returned. + * @param def the default value if no value in this dictionary. + * @return the value to which the specified key is mapped, or default if this dictionary contains no mapping for the + * key. + */ + default @Nullable V getOrDefault(@NotNull K key, @NotNull V def) { + var value = get(key); + return value == null ? def : value; + } - /** - * Return the optional value to which the specified key is mapped, or {@code null} if this dictionary - * contains no mapping for the key. - * - * @param key the key whose associated value is to be returned. - * @return the optional value to which the specified key is mapped. - */ - default @NotNull Optional getOptional(@NotNull K key) { - return Optional.ofNullable(get(key)); - } + /** + * Return the optional value to which the specified key is mapped, or {@code null} if this dictionary contains no + * mapping for the key. + * + * @param key the key whose associated value is to be returned. + * @return the optional value to which the specified key is mapped. + */ + default @NotNull Optional getOptional(@NotNull K key) { + return Optional.ofNullable(get(key)); + } - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullSupplier factory) { - throw new UnsupportedOperationException(); - } + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param key the key. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullSupplier factory) { + throw new UnsupportedOperationException(); + } - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullFunction factory) { - throw new UnsupportedOperationException(); - } + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param key the key. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullFunction factory) { + throw new UnsupportedOperationException(); + } - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullFunction factory) { - throw new UnsupportedOperationException(); - } + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param the argument's type. + * @param key the key. + * @param argument the additional argument. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullFunction factory) { + throw new UnsupportedOperationException(); + } - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - * @see #getOrCompute(Object, Object, NotNullBiFunction) - */ - default @NotNull V get(@NotNull K key, @NotNull T argument, @NotNull NotNullBiFunction factory) { - return getOrCompute(key, argument, factory); - } + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param the argument's type. + * @param key the key. + * @param argument the additional argument. + * @param factory the factory. + * @return the stored value by the key or the new value. + * @see #getOrCompute(Object, Object, NotNullBiFunction) + */ + default @NotNull V get(@NotNull K key, @NotNull T argument, @NotNull NotNullBiFunction factory) { + return getOrCompute(key, argument, factory); + } - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, - * puts this value to this dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @NotNull V getOrCompute( - @NotNull K key, - @NotNull T argument, - @NotNull NotNullBiFunction factory - ) { - throw new UnsupportedOperationException(); - } + /** + * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this + * dictionary and return this value. + * + * @param the argument's type. + * @param key the key. + * @param argument the additional argument. + * @param factory the factory. + * @return the stored value by the key or the new value. + */ + default @NotNull V getOrCompute( + @NotNull K key, + @NotNull T argument, + @NotNull NotNullBiFunction factory) { + throw new UnsupportedOperationException(); + } - /** - * Put to the array all keys of this dictionary. - * - * @param container the container. - * @return the array with all keys. - */ - default @NotNull Array keyArray(@NotNull Array container) { - throw new UnsupportedOperationException(); - } + /** + * Put to the array all keys of this dictionary. + * + * @param container the container. + * @return the array with all keys. + */ + default @NotNull Array keyArray(@NotNull Array container) { + throw new UnsupportedOperationException(); + } - /** - * Create an array with all keys of this dictionary. - * - * @param type the key's type. - * @return the array with all keys of this dictionary. - */ - default @NotNull Array keyArray(@NotNull Class type) { - return keyArray(ArrayFactory.newArray(type, size())); - } + /** + * Create an array with all keys of this dictionary. + * + * @param type the key's type. + * @return the array with all keys of this dictionary. + */ + default @NotNull Array keyArray(@NotNull Class type) { + return keyArray(ArrayFactory.newArray(type, size())); + } - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the previous value for the key or null. - */ - default @Nullable V put(@NotNull K key, @NotNull V value) { - throw new UnsupportedOperationException(); - } + /** + * Put the value by the key. + * + * @param key the value's key. + * @param value the value. + * @return the previous value for the key or null. + */ + default @Nullable V put(@NotNull K key, @NotNull V value) { + throw new UnsupportedOperationException(); + } - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the optional value of the previous value for the key. - */ - default @NotNull Optional putOptional(@NotNull K key, @NotNull V value) { - return Optional.ofNullable(put(key, value)); - } + /** + * Put the value by the key. + * + * @param key the value's key. + * @param value the value. + * @return the optional value of the previous value for the key. + */ + default @NotNull Optional putOptional(@NotNull K key, @NotNull V value) { + return Optional.ofNullable(put(key, value)); + } - /** - * Remove a mapping by the key. - * - * @param key the key. - * @return the previous value for the key or null. - */ - default @Nullable V remove(@NotNull K key) { - throw new UnsupportedOperationException(); - } + /** + * Remove a mapping by the key. + * + * @param key the key. + * @return the previous value for the key or null. + */ + default @Nullable V remove(@NotNull K key) { + throw new UnsupportedOperationException(); + } - /** - * Remove a mapping by the key. - * - * @param key the key. - * @return the optional value of the previous value for the key. - */ - default @NotNull Optional removeOptional(@NotNull K key) { - return Optional.ofNullable(remove(key)); - } + /** + * Remove a mapping by the key. + * + * @param key the key. + * @return the optional value of the previous value for the key. + */ + default @NotNull Optional removeOptional(@NotNull K key) { + return Optional.ofNullable(remove(key)); + } - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param consumer the consumer. - */ - default void forEach(@NotNull NotNullBiConsumer consumer) { - throw new UnsupportedOperationException(); - } + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param consumer the consumer. + */ + default void forEach(@NotNull NotNullBiConsumer consumer) { + throw new UnsupportedOperationException(); + } - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - default void forEach( - @NotNull T argument, - @NotNull NotNullTripleConsumer consumer - ) { - throw new UnsupportedOperationException(); - } + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param argument the argument. + * @param consumer the consumer. + * @param the argument's type. + */ + default void forEach( + @NotNull T argument, + @NotNull NotNullTripleConsumer consumer) { + throw new UnsupportedOperationException(); + } - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the consumer. - * @param the first argument's type. - * @param the second argument's type. - */ - default void forEach( - @NotNull F first, - @NotNull S second, - @NotNull FourObjectConsumer<@NotNull ? super F, @NotNull ? super S, @NotNull ? super K, @NotNull ? super V> consumer - ) { - throw new UnsupportedOperationException(); - } + /** + * Performs the given action for each key-value pair of this dictionary. + * + * @param first the first argument. + * @param second the second argument. + * @param consumer the consumer. + * @param the first argument's type. + * @param the second argument's type. + */ + default void forEach( + @NotNull F first, + @NotNull S second, + @NotNull FourObjectConsumer<@NotNull ? super F, @NotNull ? super S, @NotNull ? super K, @NotNull ? super V> consumer) { + throw new UnsupportedOperationException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java index 9578cd22..a4eea1c3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java @@ -14,81 +14,83 @@ */ public class ObjectDictionaryIterator implements Iterator { - /** - * The dictionary. - */ - private final @NotNull UnsafeObjectDictionary dictionary; - - /** - * The next entry. - */ - private @Nullable ObjectEntry next; - - /** - * The current entry. - */ - private @Nullable ObjectEntry current; - - /** - * The current index. - */ - private int index; - - public ObjectDictionaryIterator(@NotNull UnsafeObjectDictionary dictionary) { - this.dictionary = dictionary; - - if (dictionary.size() > 0) { - var entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null); - } + /** + * The dictionary. + */ + private final @NotNull UnsafeObjectDictionary dictionary; + + /** + * The next entry. + */ + private @Nullable ObjectEntry next; + + /** + * The current entry. + */ + private @Nullable ObjectEntry current; + + /** + * The current index. + */ + private int index; + + public ObjectDictionaryIterator(@NotNull UnsafeObjectDictionary dictionary) { + this.dictionary = dictionary; + + if (dictionary.size() > 0) { + var entries = dictionary.entries(); + while (index < entries.length && (next = entries[index++]) == null) + ; } - - @Override - public boolean hasNext() { - return next != null; + } + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public @NotNull V next() { + //noinspection ConstantConditions + return nextEntry().getValue(); + } + + /** + * Get the next entry. + * + * @return the next entry. + */ + private @NotNull ObjectEntry nextEntry() { + + var entries = dictionary.entries(); + var entry = next; + + if (entry == null) { + throw new NoSuchElementException(); } - @Override - public @NotNull V next() { - //noinspection ConstantConditions - return nextEntry().getValue(); + if ((next = entry.getNext()) == null) { + while (index < entries.length && (next = entries[index++]) == null) + ; } - /** - * Get the next entry. - * - * @return the next entry. - */ - private @NotNull ObjectEntry nextEntry() { - - var entries = dictionary.entries(); - var entry = next; - - if (entry == null) { - throw new NoSuchElementException(); - } + current = entry; - if ((next = entry.getNext()) == null) { - while (index < entries.length && (next = entries[index++]) == null); - } + return entry; + } - current = entry; + @Override + public void remove() { - return entry; + if (current == null) { + throw new IllegalStateException(); } - @Override - public void remove() { + K key = current.getKey(); - if (current == null) { - throw new IllegalStateException(); - } + current = null; - K key = current.getKey(); - - current = null; - - //noinspection ConstantConditions - dictionary.removeEntryForKey(key); - } + //noinspection ConstantConditions + dictionary.removeEntryForKey(key); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java index 4b519238..29730f5b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java @@ -15,85 +15,89 @@ */ public class ObjectEntry implements Entry, V> { - /** - * The next entry. - */ - private @Setter @Getter @Nullable ObjectEntry next; - - /** - * The key of this entry. - */ - private @Getter @Nullable K key; - - /** - * The value of this entry. - */ - private @Getter @Nullable V value; - - /** - * The hash of the key. - */ - private @Getter int hash; - - @Override - public boolean equals(@Nullable Object object) { - - if (object == null || object.getClass() != ObjectEntry.class) { - return false; - } - - var entry = (ObjectEntry) object; - var firstKey = getKey(); - var secondKey = entry.getKey(); - - if (!Objects.equals(firstKey, secondKey)) { - return false; - } - - var firstValue = getValue(); - var secondValue = entry.getValue(); - - return Objects.equals(firstValue, secondValue); - } - - @Override - public void free() { - key = null; - value = null; - next = null; - hash = 0; + /** + * The next entry. + */ + private @Setter + @Getter + @Nullable ObjectEntry next; + + /** + * The key of this entry. + */ + private @Getter + @Nullable K key; + + /** + * The value of this entry. + */ + private @Getter + @Nullable V value; + + /** + * The hash of the key. + */ + private @Getter int hash; + + @Override + public boolean equals(@Nullable Object object) { + + if (object == null || object.getClass() != ObjectEntry.class) { + return false; } - @Override - public final int hashCode() { - return Objects.hashCode(key) ^ Objects.hashCode(value); - } + var entry = (ObjectEntry) object; + var firstKey = getKey(); + var secondKey = entry.getKey(); - /** - * Set all fields of this entry. - * - * @param hash the hash. - * @param key the key. - * @param value the value. - * @param next the next entry. - */ - public void set(int hash, @NotNull K key, @NotNull V value, @Nullable ObjectEntry next) { - this.value = value; - this.next = next; - this.key = key; - this.hash = hash; + if (!Objects.equals(firstKey, secondKey)) { + return false; } - @Override - @SuppressWarnings("ConstantConditions") - public @NotNull V setValue(@NotNull V value) { - var old = getValue(); - this.value = value; - return old; - } - - @Override - public final String toString() { - return "Entry : " + key + " = " + value; - } + var firstValue = getValue(); + var secondValue = entry.getValue(); + + return Objects.equals(firstValue, secondValue); + } + + @Override + public void free() { + key = null; + value = null; + next = null; + hash = 0; + } + + @Override + public final int hashCode() { + return Objects.hashCode(key) ^ Objects.hashCode(value); + } + + /** + * Set all fields of this entry. + * + * @param hash the hash. + * @param key the key. + * @param value the value. + * @param next the next entry. + */ + public void set(int hash, @NotNull K key, @NotNull V value, @Nullable ObjectEntry next) { + this.value = value; + this.next = next; + this.key = key; + this.hash = hash; + } + + @Override + @SuppressWarnings("ConstantConditions") + public @NotNull V setValue(@NotNull V value) { + var old = getValue(); + this.value = value; + return old; + } + + @Override + public final String toString() { + return "Entry : " + key + " = " + value; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java index a761f03c..f2431fa6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java @@ -13,28 +13,28 @@ @NoArgsConstructor public class ReadOnlyFastLongDictionary extends FastLongDictionary { - @Override - public void put(@NotNull Dictionary dictionary) { - throw new IllegalStateException("Dictionary is only read."); - } + @Override + public void put(@NotNull Dictionary dictionary) { + throw new IllegalStateException("Dictionary is only read."); + } - @Override - public @Nullable V put(long key, @Nullable V value) { - throw new IllegalStateException("Dictionary is only read."); - } + @Override + public @Nullable V put(long key, @Nullable V value) { + throw new IllegalStateException("Dictionary is only read."); + } - @Override - public @Nullable V remove(long key) { - throw new IllegalStateException("Dictionary is only read."); - } + @Override + public @Nullable V remove(long key) { + throw new IllegalStateException("Dictionary is only read."); + } - @Override - public @Nullable LongEntry removeEntryForKey(long key) { - throw new IllegalStateException("Dictionary is only read."); - } + @Override + public @Nullable LongEntry removeEntryForKey(long key) { + throw new IllegalStateException("Dictionary is only read."); + } - @Override - public void clear() { - throw new IllegalStateException("Dictionary is only read."); - } + @Override + public void clear() { + throw new IllegalStateException("Dictionary is only read."); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java index f2cfd833..21a2c8ab 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java @@ -14,40 +14,40 @@ @NoArgsConstructor public class ReadOnlyFastObjectDictionary extends FastObjectDictionary { - public ReadOnlyFastObjectDictionary(@NotNull Object... values) { + public ReadOnlyFastObjectDictionary(@NotNull Object... values) { - if (values.length < 2 || values.length % 2 != 0) { - throw new IllegalArgumentException("Incorrect argument's count."); - } - - for (int i = 0, length = values.length - 2; i <= length; i += 2) { - //noinspection unchecked - super.put((K) values[i], (V) values[i + 1]); - } - } - - @Override - public void put(@NotNull Dictionary dictionary) { - throw new IllegalStateException("Dictionary is readonly."); - } - - @Override - public @Nullable V put(@NotNull K key, @Nullable V value) { - throw new IllegalStateException("Dictionary is readonly."); - } - - @Override - public @Nullable V remove(@NotNull K key) { - throw new IllegalStateException("Dictionary is readonly."); - } - - @Override - public @Nullable ObjectEntry removeEntryForKey(@NotNull K key) { - throw new IllegalStateException("Dictionary is readonly."); + if (values.length < 2 || values.length % 2 != 0) { + throw new IllegalArgumentException("Incorrect argument's count."); } - @Override - public void clear() { - throw new IllegalStateException("Dictionary is readonly."); + for (int i = 0, length = values.length - 2; i <= length; i += 2) { + //noinspection unchecked + super.put((K) values[i], (V) values[i + 1]); } + } + + @Override + public void put(@NotNull Dictionary dictionary) { + throw new IllegalStateException("Dictionary is readonly."); + } + + @Override + public @Nullable V put(@NotNull K key, @Nullable V value) { + throw new IllegalStateException("Dictionary is readonly."); + } + + @Override + public @Nullable V remove(@NotNull K key) { + throw new IllegalStateException("Dictionary is readonly."); + } + + @Override + public @Nullable ObjectEntry removeEntryForKey(@NotNull K key) { + throw new IllegalStateException("Dictionary is readonly."); + } + + @Override + public void clear() { + throw new IllegalStateException("Dictionary is readonly."); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java index 5b148936..7abfe189 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java @@ -11,18 +11,18 @@ */ public interface UnsafeIntegerDictionary extends IntegerDictionary { - /** - * Get an array of all entries in this dictionary. - * - * @return the array of entries. - */ - @NotNull IntegerEntry[] entries(); + /** + * Get an array of all entries in this dictionary. + * + * @return the array of entries. + */ + @NotNull IntegerEntry[] entries(); - /** - * Remove an entry for the key. - * - * @param key the key of the entry. - * @return removed entry. - */ - @Nullable IntegerEntry removeEntryForKey(final int key); + /** + * Remove an entry for the key. + * + * @param key the key of the entry. + * @return removed entry. + */ + @Nullable IntegerEntry removeEntryForKey(final int key); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java index fde30dc8..1b16b135 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java @@ -11,18 +11,18 @@ */ public interface UnsafeLongDictionary extends LongDictionary { - /** - * Get an array of all entries in this dictionary. - * - * @return the array of entries. - */ - @NotNull LongEntry[] entries(); + /** + * Get an array of all entries in this dictionary. + * + * @return the array of entries. + */ + @NotNull LongEntry[] entries(); - /** - * Remove an entry for the key. - * - * @param key the key of the entry. - * @return removed entry. - */ - @Nullable LongEntry removeEntryForKey(long key); + /** + * Remove an entry for the key. + * + * @param key the key of the entry. + * @return removed entry. + */ + @Nullable LongEntry removeEntryForKey(long key); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java index 31db0e51..72dff7dc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java @@ -12,18 +12,18 @@ */ public interface UnsafeObjectDictionary extends ObjectDictionary { - /** - * Get an array of all entries in this dictionary. - * - * @return the array of entries. - */ - @NotNull ObjectEntry[] entries(); + /** + * Get an array of all entries in this dictionary. + * + * @return the array of entries. + */ + @NotNull ObjectEntry[] entries(); - /** - * Remove an entry for the key. - * - * @param key the key of the entry. - * @return removed entry. - */ - @Nullable ObjectEntry removeEntryForKey(@NotNull K key); + /** + * Remove an entry for the key. + * + * @param key the key of the entry. + * @return removed entry. + */ + @Nullable ObjectEntry removeEntryForKey(@NotNull K key); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/ConcurrentLinkedList.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/ConcurrentLinkedList.java index 5bf57b8c..1980e601 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/ConcurrentLinkedList.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/ConcurrentLinkedList.java @@ -1,46 +1,49 @@ package javasabr.rlib.common.util.linkedlist; +import org.jspecify.annotations.NullMarked; + /** * The interface to implement concurrent supporting. * * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface ConcurrentLinkedList extends LinkedList { - /** - * Lock this array for writing. - * - * @return the stamp of write lock or 0. - */ - default long writeLock() { - throw new UnsupportedOperationException(); - } + /** + * Lock this array for writing. + * + * @return the stamp of write lock or 0. + */ + default long writeLock() { + throw new UnsupportedOperationException(); + } - /** - * Unlock the write lock. - * - * @param stamp the stamp of write lock. - */ - default void writeUnlock(final long stamp) { - throw new UnsupportedOperationException(); - } + /** + * Unlock the write lock. + * + * @param stamp the stamp of write lock. + */ + default void writeUnlock(final long stamp) { + throw new UnsupportedOperationException(); + } - /** - * Lock this array for reading. - * - * @return the stamp of read lock or 0. - */ - default long readLock() { - throw new UnsupportedOperationException(); - } + /** + * Lock this array for reading. + * + * @return the stamp of read lock or 0. + */ + default long readLock() { + throw new UnsupportedOperationException(); + } - /** - * Unlock the read lock. - * - * @param stamp the stamp of read lock. - */ - default void readUnlock(final long stamp) { - throw new UnsupportedOperationException(); - } + /** + * Unlock the read lock. + * + * @param stamp the stamp of read lock. + */ + default void readUnlock(final long stamp) { + throw new UnsupportedOperationException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedList.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedList.java index 057b1818..db4c936b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedList.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedList.java @@ -2,6 +2,7 @@ import java.io.Serializable; import java.util.Deque; +import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.BiPredicate; import java.util.function.Consumer; @@ -12,8 +13,8 @@ import javasabr.rlib.common.function.TriplePredicate; import javasabr.rlib.common.util.linkedlist.impl.Node; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * Интерфей с для реализации связанного списка. Главное преймущество, это переиспользование узлов списка и быстрая @@ -28,224 +29,224 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface LinkedList extends Deque, Cloneable, Serializable, Reusable { - @Override - default void forEach(@NotNull final Consumer consumer) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - consumer.accept(node.getItem()); - } + @Override + default void forEach(Consumer consumer) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + consumer.accept(node.getItem()); } - - /** - * Apply a function to each filtered element. - * - * @param condition the condition. - * @param function the function. - */ - default void forEach(@NotNull Predicate condition, @NotNull Consumer function) { - for (var node = getFirstNode(); node != null; node = node.getNext()) { - var item = node.getItem(); - if (condition.test(item)) { - function.accept(item); - } - } + } + + /** + * Apply a function to each filtered element. + * + * @param condition the condition. + * @param function the function. + */ + default void forEach(Predicate condition, Consumer function) { + for (var node = getFirstNode(); node != null; node = node.getNext()) { + var item = node.getItem(); + if (condition.test(item)) { + function.accept(item); + } } - - /** - * Apply the function to each element which is an instance of the passed type. - * - * @param type the interested element's type. - * @param function the function. - * @param the element's type. - */ - default void applyIfType(@NotNull Class type, @NotNull Consumer function) { - for (var node = getFirstNode(); node != null; node = node.getNext()) { - var item = node.getItem(); - if (type.isInstance(item)) { - function.accept(type.cast(item)); - } - } + } + + /** + * Apply the function to each element which is an instance of the passed type. + * + * @param type the interested element's type. + * @param function the function. + * @param the element's type. + */ + default void applyIfType(Class type, Consumer function) { + for (var node = getFirstNode(); node != null; node = node.getNext()) { + var item = node.getItem(); + if (type.isInstance(item)) { + function.accept(type.cast(item)); + } } - - /** - * Apply a function to each element. - * - * @param the type of an argument. - * @param argument the argument. - * @param function the function. - */ - default void forEach(@Nullable final T argument, @NotNull final BiConsumer function) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - function.accept(argument, node.getItem()); - } + } + + /** + * Apply a function to each element. + * + * @param the type of an argument. + * @param argument the argument. + * @param function the function. + */ + default void forEach(@Nullable T argument, BiConsumer function) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + function.accept(argument, node.getItem()); } - - /** - * Apply a function to each filtered element. - * - * @param the type of an argument. - * @param argument the argument. - * @param condition the condition. - * @param function the function. - */ - default void forEach(@Nullable final T argument, @NotNull final BiPredicate condition, - @NotNull final BiConsumer function) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - final E item = node.getItem(); - if (condition.test(item, argument)) function.accept(argument, item); - } + } + + /** + * Apply a function to each filtered element. + * + * @param the type of an argument. + * @param argument the argument. + * @param condition the condition. + * @param function the function. + */ + default void forEach( + @Nullable T argument, + BiPredicate condition, + BiConsumer<@Nullable T, E> function) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + final E item = node.getItem(); + if (condition.test(item, argument)) { + function.accept(argument, item); + } } - - /** - * Apply a function to each filtered element. - * - * @param the type of a first argument. - * @param the type of a second argument. - * @param first the first argument. - * @param second the second argument. - * @param condition the condition. - * @param function the function. - */ - default void forEach(@Nullable final F first, @Nullable final S second, - @NotNull final TriplePredicate condition, - @NotNull final TripleConsumer function) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - final E item = node.getItem(); - if (condition.test(item, first, second)) function.accept(first, second, item); - } + } + + /** + * Apply a function to each filtered element. + * + * @param the type of a first argument. + * @param the type of a second argument. + * @param first the first argument. + * @param second the second argument. + * @param condition the condition. + * @param function the function. + */ + default void forEach( + @Nullable F first, + @Nullable S second, + TriplePredicate condition, + TripleConsumer function) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + final E item = node.getItem(); + if (condition.test(item, first, second)) { + function.accept(first, second, item); + } } - - /** - * Apply a function to each element. - * - * @param the type of a first argument. - * @param the type of a second argument. - * @param first the first argument. - * @param second the second argument. - * @param function the function. - */ - default void forEach(@Nullable final F first, @Nullable final S second, - @NotNull final TripleConsumer function) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - function.accept(first, second, node.getItem()); - } + } + + /** + * Apply a function to each element. + * + * @param the type of a first argument. + * @param the type of a second argument. + * @param first the first argument. + * @param second the second argument. + * @param function the function. + */ + default void forEach( + @Nullable final F first, + @Nullable final S second, + TripleConsumer function) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + function.accept(first, second, node.getItem()); } - - /** - * Apply a function to each element. - * - * @param the type of a second argument. - * @param first the first argument. - * @param second the second argument. - * @param function the function. - */ - default void forEach(final long first, final F second, @NotNull final LongBiObjectConsumer function) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - function.accept(first, second, node.getItem()); - } + } + + /** + * Apply a function to each element. + * + * @param the type of a second argument. + * @param first the first argument. + * @param second the second argument. + * @param function the function. + */ + default void forEach(long first, final F second, LongBiObjectConsumer function) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + function.accept(first, second, node.getItem()); } - - /** - * Apply a function to each element to replace an original element. - * - * @param function the function. - */ - default void apply(@NotNull final Function function) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - node.setItem(function.apply(node.getItem())); - } - } - - /** - * Gets an element for an index. - * - * @param index the index of an element. - * @return the element for the index. - */ - E get(int index); - - /** - * Get a first node. - * - * @return the first node. - */ - @Nullable - Node getFirstNode(); - - /** - * Get a last node. - * - * @return the last node. - */ - @Nullable - Node getLastNode(); - - /** - * Finds an index of an object in this list. - * - * @param object the object to find. - * @return the index of the object or -1. - */ - int indexOf(Object object); - - /** - * Returns the (non-null) Node at the specified element index. - * - * @param index the index of a node. - * @return the node. - */ - default Node node(int index) { - - final int size = size(); - - if (index < (size >> 1)) { - - Node node = getFirstNode(); - - for (int i = 0; i < index; i++) { - node = node.getNext(); - } - - return node; - - } else { - - Node node = getLastNode(); - - for (int i = size() - 1; i > index; i--) { - node = node.getPrev(); - } - - return node; - } + } + + /** + * Apply a function to each element to replace an original element. + * + * @param function the function. + */ + default void apply(Function function) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + node.setItem(function.apply(node.getItem())); } - - /** - * Removes an element for an index without reordering. - * - * @param index the index of the element. - * @return the removed element. - */ - default E remove(int index) { - return unlink(node(index)); + } + + /** + * Gets an element for an index. + * + * @param index the index of an element. + * @return the element for the index. + */ + E get(int index); + + /** + * Get a first node. + * + * @return the first node. + */ + @Nullable Node getFirstNode(); + + /** + * Get a last node. + * + * @return the last node. + */ + @Nullable Node getLastNode(); + + /** + * Finds an index of an object in this list. + * + * @param object the object to find. + * @return the index of the object or -1. + */ + int indexOf(Object object); + + /** + * Returns the (non-null) Node at the specified element index. + * + * @param index the index of a node. + * @return the node. + */ + default Node node(int index) { + + final int size = size(); + + if (index < (size >> 1)) { + Node node = getFirstNode(); + for (int i = 0; i < index && node != null; i++) { + node = node.getNext(); + } + return Objects.requireNonNull(node); + } else { + Node node = getLastNode(); + for (int i = size() - 1; i > index && node != null; i--) { + node = node.getPrev(); + } + return Objects.requireNonNull(node); } - - /** - * Take and remove a first element. - * - * @return the first element or null. - */ - @Nullable - E take(); - - /** - * Remove a node from this list. - * - * @param node the node. - * @return the removed element. - */ - @Nullable - E unlink(@NotNull Node node); - + } + + /** + * Removes an element for an index without reordering. + * + * @param index the index of the element. + * @return the removed element. + */ + @Nullable + default E remove(int index) { + return unlink(node(index)); + } + + /** + * Take and remove a first element. + * + * @return the first element or null. + */ + @Nullable E take(); + + /** + * Remove a node from this list. + * + * @param node the node. + * @return the removed element. + */ + @Nullable E unlink(Node node); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedListFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedListFactory.java index 0863877c..573fecf9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedListFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/LinkedListFactory.java @@ -2,38 +2,39 @@ import javasabr.rlib.common.util.linkedlist.impl.FastLinkedList; import javasabr.rlib.common.util.linkedlist.impl.SortedLinkedList; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory of linked list implementations. * * @author JavaSaBr */ +@NullMarked public final class LinkedListFactory { - /** - * New linked list linked list. - * - * @param the type parameter - * @param type the type - * @return the linked list - */ - public static LinkedList newLinkedList(@NotNull final Class type) { - return new FastLinkedList<>(type); - } + /** + * New linked list linked list. + * + * @param the type parameter + * @param type the type + * @return the linked list + */ + public static LinkedList newLinkedList(Class type) { + return new FastLinkedList<>(type); + } - /** - * New sorted linked list linked list. - * - * @param the type parameter - * @param type the type - * @return the linked list - */ - public static > LinkedList newSortedLinkedList(@NotNull final Class type) { - return new SortedLinkedList<>(type); - } + /** + * New sorted linked list linked list. + * + * @param the type parameter + * @param type the type + * @return the linked list + */ + public static > LinkedList newSortedLinkedList(Class type) { + return new SortedLinkedList<>(type); + } - private LinkedListFactory() { - throw new RuntimeException(); - } + private LinkedListFactory() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/AbstractLinkedList.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/AbstractLinkedList.java index 9a8b62fb..63ed3745 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/AbstractLinkedList.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/AbstractLinkedList.java @@ -5,8 +5,8 @@ import java.util.Objects; import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.linkedlist.LinkedList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of the LinkedList. @@ -14,256 +14,266 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public abstract class AbstractLinkedList implements LinkedList { - private static final long serialVersionUID = 8034712584065781997L; - - /** - * The element type. - */ - @NotNull - protected final Class type; - - /** - * Instantiates a new Abstract linked list. - * - * @param type the type - */ - public AbstractLinkedList(@NotNull final Class type) { - this.type = ClassUtils.unsafeCast(type); - } - - @Override - public boolean addAll(@NotNull final Collection collection) { - - for (final E object : collection) { - if (!add(object)) return false; - } - - return true; - } - - @Override - public boolean contains(@Nullable final Object object) { - return indexOf(object) != -1; - } + private static final long serialVersionUID = 8034712584065781997L; - @Override - public boolean containsAll(@NotNull final Collection collection) { + /** + * The element type. + */ + protected final Class type; - for (final Object object : collection) { - if (!contains(object)) return false; - } + /** + * Instantiates a new Abstract linked list. + * + * @param type the type + */ + public AbstractLinkedList(Class type) { + this.type = ClassUtils.unsafeCast(type); + } - return true; - } + @Override + public boolean addAll(Collection collection) { - @Override - public E element() { - return getFirst(); - } - - @Override - public void free() { - clear(); + for (E object : collection) { + if (!add(object)) { + return false; + } } - @Override - public E getFirst() { + return true; + } - final Node first = getFirstNode(); + @Override + public boolean contains(@Nullable Object object) { + return indexOf(object) != -1; + } - if (first == null) { - throw new NoSuchElementException(); - } + @Override + public boolean containsAll(Collection collection) { - return first.getItem(); + for (Object object : collection) { + if (!contains(object)) { + return false; + } } - @Override - public E getLast() { + return true; + } - final Node last = getLastNode(); + @Override + public E element() { + return getFirst(); + } - if (last == null) { - throw new NoSuchElementException(); - } + @Override + public void free() { + clear(); + } - return last.getItem(); - } + @Override + public E getFirst() { - /** - * Get an element type. - * - * @return the element type. - */ - @NotNull - protected Class getType() { - return type; + Node first = getFirstNode(); + if (first == null) { + throw new NoSuchElementException(); } - @Override - public int indexOf(final Object object) { + return first.getItem(); + } - int index = 0; + @Override + public E getLast() { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - final E item = node.getItem(); - if (Objects.equals(item, object)) return index; - index++; - } + final Node last = getLastNode(); - return -1; + if (last == null) { + throw new NoSuchElementException(); } - @Override - public boolean isEmpty() { - return size() < 1; + return last.getItem(); + } + + /** + * Get an element type. + * + * @return the element type. + */ + protected Class getType() { + return type; + } + + @Override + public int indexOf(final Object object) { + + int index = 0; + + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + final E item = node.getItem(); + if (Objects.equals(item, object)) { + return index; + } + index++; } - @Override - public boolean offer(final E element) { - return add(element); + return -1; + } + + @Override + public boolean isEmpty() { + return size() < 1; + } + + @Override + public boolean offer(E element) { + return add(element); + } + + @Override + public boolean offerFirst(E element) { + addFirst(element); + return true; + } + + @Override + public boolean offerLast(E element) { + addLast(element); + return true; + } + + @Override + public @Nullable E peek() { + Node first = getFirstNode(); + return first == null ? null : first.getItem(); + } + + @Override + public @Nullable E peekFirst() { + final Node first = getFirstNode(); + return first == null ? null : first.getItem(); + } + + @Override + public @Nullable E peekLast() { + final Node last = getLastNode(); + return last == null ? null : last.getItem(); + } + + @Override + public E pop() { + return removeFirst(); + } + + @Override + public void push(final E element) { + addFirst(element); + } + + @Override + public E remove() { + return removeFirst(); + } + + @Override + public boolean remove(@Nullable Object object) { + + if (object == null) { + throw new NullPointerException("object is null."); } - @Override - public boolean offerFirst(final E element) { - addFirst(element); + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + if (object.equals(node.getItem())) { + unlink(node); return true; + } } - @Override - public boolean offerLast(final E element) { - addLast(element); - return true; - } + return false; + } - @Override - public E peek() { - final Node first = getFirstNode(); - return first == null ? null : first.getItem(); - } + @Override + public boolean removeAll(final Collection collection) { - @Override - public E peekFirst() { - final Node first = getFirstNode(); - return first == null ? null : first.getItem(); + for (final Object object : collection) { + if (!remove(object)) { + return false; + } } - @Override - public E peekLast() { - final Node last = getLastNode(); - return last == null ? null : last.getItem(); - } + return true; + } - @Override - public E pop() { - return removeFirst(); - } + @Override + public boolean removeFirstOccurrence(@Nullable Object object) { - @Override - public void push(final E element) { - addFirst(element); + if (object == null) { + throw new NullPointerException("not fond object."); } - @Override - public E remove() { - return removeFirst(); + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + if (object.equals(node.getItem())) { + unlink(node); + return true; + } } - @Override - public boolean remove(final Object object) { + return false; + } - if (object == null) { - throw new NullPointerException("object is null."); - } + @Override + public boolean removeLastOccurrence(@Nullable Object object) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - if (object.equals(node.getItem())) { - unlink(node); - return true; - } - } - - return false; + if (object == null) { + throw new NullPointerException("not fond object."); } - @Override - public boolean removeAll(@NotNull final Collection collection) { - - for (final Object object : collection) { - if (!remove(object)) return false; - } - + for (Node node = getLastNode(); node != null; node = node.getPrev()) { + if (object.equals(node.getItem())) { + unlink(node); return true; + } } - @Override - public boolean removeFirstOccurrence(final Object object) { - - if (object == null) { - throw new NullPointerException("not fond object."); - } + return false; + } - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - if (object.equals(node.getItem())) { - unlink(node); - return true; - } - } + @Override + public boolean retainAll(Collection collection) { + for (E object : this) { + if (!collection.contains(object) && !remove(object)) { return false; + } } - @Override - public boolean removeLastOccurrence(final Object object) { + return true; + } - if (object == null) { - throw new NullPointerException("not fond object."); - } + @Override + public String toString() { - for (Node node = getLastNode(); node != null; node = node.getPrev()) { - if (object.equals(node.getItem())) { - unlink(node); - return true; - } - } + StringBuilder builder = new StringBuilder(getClass().getSimpleName()); + builder + .append(" size = ") + .append(size()) + .append(" : ["); - return false; - } + if (!isEmpty()) { - @Override - public boolean retainAll(@NotNull final Collection collection) { + for (E element : this) { + builder + .append(element) + .append(", "); + } - for (final E object : this) { - if (!collection.contains(object) && !remove(object)) { - return false; - } - } - - return true; + if (builder.indexOf(",") != -1) { + builder.delete(builder.length() - 2, builder.length()); + } } - @Override - public String toString() { - - final StringBuilder builder = new StringBuilder(getClass().getSimpleName()); - - builder.append(" size = ").append(size()).append(" : ["); - - if (!isEmpty()) { + builder.append("]"); - for (final E element : this) { - builder.append(element).append(", "); - } - - if (builder.indexOf(",") != -1) { - builder.delete(builder.length() - 2, builder.length()); - } - } - - builder.append("]"); - - return builder.toString(); - } + return builder.toString(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/FastLinkedList.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/FastLinkedList.java index 8215dafe..a70d28ef 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/FastLinkedList.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/FastLinkedList.java @@ -6,8 +6,8 @@ import java.util.function.Function; import javasabr.rlib.common.util.pools.PoolFactory; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The non thread-safe implementation of the LinkedList. @@ -15,451 +15,446 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class FastLinkedList extends AbstractLinkedList { - private static final long serialVersionUID = 6627882787737291879L; - - /** - * The node pool. - */ - @NotNull - private final ReusablePool> pool; - - /** - * The first element. - */ - @Nullable - private Node first; - - /** - * The second element. - */ - @Nullable - private Node last; - - /** - * The size. - */ - private int size; - - /** - * Instantiates a new Fast linked list. - * - * @param type the type - */ - public FastLinkedList(@NotNull final Class type) { - super(type); - this.pool = PoolFactory.newReusablePool(Node.class); - } - - @Override - public boolean add(@NotNull final E element) { - linkLast(element); - return true; - } - - @Override - public void addFirst(@NotNull final E element) { - linkFirst(element); - } - - @Override - public void addLast(@NotNull final E element) { - linkLast(element); - } - - @Override - public void apply(@NotNull final Function function) { - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - node.setItem(function.apply(node.getItem())); - } - } - - @Override - public void clear() { - - final ReusablePool> pool = getPool(); - - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - pool.put(node); - } - - setFirstNode(null); - setLastNode(null); - - size = 0; - } - - @NotNull - @Override - public Iterator descendingIterator() { - return new IteratorImpl<>(this, IteratorImpl.PREV); - } - - @Override - public E get(final int index) { - return index < size() >> 1 ? getFirst(index) : getLast(index); - } - - /** - * Gets first. - * - * @param index the index - * @return the first - */ - @Nullable - protected final E getFirst(final int index) { - - int i = 0; - - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - if (i == index) return node.getItem(); - i++; - } - - return null; - } - - @Nullable - @Override - public final Node getFirstNode() { - return first; - } - - /** - * Sets first node. - * - * @param first the first node. - */ - protected void setFirstNode(@Nullable final Node first) { - this.first = first; - } - - /** - * Gets last. - * - * @param index the index - * @return the last - */ - @Nullable - protected final E getLast(final int index) { - - int i = size() - 1; - - for (Node node = getLastNode(); node != null; node = node.getPrev()) { - if (i == index) return node.getItem(); - i--; - } + private static final long serialVersionUID = 6627882787737291879L; - return null; - } - - @Nullable - @Override - public final Node getLastNode() { - return last; - } - - /** - * Sets last node. - * - * @param last the last node. - */ - protected void setLastNode(@Nullable final Node last) { - this.last = last; - } + /** + * The node pool. + */ + private final ReusablePool> pool; + + /** + * The first element. + */ + @Nullable + private Node first; + + /** + * The second element. + */ + @Nullable + private Node last; + + /** + * The size. + */ + private int size; + + /** + * Instantiates a new Fast linked list. + * + * @param type the type + */ + public FastLinkedList(Class type) { + super(type); + this.pool = PoolFactory.newReusablePool(Node.class); + } + + @Override + public boolean add(E element) { + linkLast(element); + return true; + } + + @Override + public void addFirst(E element) { + linkFirst(element); + } + + @Override + public void addLast(E element) { + linkLast(element); + } + + @Override + public void apply(Function function) { + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + node.setItem(function.apply(node.getItem())); + } + } + + @Override + public void clear() { + + ReusablePool> pool = getPool(); + + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + pool.put(node); + } + + setFirstNode(null); + setLastNode(null); + + size = 0; + } + + @Override + public Iterator descendingIterator() { + return new IteratorImpl<>(this, IteratorImpl.PREV); + } + + @Override + public E get(int index) { + return index < size() >> 1 ? getFirst(index) : getLast(index); + } + + /** + * Gets first. + * + * @param index the index + * @return the first + */ + protected final E getFirst(int index) { + + int i = 0; + + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + if (i == index) { + return node.getItem(); + } + i++; + } + + throw new NoSuchElementException(); + } + + @Nullable + @Override + public final Node getFirstNode() { + return first; + } + + /** + * Sets first node. + * + * @param first the first node. + */ + protected void setFirstNode(@Nullable final Node first) { + this.first = first; + } + + /** + * Gets last. + * + * @param index the index + * @return the last + */ + protected final E getLast(final int index) { + + int i = size() - 1; + + for (Node node = getLastNode(); node != null; node = node.getPrev()) { + if (i == index) { + return node.getItem(); + } + i--; + } + + throw new NoSuchElementException(); + } + + @Nullable + @Override + public final Node getLastNode() { + return last; + } + + /** + * Sets last node. + * + * @param last the last node. + */ + protected void setLastNode(@Nullable final Node last) { + this.last = last; + } + + /** + * Get a new node. + * + * @param prev the prev node. + * @param item the item. + * @param next the next node. + * @return the new node. + */ + protected Node getNewNode(@Nullable Node prev, E item, @Nullable Node next) { + + Node node = getPool().take(Node::new); + node.setItem(item); + node.setNext(next); + node.setPrev(prev); + + return node; + } + + /** + * Gets pool. + * + * @return the pool. + */ + protected ReusablePool> getPool() { + return pool; + } + + /** + * Insert after. + * + * @param node the node + * @param item the item + */ + protected final void insertAfter(Node node, E item) { + + Node next = node.getNext(); + Node newNode = getNewNode(node, item, next); + + if (next == null) { + setLastNode(newNode); + } else { + next.setPrev(newNode); + } + + node.setNext(newNode); + } + + /** + * Insert before. + * + * @param node the node + * @param item the item + */ + protected final void insertBefore(Node node, E item) { + + Node prev = node.getPrev(); + Node newNode = getNewNode(prev, item, node); + + if (prev == null) { + setFirstNode(newNode); + } else { + prev.setNext(newNode); + } + + node.setPrev(newNode); + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(this, IteratorImpl.NEXT); + } + + /** + * Link first. + * + * @param item the item + */ + protected final void linkFirst(E item) { + Objects.requireNonNull(item); - /** - * Get a new node. - * - * @param prev the prev node. - * @param item the item. - * @param next the next node. - * @return the new node. - */ - @NotNull - protected Node getNewNode(@Nullable final Node prev, @NotNull final E item, @Nullable final Node next) { - - final Node node = getPool().take(Node::new); - node.setItem(item); - node.setNext(next); - node.setPrev(prev); - - return node; - } + Node first = getFirstNode(); + Node newNode = getNewNode(null, item, first); + + setFirstNode(newNode); - /** - * Gets pool. - * - * @return the pool. - */ - @NotNull - protected ReusablePool> getPool() { - return pool; + if (first == null) { + setLastNode(newNode); + } else { + first.setPrev(newNode); } - /** - * Insert after. - * - * @param node the node - * @param item the item - */ - protected final void insertAfter(@NotNull final Node node, final E item) { - - final Node next = node.getNext(); - final Node newNode = getNewNode(node, item, next); - - if (next == null) { - setLastNode(newNode); - } else { - next.setPrev(newNode); - } + size++; + } - node.setNext(newNode); - } - - /** - * Insert before. - * - * @param node the node - * @param item the item - */ - protected final void insertBefore(@NotNull final Node node, final E item) { + /** + * Link last. + * + * @param item the item + */ + protected final void linkLast(E item) { + Objects.requireNonNull(item); - final Node prev = node.getPrev(); - final Node newNode = getNewNode(prev, item, node); + Node last = getLastNode(); + Node newNode = getNewNode(last, item, null); - if (prev == null) { - setFirstNode(newNode); - } else { - prev.setNext(newNode); - } + setLastNode(newNode); - node.setPrev(newNode); + if (last == null) { + setFirstNode(newNode); + } else { + last.setNext(newNode); } - @NotNull - @Override - public Iterator iterator() { - return new IteratorImpl<>(this, IteratorImpl.NEXT); - } + size++; + } - /** - * Link first. - * - * @param item the item - */ - protected final void linkFirst(@NotNull final E item) { - Objects.requireNonNull(item); + @Override + public @Nullable E poll() { + Node first = getFirstNode(); + return first == null ? null : unlinkFirst(first); + } - final Node first = getFirstNode(); - final Node newNode = getNewNode(null, item, first); + @Override + public @Nullable E pollFirst() { + Node first = getFirstNode(); + return first == null ? null : unlinkFirst(first); + } - setFirstNode(newNode); + @Override + public @Nullable E pollLast() { + Node last = getLastNode(); + return last == null ? null : unlinkLast(last); + } - if (first == null) { - setLastNode(newNode); - } else { - first.setPrev(newNode); - } + @Override + public E removeFirst() { - size++; + Node first = getFirstNode(); + if (first == null) { + throw new NoSuchElementException(); } - /** - * Link last. - * - * @param item the item - */ - protected final void linkLast(@NotNull final E item) { - Objects.requireNonNull(item); - - final Node last = getLastNode(); - final Node newNode = getNewNode(last, item, null); + return unlinkFirst(first); + } - setLastNode(newNode); + @Override + public E removeLast() { - if (last == null) { - setFirstNode(newNode); - } else { - last.setNext(newNode); - } - - size++; + Node last = getLastNode(); + if (last == null) { + throw new NoSuchElementException(); } - @Override - public E poll() { - final Node first = getFirstNode(); - return first == null ? null : unlinkFirst(first); - } + return unlinkLast(last); + } - @Override - public E pollFirst() { - final Node first = getFirstNode(); - return first == null ? null : unlinkFirst(first); - } + @Override + public int size() { + return size; + } - @Override - public E pollLast() { - final Node last = getLastNode(); - return last == null ? null : unlinkLast(last); - } + @Override + public E take() { + return removeFirst(); + } - @Override - public E removeFirst() { + @Override + public Object[] toArray() { - final Node first = getFirstNode(); + Object[] array = (Object[]) java.lang.reflect.Array.newInstance(getType(), size()); - if (first == null) { - throw new NoSuchElementException(); - } + int index = 0; - return unlinkFirst(first); + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + array[index++] = node.getItem(); } - @Override - public E removeLast() { + return array; + } - final Node last = getLastNode(); + @Override + @SuppressWarnings("unchecked") + public T[] toArray(T[] array) { - if (last == null) { - throw new NoSuchElementException(); - } + int size = size(); - return unlinkLast(last); + if (array.length < size) { + array = (T[]) java.lang.reflect.Array.newInstance( + array + .getClass() + .getComponentType(), size); } - @Override - public int size() { - return size; - } - - @Override - public E take() { - return removeFirst(); - } - - @NotNull - @Override - public Object[] toArray() { + int i = 0; - final Object[] array = (Object[]) java.lang.reflect.Array.newInstance(getType(), size()); + Object[] result = array; - int index = 0; - - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - array[index++] = node.getItem(); - } - - return array; + for (Node node = getFirstNode(); node != null; node = node.getNext()) { + result[i++] = node.getItem(); } - @NotNull - @Override - @SuppressWarnings("unchecked") - public T[] toArray(@NotNull T[] array) { + return array; + } - final int size = size(); + @Override + public String toString() { + return super.toString() + "\n " + pool; + } - if (array.length < size) { - array = (T[]) java.lang.reflect.Array.newInstance(array.getClass().getComponentType(), size); - } + @Override + public final E unlink(Node node) { - int i = 0; + E element = node.getItem(); - final Object[] result = array; + Node next = node.getNext(); + Node prev = node.getPrev(); - for (Node node = getFirstNode(); node != null; node = node.getNext()) { - result[i++] = node.getItem(); - } - - return array; + if (prev == null) { + setFirstNode(next); + } else { + prev.setNext(next); } - @Override - public String toString() { - return super.toString() + "\n " + pool; + if (next == null) { + setLastNode(prev); + } else { + next.setPrev(prev); } - @Override - public final E unlink(@NotNull final Node node) { - - final E element = node.getItem(); + size--; - final Node next = node.getNext(); - final Node prev = node.getPrev(); + getPool().put(node); - if (prev == null) { - setFirstNode(next); - } else { - prev.setNext(next); - } + return element; + } - if (next == null) { - setLastNode(prev); - } else { - next.setPrev(prev); - } + /** + * Unlink first e. + * + * @param node the node + * @return the e + */ + protected final E unlinkFirst(Node node) { - size--; + E element = node.getItem(); + Node next = node.getNext(); - getPool().put(node); + setFirstNode(next); - return element; + if (next == null) { + setLastNode(null); + } else { + next.setPrev(null); } - /** - * Unlink first e. - * - * @param node the node - * @return the e - */ - protected final E unlinkFirst(@NotNull final Node node) { + size--; - final E element = node.getItem(); + getPool().put(node); - final Node next = node.getNext(); + return element; + } - setFirstNode(next); + /** + * Unlink last e. + * + * @param node the node + * @return the e + */ + protected final E unlinkLast(Node node) { - if (next == null) { - setLastNode(null); - } else { - next.setPrev(null); - } + E element = node.getItem(); + Node prev = node.getPrev(); - size--; + setLastNode(prev); - getPool().put(node); - - return element; + if (prev == null) { + setFirstNode(null); + } else { + prev.setNext(null); } - /** - * Unlink last e. - * - * @param node the node - * @return the e - */ - protected final E unlinkLast(@NotNull final Node node) { - - final E element = node.getItem(); - - final Node prev = node.getPrev(); - - setLastNode(prev); + size--; - if (prev == null) { - setFirstNode(null); - } else { - prev.setNext(null); - } + getPool().put(node); - size--; - - getPool().put(node); - - return element; - } + return element; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/IteratorImpl.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/IteratorImpl.java index b08688a8..7ba28889 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/IteratorImpl.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/IteratorImpl.java @@ -4,8 +4,8 @@ import java.util.NoSuchElementException; import java.util.Objects; import javasabr.rlib.common.util.linkedlist.LinkedList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of an iterator for the LinkedList. @@ -13,130 +13,128 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class IteratorImpl implements Iterator { - /** - * The iteration mode from start to end. - */ - public static final int NEXT = 1; - - /** - * The iteration mode from end to start. - */ - public static final int PREV = 2; - - /** - * The linked list. - */ - @NotNull - private final LinkedList list; - - /** - * The last returned node. - */ - @Nullable - private Node lastReturned; - - /** - * The next node. - */ - private Node next; - - /** - * The iteration mode. - */ - private final int mode; - - /** - * The next index. - */ - private int nextIndex; - - /** - * Instantiates a new Iterator. - * - * @param list the list - * @param mode the mode - */ - protected IteratorImpl(@NotNull final LinkedList list, final int mode) { - this.nextIndex = 0; - this.mode = mode; - this.list = list; - setNext(mode == NEXT ? list.getFirstNode() : mode == PREV ? list.getLastNode() : null); + /** + * The iteration mode from start to end. + */ + public static final int NEXT = 1; + + /** + * The iteration mode from end to start. + */ + public static final int PREV = 2; + + /** + * The linked list. + */ + private final LinkedList list; + + /** + * The last returned node. + */ + @Nullable + private Node lastReturned; + + /** + * The next node. + */ + private Node next; + + /** + * The iteration mode. + */ + private final int mode; + + /** + * The next index. + */ + private int nextIndex; + + /** + * Instantiates a new Iterator. + * + * @param list the list + * @param mode the mode + */ + protected IteratorImpl(LinkedList list, int mode) { + this.nextIndex = 0; + this.mode = mode; + this.list = list; + setNext(mode == NEXT ? list.getFirstNode() : mode == PREV ? list.getLastNode() : null); + } + + @Nullable + private Node getLastReturned() { + return lastReturned; + } + + private void setLastReturned(@Nullable Node lastReturned) { + this.lastReturned = lastReturned; + } + + private Node getNext() { + return Objects.requireNonNull(next); + } + + private void setNext(@Nullable Node next) { + this.next = next; + } + + @Override + public boolean hasNext() { + return mode == NEXT ? nextIndex < list.size() : mode == PREV && nextIndex > 0; + } + + @Override + public E next() { + + if (!hasNext()) { + throw new NoSuchElementException(); } - @Nullable - private Node getLastReturned() { - return lastReturned; - } - - private void setLastReturned(@Nullable final Node lastReturned) { - this.lastReturned = lastReturned; - } - - @NotNull - private Node getNext() { - return Objects.requireNonNull(next); - } - - private void setNext(@Nullable final Node next) { - this.next = next; - } - - @Override - public boolean hasNext() { - return mode == NEXT ? nextIndex < list.size() : mode == PREV && nextIndex > 0; - } - - @Override - public E next() { - - if (!hasNext()) { - throw new NoSuchElementException(); - } - - if (mode == NEXT) { + if (mode == NEXT) { - final Node next = getNext(); + Node next = getNext(); - setNext(next.getNext()); - setLastReturned(next); + setNext(next.getNext()); + setLastReturned(next); - nextIndex++; + nextIndex++; - return next.getItem(); - } else if (mode == PREV) { + return next.getItem(); + } else if (mode == PREV) { - final Node next = getNext(); + Node next = getNext(); - setNext(next.getPrev()); - setLastReturned(next); + setNext(next.getPrev()); + setLastReturned(next); - nextIndex--; + nextIndex--; - return next.getItem(); - } - - return null; + return next.getItem(); } - @Override - public void remove() { - - final Node lastReturned = getLastReturned(); + throw new NoSuchElementException(); + } - if (lastReturned == null) { - throw new IllegalStateException(); - } + @Override + public void remove() { - list.unlink(lastReturned); + Node lastReturned = getLastReturned(); + if (lastReturned == null) { + throw new IllegalStateException(); + } - if (mode == NEXT) { - nextIndex--; - } else if (mode == PREV) { - nextIndex++; - } + list.unlink(lastReturned); - setLastReturned(null); + if (mode == NEXT) { + nextIndex--; + } else if (mode == PREV) { + nextIndex++; } + + setLastReturned(null); + } } \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java index f3c439b3..e84b4fa2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java @@ -12,84 +12,84 @@ */ public final class Node implements Reusable { - /** - * The item. - */ - private E item; + /** + * The item. + */ + private E item; - /** - * The prev node. - */ - @Nullable - private Node prev; + /** + * The prev node. + */ + @Nullable + private Node prev; - /** - * The next node. - */ - @Nullable - private Node next; + /** + * The next node. + */ + @Nullable + private Node next; - @Override - public void free() { - item = null; - prev = null; - next = null; - } + @Override + public void free() { + item = null; + prev = null; + next = null; + } - /** - * Gets item. - * - * @return yhe item. - */ - @NotNull - public E getItem() { - return item; - } + /** + * Gets item. + * + * @return yhe item. + */ + @NotNull + public E getItem() { + return item; + } - /** - * Sets item. - * - * @param item yhe item. - */ - public void setItem(@Nullable final E item) { - this.item = item; - } + /** + * Sets item. + * + * @param item yhe item. + */ + public void setItem(@Nullable final E item) { + this.item = item; + } - /** - * Gets next. - * - * @return yhe next node. - */ - @Nullable - public Node getNext() { - return next; - } + /** + * Gets next. + * + * @return yhe next node. + */ + @Nullable + public Node getNext() { + return next; + } - /** - * Sets next. - * - * @param next yhe next node. - */ - public void setNext(@Nullable final Node next) { - this.next = next; - } + /** + * Sets next. + * + * @param next yhe next node. + */ + public void setNext(@Nullable final Node next) { + this.next = next; + } - /** - * Gets prev. - * - * @return yhe prev node. - */ - @Nullable - public Node getPrev() { - return prev; - } + /** + * Gets prev. + * + * @return yhe prev node. + */ + @Nullable + public Node getPrev() { + return prev; + } - /** - * Sets prev. - * - * @param prev yhe prev node. - */ - public void setPrev(@Nullable final Node prev) { - this.prev = prev; - } + /** + * Sets prev. + * + * @param prev yhe prev node. + */ + public void setPrev(@Nullable final Node prev) { + this.prev = prev; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java index f383c0cd..ce7c5a5b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java @@ -11,32 +11,32 @@ */ public class SortedLinkedList> extends FastLinkedList { - private static final long serialVersionUID = -8115760928469233254L; - - /** - * Instantiates a new Sorted linked list. - * - * @param type the type - */ - public SortedLinkedList(final Class type) { - super(type); - } + private static final long serialVersionUID = -8115760928469233254L; - @Override - public boolean add(@NotNull final E element) { - Objects.requireNonNull(element); + /** + * Instantiates a new Sorted linked list. + * + * @param type the type + */ + public SortedLinkedList(final Class type) { + super(type); + } - for (Node node = getFirstNode(); node != null; node = node.getNext()) { + @Override + public boolean add(@NotNull final E element) { + Objects.requireNonNull(element); - final E item = node.getItem(); + for (Node node = getFirstNode(); node != null; node = node.getNext()) { - if (element.compareTo(item) < 0) { - insertBefore(node, element); - return true; - } - } + final E item = node.getItem(); - linkLast(element); + if (element.compareTo(item) < 0) { + insertBefore(node, element); return true; + } } + + linkLast(element); + return true; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystem.java b/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystem.java index 32758db7..50b2d797 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystem.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystem.java @@ -1,126 +1,120 @@ package javasabr.rlib.common.util.os; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * THe class with description of an Operation System. * * @author JavaSaBr */ +@NullMarked public class OperatingSystem { - /** - * The name. - */ - private String name; - - /** - * The version. - */ - private String version; - - /** - * The arch. - */ - private String arch; - - /** - * The distribution. - */ - private String distribution; - - /** - * Instantiates a new Operating system. - */ - public OperatingSystem() { - final OperatingSystemResolver resolver = new OperatingSystemResolver(); - resolver.resolve(this); - } - - /** - * Gets arch. - * - * @return the arch. - */ - @NotNull - public String getArch() { - return arch; - } - - /** - * Sets arch. - * - * @param arch the arch. - */ - public void setArch(@NotNull final String arch) { - this.arch = arch; - } - - /** - * Gets distribution. - * - * @return the distribution. - */ - @Nullable - public String getDistribution() { - return distribution; - } - - /** - * Sets distribution. - * - * @param distribution the distribution. - */ - public void setDistribution(@Nullable final String distribution) { - this.distribution = distribution; - } - - /** - * Gets name. - * - * @return the name. - */ - @NotNull - public String getName() { - return name; - } - - /** - * Sets name. - * - * @param name the name. - */ - public void setName(@NotNull final String name) { - this.name = name; - } - - /** - * Gets version. - * - * @return the version. - */ - @NotNull - public String getVersion() { - return version; - } - - /** - * Sets version. - * - * @param version the version. - */ - public void setVersion(@NotNull final String version) { - this.version = version; - } - - @Override - public String toString() { - return "OperatingSystem{" + - "name='" + name + '\'' + - ", version='" + version + '\'' + - ", arch='" + arch + '\'' + - ", distribution='" + distribution + '\'' + - '}'; - } + /** + * The name. + */ + private String name; + + /** + * The version. + */ + private String version; + + /** + * The arch. + */ + private String arch; + + /** + * The distribution. + */ + private String distribution; + + /** + * Instantiates a new Operating system. + */ + public OperatingSystem() { + final OperatingSystemResolver resolver = new OperatingSystemResolver(); + resolver.resolve(this); + } + + /** + * Gets arch. + * + * @return the arch. + */ + public String getArch() { + return arch; + } + + /** + * Sets arch. + * + * @param arch the arch. + */ + public void setArch(final String arch) { + this.arch = arch; + } + + /** + * Gets distribution. + * + * @return the distribution. + */ + @Nullable + public String getDistribution() { + return distribution; + } + + /** + * Sets distribution. + * + * @param distribution the distribution. + */ + public void setDistribution(@Nullable final String distribution) { + this.distribution = distribution; + } + + /** + * Gets name. + * + * @return the name. + */ + public String getName() { + return name; + } + + /** + * Sets name. + * + * @param name the name. + */ + public void setName(final String name) { + this.name = name; + } + + /** + * Gets version. + * + * @return the version. + */ + public String getVersion() { + return version; + } + + /** + * Sets version. + * + * @param version the version. + */ + public void setVersion(final String version) { + this.version = version; + } + + @Override + public String toString() { + return "OperatingSystem{" + "name='" + name + '\'' + ", version='" + version + '\'' + ", arch='" + arch + '\'' + + ", distribution='" + distribution + '\'' + '}'; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystemResolver.java b/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystemResolver.java index 9ab1ef20..162e29c3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystemResolver.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/os/OperatingSystemResolver.java @@ -12,275 +12,279 @@ import java.util.List; import java.util.Map; import java.util.Scanner; +import org.jspecify.annotations.NullMarked; /** * THe resolver of OS information. * * @author JavaSaBr */ +@NullMarked public class OperatingSystemResolver { - /** - * The constant FILE_PROC_VERSION. - */ - public static final String FILE_PROC_VERSION = "/proc/version"; - /** - * The constant FILE_ETC_ISSUE. - */ - public static final String FILE_ETC_ISSUE = "/etc/issue"; - /** - * The constant FILE_ETC. - */ - public static final String FILE_ETC = "/etc/"; - /** - * The constant FILE_ETC_SYSTEM_RELEASE. - */ - public static final String FILE_ETC_SYSTEM_RELEASE = "/etc/system-release"; - /** - * The constant FILE_ETC_LSB_RELEASE. - */ - public static final String FILE_ETC_LSB_RELEASE = "/etc/lsb-release"; - - /** - * The constant PROP_PRETTY_NAME. - */ - public static final String PROP_PRETTY_NAME = "PRETTY_NAME"; - /** - * The constant PROP_DISTRIB_CODENAME. - */ - public static final String PROP_DISTRIB_CODENAME = "DISTRIB_CODENAME"; - /** - * The constant PROP_DISTRIB_DESCRIPTION. - */ - public static final String PROP_DISTRIB_DESCRIPTION = "DISTRIB_DESCRIPTION"; - - private static final String NAME = System.getProperty("os.name"); - private static final String VERSION = System.getProperty("os.version"); - private static final String ARCH = System.getProperty("os.arch"); - - private static final Map MAC_OS_VERSION_MAPPING = new HashMap<>(); - private static final Map DARWIN_VERSION_MAPPING = new HashMap<>(); - - private static final List LINUX_VERSION_NAMES = new ArrayList<>(); - - static { - MAC_OS_VERSION_MAPPING.put(10.0, "Puma"); - MAC_OS_VERSION_MAPPING.put(10.1, "Cheetah"); - MAC_OS_VERSION_MAPPING.put(10.2, "Jaguar"); - MAC_OS_VERSION_MAPPING.put(10.3, "Panther"); - MAC_OS_VERSION_MAPPING.put(10.4, "Tiger"); - MAC_OS_VERSION_MAPPING.put(10.5, "Leopard"); - MAC_OS_VERSION_MAPPING.put(10.6, "Snow Leopard"); - MAC_OS_VERSION_MAPPING.put(10.7, "Snow Lion"); - MAC_OS_VERSION_MAPPING.put(10.8, "Mountain Lion"); - MAC_OS_VERSION_MAPPING.put(10.9, "Mavericks"); - MAC_OS_VERSION_MAPPING.put(10.10, "Yosemite"); - MAC_OS_VERSION_MAPPING.put(10.11, "El Capitan "); - MAC_OS_VERSION_MAPPING.put(10.12, "Sierra"); - MAC_OS_VERSION_MAPPING.put(10.13, "High Sierra"); - - DARWIN_VERSION_MAPPING.put(5, "Puma"); - DARWIN_VERSION_MAPPING.put(6, "Jaguar"); - DARWIN_VERSION_MAPPING.put(7, "Panther"); - DARWIN_VERSION_MAPPING.put(8, "Tiger"); - DARWIN_VERSION_MAPPING.put(9, "Leopard"); - DARWIN_VERSION_MAPPING.put(10, "Snow Leopard"); - DARWIN_VERSION_MAPPING.put(11, "Lion"); - DARWIN_VERSION_MAPPING.put(12, "Mountain Lion"); - DARWIN_VERSION_MAPPING.put(13, "Mavericks"); - DARWIN_VERSION_MAPPING.put(14, "Yosemite"); - - LINUX_VERSION_NAMES.addAll(Arrays.asList("Linux", "SunOS")); + /** + * The constant FILE_PROC_VERSION. + */ + public static final String FILE_PROC_VERSION = "/proc/version"; + /** + * The constant FILE_ETC_ISSUE. + */ + public static final String FILE_ETC_ISSUE = "/etc/issue"; + /** + * The constant FILE_ETC. + */ + public static final String FILE_ETC = "/etc/"; + /** + * The constant FILE_ETC_SYSTEM_RELEASE. + */ + public static final String FILE_ETC_SYSTEM_RELEASE = "/etc/system-release"; + /** + * The constant FILE_ETC_LSB_RELEASE. + */ + public static final String FILE_ETC_LSB_RELEASE = "/etc/lsb-release"; + + /** + * The constant PROP_PRETTY_NAME. + */ + public static final String PROP_PRETTY_NAME = "PRETTY_NAME"; + /** + * The constant PROP_DISTRIB_CODENAME. + */ + public static final String PROP_DISTRIB_CODENAME = "DISTRIB_CODENAME"; + /** + * The constant PROP_DISTRIB_DESCRIPTION. + */ + public static final String PROP_DISTRIB_DESCRIPTION = "DISTRIB_DESCRIPTION"; + + private static final String NAME = System.getProperty("os.name"); + private static final String VERSION = System.getProperty("os.version"); + private static final String ARCH = System.getProperty("os.arch"); + + private static final Map MAC_OS_VERSION_MAPPING = new HashMap<>(); + private static final Map DARWIN_VERSION_MAPPING = new HashMap<>(); + + private static final List LINUX_VERSION_NAMES = new ArrayList<>(); + + static { + MAC_OS_VERSION_MAPPING.put(10.0, "Puma"); + MAC_OS_VERSION_MAPPING.put(10.1, "Cheetah"); + MAC_OS_VERSION_MAPPING.put(10.2, "Jaguar"); + MAC_OS_VERSION_MAPPING.put(10.3, "Panther"); + MAC_OS_VERSION_MAPPING.put(10.4, "Tiger"); + MAC_OS_VERSION_MAPPING.put(10.5, "Leopard"); + MAC_OS_VERSION_MAPPING.put(10.6, "Snow Leopard"); + MAC_OS_VERSION_MAPPING.put(10.7, "Snow Lion"); + MAC_OS_VERSION_MAPPING.put(10.8, "Mountain Lion"); + MAC_OS_VERSION_MAPPING.put(10.9, "Mavericks"); + MAC_OS_VERSION_MAPPING.put(10.10, "Yosemite"); + MAC_OS_VERSION_MAPPING.put(10.11, "El Capitan "); + MAC_OS_VERSION_MAPPING.put(10.12, "Sierra"); + MAC_OS_VERSION_MAPPING.put(10.13, "High Sierra"); + + DARWIN_VERSION_MAPPING.put(5, "Puma"); + DARWIN_VERSION_MAPPING.put(6, "Jaguar"); + DARWIN_VERSION_MAPPING.put(7, "Panther"); + DARWIN_VERSION_MAPPING.put(8, "Tiger"); + DARWIN_VERSION_MAPPING.put(9, "Leopard"); + DARWIN_VERSION_MAPPING.put(10, "Snow Leopard"); + DARWIN_VERSION_MAPPING.put(11, "Lion"); + DARWIN_VERSION_MAPPING.put(12, "Mountain Lion"); + DARWIN_VERSION_MAPPING.put(13, "Mavericks"); + DARWIN_VERSION_MAPPING.put(14, "Yosemite"); + + LINUX_VERSION_NAMES.addAll(Arrays.asList("Linux", "SunOS")); + } + + private String findFile(final File dir, final String postfix) { + + final File[] files = dir.listFiles((FilenameFilter) (directory, filename) -> filename.endsWith(postfix)); + + if (files != null && files.length > 0) { + return files[0].getAbsolutePath(); } - private String findFile(final File dir, final String postfix) { + return null; + } - final File[] files = dir.listFiles((FilenameFilter) (directory, filename) -> filename.endsWith(postfix)); + /** + * Resolve. + * + * @param system the system + */ + protected void resolve(final OperatingSystem system) { - if (files != null && files.length > 0) { - return files[0].getAbsolutePath(); - } + system.setName(NAME); + system.setArch(ARCH); + system.setVersion(VERSION); - return null; + // Windows is quite easy to tackle with + if (NAME.startsWith("Windows")) { + system.setDistribution(NAME); } - - /** - * Resolve. - * - * @param system the system - */ - protected void resolve(final OperatingSystem system) { - - system.setName(NAME); - system.setArch(ARCH); - system.setVersion(VERSION); - - // Windows is quite easy to tackle with - if (NAME.startsWith("Windows")) { - system.setDistribution(NAME); - } - // Mac requires a bit of work, but at least it's consistent - else if (NAME.startsWith("Mac")) { - resolveMacOs(system); - } else if (NAME.startsWith("Darwin")) { - resolveDarwinOs(system); - } - // Try to detect other POSIX compliant platforms, now the fun begins - else { - for (final String name : LINUX_VERSION_NAMES) { - if (NAME.startsWith(name)) { - resolveLinuxOs(system); - } - } + // Mac requires a bit of work, but at least it's consistent + else if (NAME.startsWith("Mac")) { + resolveMacOs(system); + } else if (NAME.startsWith("Darwin")) { + resolveDarwinOs(system); + } + // Try to detect other POSIX compliant platforms, now the fun begins + else { + for (final String name : LINUX_VERSION_NAMES) { + if (NAME.startsWith(name)) { + resolveLinuxOs(system); } + } } + } - private void resolveDarwinOs(final OperatingSystem system) { - final String[] versions = VERSION.split("\\."); - system.setDistribution("OS X " + DARWIN_VERSION_MAPPING.get(parseInt(versions[0])) + " (" + VERSION + ")"); - } + private void resolveDarwinOs(final OperatingSystem system) { + final String[] versions = VERSION.split("\\."); + system.setDistribution("OS X " + DARWIN_VERSION_MAPPING.get(parseInt(versions[0])) + " (" + VERSION + ")"); + } - private void resolveLinuxOs(final OperatingSystem system) { + private void resolveLinuxOs(final OperatingSystem system) { - // The most likely is to have a LSB compliant distro - resolveNameFromLsbRelease(system); + // The most likely is to have a LSB compliant distro + resolveNameFromLsbRelease(system); - if (system.getDistribution() != null) { - return; - } + if (system.getDistribution() != null) { + return; + } - // Generic Linux platform name - resolveNameFromFile(system, FILE_ETC_SYSTEM_RELEASE); + // Generic Linux platform name + resolveNameFromFile(system, FILE_ETC_SYSTEM_RELEASE); - if (system.getDistribution() != null) { - return; - } + if (system.getDistribution() != null) { + return; + } - final File dir = new File(FILE_ETC); + final File dir = new File(FILE_ETC); - if (dir.exists()) { + if (dir.exists()) { - // if generic 'system-release' file is not present, then try to find - // another one - resolveNameFromFile(system, findFile(dir, "-release")); + // if generic 'system-release' file is not present, then try to find + // another one + resolveNameFromFile(system, findFile(dir, "-release")); - if (system.getDistribution() != null) { - return; - } + if (system.getDistribution() != null) { + return; + } - // if generic 'system-release' file is not present, then try to find - // '_version' - resolveNameFromFile(system, findFile(dir, "-_version")); + // if generic 'system-release' file is not present, then try to find + // '_version' + resolveNameFromFile(system, findFile(dir, "-_version")); - if (system.getDistribution() != null) { - return; - } + if (system.getDistribution() != null) { + return; + } - // try with /etc/issue file - resolveNameFromFile(system, FILE_ETC_ISSUE); - } + // try with /etc/issue file + resolveNameFromFile(system, FILE_ETC_ISSUE); + } - if (system.getDistribution() != null) { - return; - } + if (system.getDistribution() != null) { + return; + } - // if nothing found yet, looks for the version info - final File fileVersion = new File(FILE_PROC_VERSION); + // if nothing found yet, looks for the version info + final File fileVersion = new File(FILE_PROC_VERSION); - if (fileVersion.exists()) { - resolveNameFromFile(system, fileVersion.getAbsolutePath()); - } + if (fileVersion.exists()) { + resolveNameFromFile(system, fileVersion.getAbsolutePath()); + } - if (system.getDistribution() != null) { - system.setDistribution(NAME); - } + if (system.getDistribution() != null) { + system.setDistribution(NAME); } + } - private void resolveMacOs(final OperatingSystem system) { + private void resolveMacOs(final OperatingSystem system) { - final String[] versions = VERSION.split("\\."); + final String[] versions = VERSION.split("\\."); - final double version = parseDouble(versions[0] + "." + versions[1]); + final double version = parseDouble(versions[0] + "." + versions[1]); - if (version < 10) { - system.setDistribution("Mac OS " + VERSION); - } else { - system.setDistribution("OS X " + MAC_OS_VERSION_MAPPING.get(version) + " (" + VERSION + ")"); - } + if (version < 10) { + system.setDistribution("Mac OS " + VERSION); + } else { + system.setDistribution("OS X " + MAC_OS_VERSION_MAPPING.get(version) + " (" + VERSION + ")"); } + } - private void resolveNameFromFile(final OperatingSystem system, final String filename) { + private void resolveNameFromFile(final OperatingSystem system, final String filename) { - if (filename == null) { - return; - } - - final File file = new File(filename); - - if (!file.exists()) { - return; - } + if (filename == null) { + return; + } - String lastLine = null; + final File file = new File(filename); - try (Scanner scanner = new Scanner(file)) { + if (!file.exists()) { + return; + } - int lineNb = 0; + String lastLine = null; - while (scanner.hasNextLine()) { + try (Scanner scanner = new Scanner(file)) { - final String line = scanner.nextLine(); + int lineNb = 0; - if (lineNb++ == 0) { - lastLine = line; - } + while (scanner.hasNextLine()) { - if (line.startsWith(PROP_PRETTY_NAME)) { - system.setDistribution(line.substring(13, line.length() - 1)); - break; - } - } + final String line = scanner.nextLine(); - } catch (final FileNotFoundException e) { - e.printStackTrace(); + if (lineNb++ == 0) { + lastLine = line; } - if (system.getDistribution() == null) { - system.setDistribution(lastLine); + if (line.startsWith(PROP_PRETTY_NAME)) { + system.setDistribution(line.substring(13, line.length() - 1)); + break; } + } + + } catch (final FileNotFoundException e) { + e.printStackTrace(); } - private void resolveNameFromLsbRelease(final OperatingSystem system) { + if (system.getDistribution() == null) { + system.setDistribution(lastLine); + } + } - final File file = new File(FILE_ETC_LSB_RELEASE); + private void resolveNameFromLsbRelease(final OperatingSystem system) { - if (!file.exists()) { - return; - } + final File file = new File(FILE_ETC_LSB_RELEASE); - String description = null; - String codename = null; + if (!file.exists()) { + return; + } - try (Scanner scanner = new Scanner(file)) { + String description = null; + String codename = null; - while (scanner.hasNextLine()) { + try (Scanner scanner = new Scanner(file)) { - final String line = scanner.nextLine(); + while (scanner.hasNextLine()) { - if (line.startsWith(PROP_DISTRIB_DESCRIPTION)) { - description = line.replace(PROP_DISTRIB_DESCRIPTION + "=", "").replace("\"", ""); - } else if (line.startsWith(PROP_DISTRIB_CODENAME)) { - codename = line.replace(PROP_DISTRIB_CODENAME + "=", ""); - } + final String line = scanner.nextLine(); - if (description != null && codename != null) { - system.setDistribution(description + " (" + codename + ")"); - break; - } - } + if (line.startsWith(PROP_DISTRIB_DESCRIPTION)) { + description = line + .replace(PROP_DISTRIB_DESCRIPTION + "=", "") + .replace("\"", ""); + } else if (line.startsWith(PROP_DISTRIB_CODENAME)) { + codename = line.replace(PROP_DISTRIB_CODENAME + "=", ""); + } - } catch (final FileNotFoundException e) { - e.printStackTrace(); + if (description != null && codename != null) { + system.setDistribution(description + " (" + codename + ")"); + break; } + } + + } catch (final FileNotFoundException e) { + e.printStackTrace(); } + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Pool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Pool.java index a0b255d1..e0a13c1f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Pool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Pool.java @@ -5,8 +5,8 @@ import java.util.function.LongFunction; import java.util.function.Supplier; import javasabr.rlib.common.function.ObjectLongFunction; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface for implementing a pool for storing and reusing any objects. @@ -14,106 +14,106 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface Pool { - /** - * Return true if this pool is empty. - * - * @return true if this pool is empty. - */ - boolean isEmpty(); + /** + * Return true if this pool is empty. + * + * @return true if this pool is empty. + */ + boolean isEmpty(); - /** - * Put the object to this pool. - * - * @param object the object. - */ - void put(@NotNull E object); + /** + * Put the object to this pool. + * + * @param object the object. + */ + void put(E object); - /** - * Remove the object from this pool. - * - * @param object the object. - */ - void remove(@NotNull E object); + /** + * Remove the object from this pool. + * + * @param object the object. + */ + void remove(E object); - /** - * Take an object from this pool. - * - * @return taken object or null if this pool is empty. - */ - @Nullable E take(); + /** + * Take an object from this pool. + * + * @return taken object or null if this pool is empty. + */ + @Nullable + E take(); - /** - * Take an object from this pool or create a new object. - * - * @param factory the factory to create new object if this pool is empty. - * @return taken or created object. - */ - default @NotNull E take(@NotNull Supplier<@NotNull E> factory) { - E take = take(); - return take != null ? take : factory.get(); - } + /** + * Take an object from this pool or create a new object. + * + * @param factory the factory to create new object if this pool is empty. + * @return taken or created object. + */ + default E take(Supplier factory) { + E take = take(); + return take != null ? take : factory.get(); + } - /** - * Take an object from this pool or create a new object. - * - * @param argument the argument. - * @param factory the factory to create new object if this pool is empty. - * @param the argument's type. - * @return taken or created object. - */ - default @NotNull E take(@NotNull T argument, @NotNull Function<@NotNull T, @NotNull E> factory) { - E take = take(); - return take != null ? take : factory.apply(argument); - } + /** + * Take an object from this pool or create a new object. + * + * @param argument the argument. + * @param factory the factory to create new object if this pool is empty. + * @param the argument's type. + * @return taken or created object. + */ + default E take(T argument, Function factory) { + E take = take(); + return take != null ? take : factory.apply(argument); + } - /** - * Take an object from this pool or create a new object. - * - * @param argument the argument. - * @param factory the factory to create new object if this pool is empty. - * @return taken or created object. - */ - default @NotNull E take(long argument, @NotNull LongFunction<@NotNull E> factory) { - E take = take(); - return take != null ? take : factory.apply(argument); - } + /** + * Take an object from this pool or create a new object. + * + * @param argument the argument. + * @param factory the factory to create new object if this pool is empty. + * @return taken or created object. + */ + default E take(long argument, LongFunction factory) { + E take = take(); + return take != null ? take : factory.apply(argument); + } - /** - * Take an object from this pool or create a new object. - * - * @param first the first argument. - * @param second the second argument. - * @param factory the factory to create new object if this pool is empty. - * @param the first argument's type. - * @return taken or created object. - */ - default @NotNull E take( - @NotNull F first, - long second, - @NotNull ObjectLongFunction<@NotNull F, @NotNull E> factory - ) { - E take = take(); - return take != null ? take : factory.apply(first, second); - } + /** + * Take an object from this pool or create a new object. + * + * @param first the first argument. + * @param second the second argument. + * @param factory the factory to create new object if this pool is empty. + * @param the first argument's type. + * @return taken or created object. + */ + default E take( + F first, + long second, + ObjectLongFunction factory) { + E take = take(); + return take != null ? take : factory.apply(first, second); + } - /** - * Take an object from this pool or create a new object. - * - * @param first the first argument. - * @param second the second argument. - * @param factory the factory to create new object if this pool is empty. - * @param the first argument's type. - * @param the second argument's type. - * @return taken or created object. - */ - default @NotNull E take( - @NotNull F first, - @NotNull S second, - @NotNull BiFunction<@NotNull F, @NotNull S, @NotNull E> factory - ) { - E take = take(); - return take != null ? take : factory.apply(first, second); - } + /** + * Take an object from this pool or create a new object. + * + * @param first the first argument. + * @param second the second argument. + * @param factory the factory to create new object if this pool is empty. + * @param the first argument's type. + * @param the second argument's type. + * @return taken or created object. + */ + default E take( + F first, + S second, + BiFunction factory) { + E take = take(); + return take != null ? take : factory.apply(first, second); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/PoolFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/PoolFactory.java index 4e49a5f0..c2d97f4c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/PoolFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/PoolFactory.java @@ -10,112 +10,109 @@ import javasabr.rlib.common.util.pools.impl.FastPool; import javasabr.rlib.common.util.pools.impl.FastReusablePool; import javasabr.rlib.common.util.pools.impl.SynchronizedReusablePool; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory for creating new pools. * * @author JavaSaBr */ +@NullMarked public final class PoolFactory { - /** - * Create a reusable pool based on {@link AtomicReadWriteLock}. - * - * @param type the object's type. - * @param the object's type. - * @return the reusable pool. - */ - public static @NotNull ReusablePool newConcurrentAtomicARSWLockReusablePool( - @NotNull Class type - ) { - return new ConcurrentAtomicARSWLockReusablePool<>(type); - } + /** + * Create a reusable pool based on {@link AtomicReadWriteLock}. + * + * @param type the object's type. + * @param the object's type. + * @return the reusable pool. + */ + public static ReusablePool newConcurrentAtomicARSWLockReusablePool( + Class type) { + return new ConcurrentAtomicARSWLockReusablePool<>(type); + } - /** - * Create a reusable pool based on {@link java.util.concurrent.locks.StampedLock}. - * - * @param type the object's type. - * @param the object's type. - * @return the reusable pool. - */ - public static @NotNull ReusablePool newConcurrentStampedLockReusablePool( - @NotNull Class type - ) { - return new ConcurrentStampedLockReusablePool<>(type); - } + /** + * Create a reusable pool based on {@link java.util.concurrent.locks.StampedLock}. + * + * @param type the object's type. + * @param the object's type. + * @return the reusable pool. + */ + public static ReusablePool newConcurrentStampedLockReusablePool( + Class type) { + return new ConcurrentStampedLockReusablePool<>(type); + } - /** - * Create a reusable pool based on {@link ReentrantARSWLock}. - * - * @param type the object's type. - * @param the object's type. - * @return the reusable pool. - */ - public static @NotNull ReusablePool newConcurrentReentrantRWLockReusablePool( - @NotNull Class type - ) { - return new ConcurrentReentrantRWLockPool<>(type); - } + /** + * Create a reusable pool based on {@link ReentrantARSWLock}. + * + * @param type the object's type. + * @param the object's type. + * @return the reusable pool. + */ + public static ReusablePool newConcurrentReentrantRWLockReusablePool( + Class type) { + return new ConcurrentReentrantRWLockPool<>(type); + } - /** - * Create a reusable pool based on synchronization block. - * - * @param type the object's type. - * @param the object's type. - * @return the reusable pool. - */ - public static @NotNull ReusablePool newSynchronizedReusablePool( - @NotNull Class type - ) { - return new SynchronizedReusablePool<>(type); - } + /** + * Create a reusable pool based on synchronization block. + * + * @param type the object's type. + * @param the object's type. + * @return the reusable pool. + */ + public static ReusablePool newSynchronizedReusablePool( + Class type) { + return new SynchronizedReusablePool<>(type); + } - /** - * Create a reusable pool. - * - * @param type the object's type. - * @param the object's type. - * @return the reusable pool. - */ - public static @NotNull ReusablePool newReusablePool(@NotNull Class type) { - return new FastReusablePool<>(type); - } + /** + * Create a reusable pool. + * + * @param type the object's type. + * @param the object's type. + * @return the reusable pool. + */ + public static ReusablePool newReusablePool(Class type) { + return new FastReusablePool<>(type); + } - /** - * Create a pool based on {@link ReentrantARSWLock}. - * - * @param type the object's type. - * @param the object's type. - * @return the pool. - */ - public static @NotNull Pool newConcurrentAtomicARSWLockPool(@NotNull Class type) { - return new ConcurrentAtomicARSWLockPool<>(type); - } + /** + * Create a pool based on {@link ReentrantARSWLock}. + * + * @param type the object's type. + * @param the object's type. + * @return the pool. + */ + public static Pool newConcurrentAtomicARSWLockPool(Class type) { + return new ConcurrentAtomicARSWLockPool<>(type); + } - /** - * Create a pool based on {@link java.util.concurrent.locks.StampedLock}. - * - * @param type the object's type. - * @param the object's type. - * @return the pool. - */ - public static @NotNull Pool newConcurrentStampedLockPool(@NotNull Class type) { - return new ConcurrentStampedLockPool<>(type); - } + /** + * Create a pool based on {@link java.util.concurrent.locks.StampedLock}. + * + * @param type the object's type. + * @param the object's type. + * @return the pool. + */ + public static Pool newConcurrentStampedLockPool(Class type) { + return new ConcurrentStampedLockPool<>(type); + } - /** - * Create a pool. - * - * @param type the object's type. - * @param the object's type. - * @return the reusable pool. - */ - public static @NotNull Pool newPool(@NotNull Class type) { - return new FastPool<>(type); - } + /** + * Create a pool. + * + * @param type the object's type. + * @param the object's type. + * @return the reusable pool. + */ + public static Pool newPool(Class type) { + return new FastPool<>(type); + } - private PoolFactory() { - throw new IllegalArgumentException(); - } + private PoolFactory() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Reusable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Reusable.java index 70b07089..385c8d76 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Reusable.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/Reusable.java @@ -1,33 +1,32 @@ package javasabr.rlib.common.util.pools; /** - * The interface for implementing reusable objects. You can use reusable objects with {@link - * ReusablePool}*. + * The interface for implementing reusable objects. You can use reusable objects with {@link ReusablePool}*. * * @author JavaSaBr */ public interface Reusable extends AutoCloseable { - /** - * Cleanup this object before storing to a pool. - */ - default void free() { - } + /** + * Cleanup this object before storing to a pool. + */ + default void free() { + } - /** - * Prepares to reuse this object before taking from a pool. - */ - default void reuse() { - } + /** + * Prepares to reuse this object before taking from a pool. + */ + default void reuse() { + } - /** - * Stores this object to a pool. - */ - default void release() { - } + /** + * Stores this object to a pool. + */ + default void release() { + } - @Override - default void close() { - release(); - } + @Override + default void close() { + release(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/ReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/ReusablePool.java index da36bfa1..f78e7fcb 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/ReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/ReusablePool.java @@ -6,5 +6,4 @@ * @param the type parameter * @author JavaSaBr */ -public interface ReusablePool extends Pool { -} +public interface ReusablePool extends Pool {} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockPool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockPool.java index 555e6a45..110d8f8a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockPool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockPool.java @@ -4,23 +4,23 @@ import javasabr.rlib.common.util.array.ConcurrentArray; import javasabr.rlib.common.util.array.impl.ConcurrentAtomicARSWLockArray; import javasabr.rlib.common.util.pools.Pool; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * The threadsafe implementation of the {@link Pool} using like a storage the {@link - * ConcurrentAtomicARSWLockArray}*. + * The threadsafe implementation of the {@link Pool} using like a storage the {@link ConcurrentAtomicARSWLockArray}*. * * @param the object's type. * @author JavaSaBr */ +@NullMarked public class ConcurrentAtomicARSWLockPool extends ConcurrentPool { - public ConcurrentAtomicARSWLockPool(@NotNull Class type) { - super(type); - } + public ConcurrentAtomicARSWLockPool(Class type) { + super(type); + } - @Override - protected @NotNull ConcurrentArray createPool(@NotNull Class type) { - return ArrayFactory.newConcurrentAtomicARSWLockArray(type); - } + @Override + protected ConcurrentArray createPool(Class type) { + return ArrayFactory.newConcurrentAtomicARSWLockArray(type); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java index 4d4017f3..64d502d4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java @@ -6,22 +6,24 @@ import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * The threadsafe implementation of the {@link ReusablePool} using like a storage the {@link - * ConcurrentAtomicARSWLockArray}*. + * The threadsafe implementation of the {@link ReusablePool} using like a storage the + * {@link ConcurrentAtomicARSWLockArray}*. * * @param the type parameter * @author JavaSaBr */ +@NullMarked public class ConcurrentAtomicARSWLockReusablePool extends ConcurrentReusablePool { - public ConcurrentAtomicARSWLockReusablePool(@NotNull Class type) { - super(type); - } + public ConcurrentAtomicARSWLockReusablePool(Class type) { + super(type); + } - @Override - protected @NotNull ConcurrentArray createPool(@NotNull Class type) { - return ArrayFactory.newConcurrentAtomicARSWLockArray(type); - } + @Override + protected ConcurrentArray createPool(Class type) { + return ArrayFactory.newConcurrentAtomicARSWLockArray(type); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentPool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentPool.java index e2363c49..0bac4cfd 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentPool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentPool.java @@ -3,8 +3,8 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ConcurrentArray; import javasabr.rlib.common.util.pools.Pool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base concurrent implementation of the {@link Pool}. @@ -12,53 +12,53 @@ * @param the object's type. * @author JavaSaBr */ +@NullMarked public abstract class ConcurrentPool implements Pool { - /** - * The storage of objects. - */ - @NotNull - protected final ConcurrentArray pool; + /** + * The storage of objects. + */ + protected final ConcurrentArray pool; - public ConcurrentPool(@NotNull Class type) { - this.pool = createPool(type); - } - - protected abstract @NotNull ConcurrentArray createPool(@NotNull Class type); + public ConcurrentPool(Class type) { + this.pool = createPool(type); + } - @Override - public boolean isEmpty() { - return pool.isEmpty(); - } + protected abstract ConcurrentArray createPool(Class type); - @Override - public void put(@NotNull E object) { - pool.runInWriteLock(object, Array::add); - } + @Override + public boolean isEmpty() { + return pool.isEmpty(); + } - @Override - public void remove(@NotNull E object) { - pool.runInWriteLock(object, Array::fastRemove); - } + @Override + public void put(E object) { + pool.runInWriteLock(object, Array::add); + } - @Override - public @Nullable E take() { + @Override + public void remove(E object) { + pool.runInWriteLock(object, Array::fastRemove); + } - if (pool.isEmpty()) { - return null; - } + @Override + public @Nullable E take() { - E object = pool.getInWriteLock(Array::pop); + if (pool.isEmpty()) { + return null; + } - if (object == null) { - return null; - } + E object = pool.getInWriteLock(Array::pop); - return object; + if (object == null) { + return null; } - @Override - public String toString() { - return pool.toString(); - } + return object; + } + + @Override + public String toString() { + return pool.toString(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java index 7d1f3423..84b46ddc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java @@ -6,22 +6,24 @@ import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * The threadsafe implementation of the {@link ReusablePool} using like a storage the {@link - * ConcurrentReentrantRWLockArray}*. + * The threadsafe implementation of the {@link ReusablePool} using like a storage the + * {@link ConcurrentReentrantRWLockArray}*. * * @param the type parameter * @author JavaSaBr */ +@NullMarked public class ConcurrentReentrantRWLockPool extends ConcurrentReusablePool { - public ConcurrentReentrantRWLockPool(@NotNull Class type) { - super(type); - } + public ConcurrentReentrantRWLockPool(Class type) { + super(type); + } - @Override - protected @NotNull ConcurrentArray createPool(@NotNull Class type) { - return ArrayFactory.newConcurrentReentrantRWLockArray(type); - } + @Override + protected ConcurrentArray createPool(Class type) { + return ArrayFactory.newConcurrentReentrantRWLockArray(type); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReusablePool.java index 58d6784a..4d27a9cd 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReusablePool.java @@ -3,8 +3,8 @@ import javasabr.rlib.common.util.pools.Pool; import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base concurrent implementation of the {@link Pool} for {@link Reusable} objects. @@ -12,28 +12,28 @@ * @param the object's type. * @author JavaSaBr */ -public abstract class ConcurrentReusablePool extends ConcurrentPool - implements ReusablePool { +@NullMarked +public abstract class ConcurrentReusablePool extends ConcurrentPool implements ReusablePool { - public ConcurrentReusablePool(@NotNull Class type) { - super(type); - } - - @Override - public void put(@NotNull E object) { - object.free(); - super.put(object); - } + public ConcurrentReusablePool(Class type) { + super(type); + } - @Override - public @Nullable E take() { + @Override + public void put(E object) { + object.free(); + super.put(object); + } - E object = super.take(); + @Override + public @Nullable E take() { - if (object != null) { - object.reuse(); - } + E object = super.take(); - return object; + if (object != null) { + object.reuse(); } + + return object; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java index 64ed84e6..1b7be3de 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java @@ -5,22 +5,23 @@ import javasabr.rlib.common.util.array.impl.ConcurrentStampedLockArray; import javasabr.rlib.common.util.pools.Pool; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * The threadsafe implementation of the {@link Pool} using like a storage the {@link - * ConcurrentStampedLockArray}*. + * The threadsafe implementation of the {@link Pool} using like a storage the {@link ConcurrentStampedLockArray}*. * * @param the object's type. * @author JavaSaBr */ +@NullMarked public class ConcurrentStampedLockPool extends ConcurrentPool { - public ConcurrentStampedLockPool(@NotNull Class type) { - super(type); - } + public ConcurrentStampedLockPool(Class type) { + super(type); + } - @Override - protected @NotNull ConcurrentArray createPool(@NotNull Class type) { - return ArrayFactory.newConcurrentStampedLockArray(type); - } + @Override + protected ConcurrentArray createPool(Class type) { + return ArrayFactory.newConcurrentStampedLockArray(type); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java index 225ee468..9a5d2401 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java @@ -6,22 +6,24 @@ import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** - * The threadsafe implementation of the {@link ReusablePool} using like a storage the {@link - * ConcurrentStampedLockArray}*. + * The threadsafe implementation of the {@link ReusablePool} using like a storage the + * {@link ConcurrentStampedLockArray}*. * * @param the type parameter * @author JavaSaBr */ +@NullMarked public class ConcurrentStampedLockReusablePool extends ConcurrentReusablePool { - public ConcurrentStampedLockReusablePool(@NotNull Class type) { - super(type); - } + public ConcurrentStampedLockReusablePool(Class type) { + super(type); + } - @Override - protected @NotNull ConcurrentArray createPool(@NotNull Class type) { - return ArrayFactory.newConcurrentStampedLockArray(type); - } + @Override + protected ConcurrentArray createPool(Class type) { + return ArrayFactory.newConcurrentStampedLockArray(type); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastPool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastPool.java index a40aea42..6d467746 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastPool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastPool.java @@ -2,8 +2,8 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.pools.Pool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The fast implementation of the {@link Pool}. It isn't threadsafe. @@ -11,47 +11,47 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class FastPool implements Pool { - /** - * The storage of objects. - */ - @NotNull - private final Array pool; + /** + * The storage of objects. + */ + private final Array pool; - public FastPool(@NotNull Class type) { - this.pool = Array.ofType(type); - } + public FastPool(Class type) { + this.pool = Array.ofType(type); + } - @Override - public boolean isEmpty() { - return pool.isEmpty(); - } + @Override + public boolean isEmpty() { + return pool.isEmpty(); + } - @Override - public void put(@NotNull E object) { - pool.add(object); - } + @Override + public void put(E object) { + pool.add(object); + } - @Override - public void remove(@NotNull E object) { - pool.fastRemove(object); - } + @Override + public void remove(E object) { + pool.fastRemove(object); + } - @Override - public @Nullable E take() { + @Override + public @Nullable E take() { - E object = pool.pop(); + E object = pool.pop(); - if (object == null) { - return null; - } - - return object; + if (object == null) { + return null; } - @Override - public String toString() { - return pool.toString(); - } + return object; + } + + @Override + public String toString() { + return pool.toString(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastReusablePool.java index c53b84df..d9c8761d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/FastReusablePool.java @@ -2,8 +2,8 @@ import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The fast implementation of the {@link ReusablePool}. It isn't threadsafe. @@ -11,26 +11,27 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class FastReusablePool extends FastPool implements ReusablePool { - public FastReusablePool(@NotNull Class type) { - super(type); - } - - public void put(@NotNull E object) { - object.free(); - super.put(object); - } + public FastReusablePool(Class type) { + super(type); + } - @Override - public @Nullable E take() { + public void put(E object) { + object.free(); + super.put(object); + } - E object = super.take(); + @Override + public @Nullable E take() { - if (object != null) { - object.reuse(); - } + E object = super.take(); - return object; + if (object != null) { + object.reuse(); } + + return object; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/SynchronizedReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/SynchronizedReusablePool.java index 0c95a36d..4dcf1efd 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/SynchronizedReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/SynchronizedReusablePool.java @@ -2,8 +2,8 @@ import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The implementation of the {@link ReusablePool} using synchronization for take/put methods. @@ -11,29 +11,30 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class SynchronizedReusablePool extends FastReusablePool { - public SynchronizedReusablePool(@NotNull Class type) { - super(type); - } + public SynchronizedReusablePool(Class type) { + super(type); + } - @Override - public synchronized boolean isEmpty() { - return super.isEmpty(); - } + @Override + public synchronized boolean isEmpty() { + return super.isEmpty(); + } - @Override - public synchronized void put(@NotNull E object) { - super.put(object); - } + @Override + public synchronized void put(E object) { + super.put(object); + } - @Override - public synchronized void remove(@NotNull E object) { - super.remove(object); - } + @Override + public synchronized void remove(E object) { + super.remove(object); + } - @Override - public synchronized @Nullable E take() { - return super.take(); - } + @Override + public synchronized @Nullable E take() { + return super.take(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java index e4aea224..104b82fe 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java @@ -1,80 +1,80 @@ package javasabr.rlib.common.util.random; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * @author JavaSaBr */ +@NullMarked public final class FastRandom implements Random { - /** - * Генератор чисел. - */ - private final java.util.Random random; - - /** - * Instantiates a new Fast random. - */ - public FastRandom() { - this.random = new java.util.Random(); - } - - @Override - public void byteArray(@NotNull final byte[] array, final int offset, int length) { - - length += offset; - - for (int i = offset; i < length; i++) { - array[i] = (byte) nextInt(256); - } + /** + * Генератор чисел. + */ + private final java.util.Random random; + + /** + * Instantiates a new Fast random. + */ + public FastRandom() { + this.random = new java.util.Random(); + } + + @Override + public void byteArray(byte @NotNull [] array, int offset, int length) { + length += offset; + for (int i = offset; i < length; i++) { + array[i] = (byte) nextInt(256); } + } - @Override - public boolean chance(final float chance) { - - if (chance < 0F) { - return false; - } else if (chance > 99.999999F) { - return true; - } + @Override + public boolean chance(float chance) { - return nextFloat() * nextInt(100) <= chance; + if (chance < 0F) { + return false; + } else if (chance > 99.999999F) { + return true; } - @Override - public boolean chance(final int chance) { + return nextFloat() * nextInt(100) <= chance; + } - if (chance < 1) { - return false; - } else if (chance > 99) { - return true; - } - - return nextInt(99) <= chance; - } + @Override + public boolean chance(int chance) { - @Override - public float nextFloat() { - return random.nextFloat(); + if (chance < 1) { + return false; + } else if (chance > 99) { + return true; } - @Override - public int nextInt() { - return random.nextInt(); - } - - @Override - public int nextInt(final int max) { - return random.nextInt(max); - } - - @Override - public int nextInt(final int min, final int max) { - return min + nextInt(Math.abs(max - min) + 1); - } - - @Override - public long nextLong(final long min, final long max) { - return min + Math.round(nextFloat() * Math.abs(max - min) + 1); - } + return nextInt(99) <= chance; + } + + @Override + public float nextFloat() { + return random.nextFloat(); + } + + @Override + public int nextInt() { + return random.nextInt(); + } + + @Override + public int nextInt(int max) { + return random.nextInt(max); + } + + @Override + public int nextInt(int min, int max) { + return min + nextInt(Math.abs(max - min) + 1); + } + + @Override + public long nextLong(long min, long max) { + return min + Math.round(nextFloat() * Math.abs(max - min) + 1); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java index 366049ea..ee44d261 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java @@ -1,76 +1,77 @@ package javasabr.rlib.common.util.random; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to implement a random. * * @author JavaSaBr */ +@NullMarked public interface Random { - /** - * Fill an array random values. - * - * @param array the array. - * @param offset the offset. - * @param length the length. - */ - void byteArray(@NotNull byte[] array, int offset, int length); + /** + * Fill an array random values. + * + * @param array the array. + * @param offset the offset. + * @param length the length. + */ + void byteArray(byte[] array, int offset, int length); - /** - * Try to get success. - * - * @param chance the chance from 0 to 100. - * @return true if the chance was successful. - */ - boolean chance(float chance); + /** + * Try to get success. + * + * @param chance the chance from 0 to 100. + * @return true if the chance was successful. + */ + boolean chance(float chance); - /** - * Try to get success. - * - * @param chance the chance from 0 to 100. - * @return true if the chance was successful. - */ - boolean chance(int chance); + /** + * Try to get success. + * + * @param chance the chance from 0 to 100. + * @return true if the chance was successful. + */ + boolean chance(int chance); - /** - * Get a next random float value. - * - * @return the next value from 0.0 to 1.0. - */ - float nextFloat(); + /** + * Get a next random float value. + * + * @return the next value from 0.0 to 1.0. + */ + float nextFloat(); - /** - * Get a next random int value. - * - * @return the next value from int_min to int_max. - */ - int nextInt(); + /** + * Get a next random int value. + * + * @return the next value from int_min to int_max. + */ + int nextInt(); - /** - * Get a next random int value. - * - * @param max the max value. - * @return the next value [0, max]. - */ - int nextInt(int max); + /** + * Get a next random int value. + * + * @param max the max value. + * @return the next value [0, max]. + */ + int nextInt(int max); - /** - * Get a next random int value. - * - * @param min the min value. - * @param max the max value. - * @return the next value [min, max]. - */ - int nextInt(int min, int max); + /** + * Get a next random int value. + * + * @param min the min value. + * @param max the max value. + * @return the next value [min, max]. + */ + int nextInt(int min, int max); - /** - * Get a next random long value. - * - * @param min the min value. - * @param max the max value. - * @return the next value [min, max]. - */ - long nextLong(long min, long max); + /** + * Get a next random long value. + * + * @param min the min value. + * @param max the max value. + * @return the next value [min, max]. + */ + long nextLong(long min, long max); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java index 793ce87b..236ec549 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java @@ -1,25 +1,25 @@ package javasabr.rlib.common.util.random; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory of randoms implementations. * * @author JavaSaBr */ +@NullMarked public final class RandomFactory { - /** - * New fast random random. - * - * @return the random - */ - @NotNull - public static Random newFastRandom() { - return new FastRandom(); - } + /** + * New fast random random. + * + * @return the random + */ + public static Random newFastRandom() { + return new FastRandom(); + } - private RandomFactory() { - throw new RuntimeException(); - } + private RandomFactory() { + throw new RuntimeException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/AbstractReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/AbstractReference.java index 8d56da8c..470d2939 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/AbstractReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/AbstractReference.java @@ -5,5 +5,4 @@ * * @author JavaSaBr */ -public abstract class AbstractReference implements Reference { -} +public abstract class AbstractReference implements Reference {} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ByteReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ByteReference.java index 2a1e0df5..6e1df650 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ByteReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ByteReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class ByteReference extends AbstractReference { - /** - * The value of this reference. - */ - private byte value; + /** + * The value of this reference. + */ + private byte value; - @Override - public void free() { - this.value = 0; - } + @Override + public void free() { + this.value = 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/CharReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/CharReference.java index a8fbe17d..03d4162c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/CharReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/CharReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class CharReference extends AbstractReference { - /** - * The value of this reference. - */ - private char value; + /** + * The value of this reference. + */ + private char value; - @Override - public void free() { - this.value = 0; - } + @Override + public void free() { + this.value = 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/DoubleReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/DoubleReference.java index 39b58a1f..6928a861 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/DoubleReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/DoubleReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class DoubleReference extends AbstractReference { - /** - * The value of this reference. - */ - private double value; + /** + * The value of this reference. + */ + private double value; - @Override - public void free() { - this.value = 0D; - } + @Override + public void free() { + this.value = 0D; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/FloatReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/FloatReference.java index b4957e66..f41335b0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/FloatReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/FloatReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class FloatReference extends AbstractReference { - /** - * The value of this reference. - */ - private float value; + /** + * The value of this reference. + */ + private float value; - @Override - public void free() { - this.value = 0F; - } + @Override + public void free() { + this.value = 0F; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalByteReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalByteReference.java index 7b350fe7..e3fbab7f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalByteReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalByteReference.java @@ -7,8 +7,8 @@ */ final class GlobalByteReference extends ByteReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalCharReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalCharReference.java index 09067df5..b704f558 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalCharReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalCharReference.java @@ -7,8 +7,8 @@ */ final class GlobalCharReference extends CharReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalDoubleReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalDoubleReference.java index 4dbbfdbb..3037f881 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalDoubleReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalDoubleReference.java @@ -7,8 +7,8 @@ */ final class GlobalDoubleReference extends DoubleReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalFloatReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalFloatReference.java index a37de740..dde133c9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalFloatReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalFloatReference.java @@ -7,8 +7,8 @@ */ final class GlobalFloatReference extends FloatReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalIntReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalIntReference.java index 5713ad36..cd664ba8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalIntReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalIntReference.java @@ -7,8 +7,8 @@ */ final class GlobalIntReference extends IntReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalLongReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalLongReference.java index 3546a873..eb5d7d36 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalLongReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalLongReference.java @@ -7,8 +7,8 @@ */ final class GlobalLongReference extends LongReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalObjectReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalObjectReference.java index c38932ea..4a9fb83c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalObjectReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalObjectReference.java @@ -7,8 +7,8 @@ */ final class GlobalObjectReference extends ObjectReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalShortReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalShortReference.java index b2d70c9b..509b4b96 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalShortReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/GlobalShortReference.java @@ -7,8 +7,8 @@ */ final class GlobalShortReference extends ShortReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/IntReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/IntReference.java index 01a9aa15..4eab7962 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/IntReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/IntReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class IntReference extends AbstractReference { - /** - * The value of this reference. - */ - private int value; + /** + * The value of this reference. + */ + private int value; - @Override - public void free() { - this.value = 0; - } + @Override + public void free() { + this.value = 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/LongReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/LongReference.java index 4e2e8984..19a51d3c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/LongReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/LongReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class LongReference extends AbstractReference { - /** - * The value of this reference. - */ - private long value; + /** + * The value of this reference. + */ + private long value; - @Override - public void free() { - this.value = 0L; - } + @Override + public void free() { + this.value = 0L; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ObjectReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ObjectReference.java index fae14125..ebf4ed56 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ObjectReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ObjectReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class ObjectReference extends AbstractReference { - /** - * The object of this reference. - */ - private T value; + /** + * The object of this reference. + */ + private T value; - @Override - public void free() { - this.value = null; - } + @Override + public void free() { + this.value = null; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/Reference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/Reference.java index 9bb8752e..ace1ae9f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/Reference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/Reference.java @@ -7,5 +7,4 @@ * * @author JavaSaBr */ -public interface Reference extends Reusable { -} +public interface Reference extends Reusable {} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ReferenceFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ReferenceFactory.java index d43d2746..f987e5fc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ReferenceFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ReferenceFactory.java @@ -2,364 +2,413 @@ import javasabr.rlib.common.util.pools.PoolFactory; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr */ +@NullMarked public final class ReferenceFactory { - private static final ReusablePool GLOBAL_BYTE_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalByteReference.class); - private static final ReusablePool GLOBAL_SHORT_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalShortReference.class); - private static final ReusablePool GLOBAL_CHAR_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalCharReference.class); - private static final ReusablePool GLOBAL_INT_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalIntReference.class); - private static final ReusablePool GLOBAL_LONG_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalLongReference.class); - private static final ReusablePool GLOBAL_FLOAT_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalFloatReference.class); - private static final ReusablePool GLOBAL_DOUBLE_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalDoubleReference.class); - private static final ReusablePool GLOBAL_OBJ_REF_POOL = - PoolFactory.newConcurrentStampedLockReusablePool(GlobalObjectReference.class); - - private static final ThreadLocal> TL_BYTE_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLByteReference.class)); - private static final ThreadLocal> TL_SHORT_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLShortReference.class)); - private static final ThreadLocal> TL_CHAR_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLCharReference.class)); - private static final ThreadLocal> TL_INT_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLIntReference.class)); - private static final ThreadLocal> TL_LONG_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLLongReference.class)); - private static final ThreadLocal> TL_FLOAT_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLFloatReference.class)); - private static final ThreadLocal> TL_DOUBLE_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLDoubleReference.class)); - private static final ThreadLocal> TL_OBJECT_REF_POOL = - ThreadLocal.withInitial(() -> PoolFactory.newReusablePool(TLObjectReference.class)); - - /** - * @param value the init value. - * @return the new byte ref. - * @since 9.2.1 - */ - public static @NotNull ByteReference newByteRef(byte value) { - return new ByteReference(value); - } - - /** - * @param value the init value. - * @return the new byte ref. - * @since 9.2.1 - */ - public static @NotNull ByteReference newReusableByteRef(byte value) { - var ref = GLOBAL_BYTE_REF_POOL.take(GlobalByteReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new byte ref. - * @since 9.2.1 - */ - public static @NotNull ByteReference newThreadLocalByteRef(byte value) { - var ref = TL_BYTE_REF_POOL.get().take(TLByteReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new short ref. - * @since 9.2.1 - */ - public static @NotNull ShortReference newShortRef(short value) { - return new ShortReference(value); - } - - /** - * @param value the init value. - * @return the new short ref. - * @since 9.2.1 - */ - public static @NotNull ShortReference newReusableShortRef(short value) { - var ref = GLOBAL_SHORT_REF_POOL.take(GlobalShortReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new short ref. - * @since 9.2.1 - */ - public static @NotNull ShortReference newThreadLocalShortRef(short value) { - var ref = TL_SHORT_REF_POOL.get().take(TLShortReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new char ref. - * @since 9.2.1 - */ - public static @NotNull CharReference newCharRef(char value) { - return new CharReference(value); - } - - /** - * @param value the init value. - * @return the new char ref. - * @since 9.2.1 - */ - public static @NotNull CharReference newReusableCharRef(char value) { - var ref = GLOBAL_CHAR_REF_POOL.take(GlobalCharReference::new); - ref.setValue(value); - return ref ; - } - - /** - * @param value the init value. - * @return the new char ref. - * @since 9.2.1 - */ - public static @NotNull CharReference newThreadLocalCharRef(char value) { - var ref = TL_CHAR_REF_POOL.get().take(TLCharReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new int ref. - * @since 9.2.1 - */ - public static @NotNull IntReference newIntRef(int value) { - return new IntReference(value); - } - - /** - * @param value the init value. - * @return the new int ref. - * @since 9.2.1 - */ - public static @NotNull IntReference newReusableIntRef(int value) { - var ref = GLOBAL_INT_REF_POOL.take(GlobalIntReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new int ref. - * @since 9.2.1 - */ - public static @NotNull IntReference newThreadLocalIntRef(int value) { - var ref = TL_INT_REF_POOL.get().take(TLIntReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new long ref. - * @since 9.2.1 - */ - public static @NotNull LongReference newLongRef(long value) { - return new LongReference(value); - } - - /** - * @param value the init value. - * @return the new long ref. - * @since 9.2.1 - */ - public static @NotNull LongReference newReusableLongRef(long value) { - var ref = GLOBAL_LONG_REF_POOL.take(GlobalLongReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new long ref. - * @since 9.2.1 - */ - public static @NotNull LongReference newThreadLocalLongRef(long value) { - var ref = TL_LONG_REF_POOL.get().take(TLLongReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new float ref. - * @since 9.2.1 - */ - public static @NotNull FloatReference newFloatRef(float value) { - return new FloatReference(value); - } - - /** - * @param value the init value. - * @return the new float ref. - * @since 9.2.1 - */ - public static @NotNull FloatReference newReusableFloatRef(float value) { - var ref = GLOBAL_FLOAT_REF_POOL.take(GlobalFloatReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new float ref. - * @since 9.2.1 - */ - public static @NotNull FloatReference newThreadLocalFloatRef(float value) { - var ref = TL_FLOAT_REF_POOL.get().take(TLFloatReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new double ref. - * @since 9.2.1 - */ - public static @NotNull DoubleReference newDoubleRef(double value) { - return new DoubleReference(value); - } - - /** - * @param value the init value. - * @return the new double ref. - * @since 9.2.1 - */ - public static @NotNull DoubleReference newReusableDoubleRef(double value) { - var ref = GLOBAL_DOUBLE_REF_POOL.take(GlobalDoubleReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @return the new double ref. - * @since 9.2.1 - */ - public static @NotNull DoubleReference newThreadLocalDoubleRef(double value) { - var ref = TL_DOUBLE_REF_POOL.get().take(TLDoubleReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @param the object's type. - * @return the new object ref. - * @since 9.2.1 - */ - public static @NotNull ObjectReference newObjRef(@Nullable T value) { - return new ObjectReference<>(value); - } - - /** - * @param value the init value. - * @param the object's type. - * @return the new object ref. - * @since 9.2.1 - */ - public static @NotNull ObjectReference newReusableObjRef(@Nullable T value) { - ObjectReference ref = GLOBAL_OBJ_REF_POOL.take(GlobalObjectReference::new); - ref.setValue(value); - return ref; - } - - /** - * @param value the init value. - * @param the object's type. - * @return the new object ref. - * @since 9.2.1 - */ - public static @NotNull ObjectReference newThreadLocalObjRef(@Nullable T value) { - TLObjectReference ref = TL_OBJECT_REF_POOL.get().take(TLObjectReference::new); - ref.setValue(value); - return ref; - } - - static void release(@NotNull GlobalByteReference ref) { - GLOBAL_BYTE_REF_POOL.put(ref); - } - - static void release(@NotNull GlobalShortReference ref) { - GLOBAL_SHORT_REF_POOL.put(ref); - } - - static void release(@NotNull GlobalCharReference ref) { - GLOBAL_CHAR_REF_POOL.put(ref); - } - - static void release(@NotNull GlobalIntReference ref) { - GLOBAL_INT_REF_POOL.put(ref); - } - - static void release(@NotNull GlobalLongReference ref) { - GLOBAL_LONG_REF_POOL.put(ref); - } - - static void release(@NotNull GlobalFloatReference ref) { - GLOBAL_FLOAT_REF_POOL.put(ref); - } - - static void release(@NotNull GlobalDoubleReference ref) { - GLOBAL_DOUBLE_REF_POOL.put(ref); - } - - static void release(@NotNull GlobalObjectReference ref) { - GLOBAL_OBJ_REF_POOL.put(ref); - } - - static void release(@NotNull TLByteReference ref) { - TL_BYTE_REF_POOL.get().put(ref); - } - - static void release(@NotNull TLShortReference ref) { - TL_SHORT_REF_POOL.get().put(ref); - } - - static void release(@NotNull TLCharReference ref) { - TL_CHAR_REF_POOL.get().put(ref); - } - - static void release(@NotNull TLIntReference ref) { - TL_INT_REF_POOL.get().put(ref); - } - - static void release(@NotNull TLLongReference ref) { - TL_LONG_REF_POOL.get().put(ref); - } - - static void release(@NotNull TLFloatReference ref) { - TL_FLOAT_REF_POOL.get().put(ref); - } - - static void release(@NotNull TLDoubleReference ref) { - TL_DOUBLE_REF_POOL.get().put(ref); - } - - static void release(@NotNull TLObjectReference ref) { - TL_OBJECT_REF_POOL.get().put(ref); - } - - private ReferenceFactory() { - throw new IllegalArgumentException(); - } + private static final ReusablePool GLOBAL_BYTE_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalByteReference.class); + private static final ReusablePool GLOBAL_SHORT_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalShortReference.class); + private static final ReusablePool GLOBAL_CHAR_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalCharReference.class); + private static final ReusablePool GLOBAL_INT_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalIntReference.class); + private static final ReusablePool GLOBAL_LONG_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalLongReference.class); + private static final ReusablePool GLOBAL_FLOAT_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalFloatReference.class); + private static final ReusablePool GLOBAL_DOUBLE_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalDoubleReference.class); + private static final ReusablePool GLOBAL_OBJ_REF_POOL = + PoolFactory.newConcurrentStampedLockReusablePool( + GlobalObjectReference.class); + + private static final ThreadLocal> TL_BYTE_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLByteReference.class)); + private static final ThreadLocal> TL_SHORT_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLShortReference.class)); + private static final ThreadLocal> TL_CHAR_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLCharReference.class)); + private static final ThreadLocal> TL_INT_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLIntReference.class)); + private static final ThreadLocal> TL_LONG_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLLongReference.class)); + private static final ThreadLocal> TL_FLOAT_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLFloatReference.class)); + private static final ThreadLocal> TL_DOUBLE_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLDoubleReference.class)); + private static final ThreadLocal> TL_OBJECT_REF_POOL = + ThreadLocal.withInitial(() -> PoolFactory.newReusablePool( + TLObjectReference.class)); + + /** + * @param value the init value. + * @return the new byte ref. + * @since 9.2.1 + */ + public static ByteReference newByteRef(byte value) { + return new ByteReference(value); + } + + /** + * @param value the init value. + * @return the new byte ref. + * @since 9.2.1 + */ + public static ByteReference newReusableByteRef(byte value) { + var ref = GLOBAL_BYTE_REF_POOL.take(GlobalByteReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new byte ref. + * @since 9.2.1 + */ + public static ByteReference newThreadLocalByteRef(byte value) { + var ref = TL_BYTE_REF_POOL + .get() + .take(TLByteReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new short ref. + * @since 9.2.1 + */ + public static ShortReference newShortRef(short value) { + return new ShortReference(value); + } + + /** + * @param value the init value. + * @return the new short ref. + * @since 9.2.1 + */ + public static ShortReference newReusableShortRef(short value) { + var ref = GLOBAL_SHORT_REF_POOL.take(GlobalShortReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new short ref. + * @since 9.2.1 + */ + public static ShortReference newThreadLocalShortRef(short value) { + var ref = TL_SHORT_REF_POOL + .get() + .take(TLShortReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new char ref. + * @since 9.2.1 + */ + public static CharReference newCharRef(char value) { + return new CharReference(value); + } + + /** + * @param value the init value. + * @return the new char ref. + * @since 9.2.1 + */ + public static CharReference newReusableCharRef(char value) { + var ref = GLOBAL_CHAR_REF_POOL.take(GlobalCharReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new char ref. + * @since 9.2.1 + */ + public static CharReference newThreadLocalCharRef(char value) { + var ref = TL_CHAR_REF_POOL + .get() + .take(TLCharReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new int ref. + * @since 9.2.1 + */ + public static IntReference newIntRef(int value) { + return new IntReference(value); + } + + /** + * @param value the init value. + * @return the new int ref. + * @since 9.2.1 + */ + public static IntReference newReusableIntRef(int value) { + var ref = GLOBAL_INT_REF_POOL.take(GlobalIntReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new int ref. + * @since 9.2.1 + */ + public static IntReference newThreadLocalIntRef(int value) { + var ref = TL_INT_REF_POOL + .get() + .take(TLIntReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new long ref. + * @since 9.2.1 + */ + public static LongReference newLongRef(long value) { + return new LongReference(value); + } + + /** + * @param value the init value. + * @return the new long ref. + * @since 9.2.1 + */ + public static LongReference newReusableLongRef(long value) { + var ref = GLOBAL_LONG_REF_POOL.take(GlobalLongReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new long ref. + * @since 9.2.1 + */ + public static LongReference newThreadLocalLongRef(long value) { + var ref = TL_LONG_REF_POOL + .get() + .take(TLLongReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new float ref. + * @since 9.2.1 + */ + public static FloatReference newFloatRef(float value) { + return new FloatReference(value); + } + + /** + * @param value the init value. + * @return the new float ref. + * @since 9.2.1 + */ + public static FloatReference newReusableFloatRef(float value) { + var ref = GLOBAL_FLOAT_REF_POOL.take(GlobalFloatReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new float ref. + * @since 9.2.1 + */ + public static FloatReference newThreadLocalFloatRef(float value) { + var ref = TL_FLOAT_REF_POOL + .get() + .take(TLFloatReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new double ref. + * @since 9.2.1 + */ + public static DoubleReference newDoubleRef(double value) { + return new DoubleReference(value); + } + + /** + * @param value the init value. + * @return the new double ref. + * @since 9.2.1 + */ + public static DoubleReference newReusableDoubleRef(double value) { + var ref = GLOBAL_DOUBLE_REF_POOL.take(GlobalDoubleReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @return the new double ref. + * @since 9.2.1 + */ + public static DoubleReference newThreadLocalDoubleRef(double value) { + var ref = TL_DOUBLE_REF_POOL + .get() + .take(TLDoubleReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @param the object's type. + * @return the new object ref. + * @since 9.2.1 + */ + public static ObjectReference newObjRef(@Nullable T value) { + return new ObjectReference<>(value); + } + + /** + * @param value the init value. + * @param the object's type. + * @return the new object ref. + * @since 9.2.1 + */ + public static ObjectReference newReusableObjRef(@Nullable T value) { + ObjectReference ref = GLOBAL_OBJ_REF_POOL.take(GlobalObjectReference::new); + ref.setValue(value); + return ref; + } + + /** + * @param value the init value. + * @param the object's type. + * @return the new object ref. + * @since 9.2.1 + */ + public static ObjectReference newThreadLocalObjRef(@Nullable T value) { + TLObjectReference ref = TL_OBJECT_REF_POOL + .get() + .take(TLObjectReference::new); + ref.setValue(value); + return ref; + } + + static void release(GlobalByteReference ref) { + GLOBAL_BYTE_REF_POOL.put(ref); + } + + static void release(GlobalShortReference ref) { + GLOBAL_SHORT_REF_POOL.put(ref); + } + + static void release(GlobalCharReference ref) { + GLOBAL_CHAR_REF_POOL.put(ref); + } + + static void release(GlobalIntReference ref) { + GLOBAL_INT_REF_POOL.put(ref); + } + + static void release(GlobalLongReference ref) { + GLOBAL_LONG_REF_POOL.put(ref); + } + + static void release(GlobalFloatReference ref) { + GLOBAL_FLOAT_REF_POOL.put(ref); + } + + static void release(GlobalDoubleReference ref) { + GLOBAL_DOUBLE_REF_POOL.put(ref); + } + + static void release(GlobalObjectReference ref) { + GLOBAL_OBJ_REF_POOL.put(ref); + } + + static void release(TLByteReference ref) { + TL_BYTE_REF_POOL + .get() + .put(ref); + } + + static void release(TLShortReference ref) { + TL_SHORT_REF_POOL + .get() + .put(ref); + } + + static void release(TLCharReference ref) { + TL_CHAR_REF_POOL + .get() + .put(ref); + } + + static void release(TLIntReference ref) { + TL_INT_REF_POOL + .get() + .put(ref); + } + + static void release(TLLongReference ref) { + TL_LONG_REF_POOL + .get() + .put(ref); + } + + static void release(TLFloatReference ref) { + TL_FLOAT_REF_POOL + .get() + .put(ref); + } + + static void release(TLDoubleReference ref) { + TL_DOUBLE_REF_POOL + .get() + .put(ref); + } + + static void release(TLObjectReference ref) { + TL_OBJECT_REF_POOL + .get() + .put(ref); + } + + private ReferenceFactory() { + throw new IllegalArgumentException(); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ShortReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ShortReference.java index e712c14a..b152ea53 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ShortReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/ShortReference.java @@ -20,13 +20,13 @@ @EqualsAndHashCode(callSuper = false) public class ShortReference extends AbstractReference { - /** - * The value of this reference. - */ - private short value; + /** + * The value of this reference. + */ + private short value; - @Override - public void free() { - this.value = 0; - } + @Override + public void free() { + this.value = 0; + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLByteReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLByteReference.java index 381b5878..2db653f0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLByteReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLByteReference.java @@ -7,8 +7,8 @@ */ final class TLByteReference extends ByteReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLCharReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLCharReference.java index bc387bfa..f633fb21 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLCharReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLCharReference.java @@ -7,8 +7,8 @@ */ final class TLCharReference extends CharReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLDoubleReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLDoubleReference.java index d2185350..99574a0e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLDoubleReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLDoubleReference.java @@ -7,8 +7,8 @@ */ final class TLDoubleReference extends DoubleReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLFloatReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLFloatReference.java index 0a3f07ff..7cf1ca29 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLFloatReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLFloatReference.java @@ -7,8 +7,8 @@ */ final class TLFloatReference extends FloatReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLIntReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLIntReference.java index 48c5310c..e8eade8c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLIntReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLIntReference.java @@ -7,8 +7,8 @@ */ final class TLIntReference extends IntReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLLongReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLLongReference.java index 84f28220..5ce8b30c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLLongReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLLongReference.java @@ -7,8 +7,8 @@ */ final class TLLongReference extends LongReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLObjectReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLObjectReference.java index 7fc75a23..4c200e32 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLObjectReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLObjectReference.java @@ -7,8 +7,8 @@ */ final class TLObjectReference extends ObjectReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLShortReference.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLShortReference.java index decd05e7..f9def83f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLShortReference.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ref/TLShortReference.java @@ -7,8 +7,8 @@ */ final class TLShortReference extends ShortReference { - @Override - public void release() { - ReferenceFactory.release(this); - } + @Override + public void release() { + ReferenceFactory.release(this); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java b/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java index 06ee95d4..3b18a6bf 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java @@ -4,23 +4,26 @@ public class BaseTest { - protected static class Type1 { - public static final Type1 EXAMPLE = new Type1(); - } + protected static class Type1 { + public static final Type1 EXAMPLE = new Type1(); + } - protected static class Type2 { - public static final Type2 EXAMPLE = new Type2(); - } + protected static class Type2 { + public static final Type2 EXAMPLE = new Type2(); + } - public void assertType(@NotNull T object, @NotNull Class type) { - if (!type.isInstance(object)) { - throw new ClassCastException(); - } + public void assertType(@NotNull T object, @NotNull Class type) { + if (!type.isInstance(object)) { + throw new ClassCastException(); } + } - public void assertIntType(@NotNull Integer val) {} + public void assertIntType(@NotNull Integer val) { + } - public void assertLongType(@NotNull Long val) {} + public void assertLongType(@NotNull Long val) { + } - public void assertFloatType(@NotNull Float val) {} + public void assertFloatType(@NotNull Float val) { + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/classpath/ClasspathScannerTests.java b/rlib-common/src/test/java/javasabr/rlib/common/classpath/ClasspathScannerTests.java index 161f6acd..5feba7f3 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/classpath/ClasspathScannerTests.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/classpath/ClasspathScannerTests.java @@ -10,19 +10,19 @@ */ public class ClasspathScannerTests { - @Test - void testSystemClasspathScanner() { + @Test + void testSystemClasspathScanner() { - var scanner = ClassPathScannerFactory.newDefaultScanner(); - scanner.setUseSystemClasspath(true); - scanner.scan(); + var scanner = ClassPathScannerFactory.newDefaultScanner(); + scanner.setUseSystemClasspath(true); + scanner.scan(); - var implementations = scanner.findImplements(Collection.class); + var implementations = scanner.findImplements(Collection.class); - Assertions.assertFalse(implementations.isEmpty()); + Assertions.assertFalse(implementations.isEmpty()); - var inherited = scanner.findInherited(AbstractArray.class); + var inherited = scanner.findInherited(AbstractArray.class); - Assertions.assertFalse(inherited.isEmpty()); - } + Assertions.assertFalse(inherited.isEmpty()); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/compiler/CompilerTests.java b/rlib-common/src/test/java/javasabr/rlib/common/compiler/CompilerTests.java index e213bc60..6b75fe61 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/compiler/CompilerTests.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/compiler/CompilerTests.java @@ -13,23 +13,24 @@ */ public class CompilerTests { - @Test - void compileTest() - throws URISyntaxException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + @Test + void compileTest() + throws URISyntaxException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { - var javaSource = getClass() - .getResource("/java/source/TestCompileJavaSource.java"); + var javaSource = getClass().getResource("/java/source/TestCompileJavaSource.java"); - var compiler = CompilerFactory.newDefaultCompiler(); - var compiled = compiler.compile(javaSource.toURI()); + var compiler = CompilerFactory.newDefaultCompiler(); + var compiled = compiler.compile(javaSource.toURI()); - Assertions.assertEquals(1, compiled.length); - Assertions.assertEquals("TestCompileJavaSource", compiled[0].getName()); + Assertions.assertEquals(1, compiled.length); + Assertions.assertEquals("TestCompileJavaSource", compiled[0].getName()); - var instance = ClassUtils.newInstance(compiled[0]); - var method = instance.getClass().getMethod("makeString"); - var result = method.invoke(instance); + var instance = ClassUtils.newInstance(compiled[0]); + var method = instance + .getClass() + .getMethod("makeString"); + var result = method.invoke(instance); - Assertions.assertEquals("testString", result); - } + Assertions.assertEquals("testString", result); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/concurrent/executor/TestThreadPoolTaskExecutor.java b/rlib-common/src/test/java/javasabr/rlib/common/concurrent/executor/TestThreadPoolTaskExecutor.java index fd953e66..bca06b78 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/concurrent/executor/TestThreadPoolTaskExecutor.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/concurrent/executor/TestThreadPoolTaskExecutor.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.concurrent.executor; import javasabr.rlib.common.concurrent.GroupThreadFactory; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.concurrent.executor.impl.ThreadPoolTaskExecutor; import javasabr.rlib.common.concurrent.util.ThreadUtils; import org.junit.jupiter.api.Assertions; @@ -13,36 +13,36 @@ */ public class TestThreadPoolTaskExecutor { - private static final int TASK_LIMIT = 100; + private static final int TASK_LIMIT = 100; - public void test() { + public void test() { - final String header = TestThreadPoolTaskExecutor.class.getSimpleName() + ": "; + final String header = TestThreadPoolTaskExecutor.class.getSimpleName() + ": "; - System.out.println(header + " start test executor..."); + System.out.println(header + " start test executor..."); - final GroupThreadFactory factory = new GroupThreadFactory("test_executor", Thread::new, Thread.NORM_PRIORITY); - final TaskExecutor executor = new ThreadPoolTaskExecutor(factory, 5, 5) { + final GroupThreadFactory factory = new GroupThreadFactory("test_executor", Thread::new, Thread.NORM_PRIORITY); + final TaskExecutor executor = new ThreadPoolTaskExecutor(factory, 5, 5) { - @Override - protected Object getLocalObjects(final Thread thread) { - return new Object(); - } - }; + @Override + protected Object getLocalObjects(final Thread thread) { + return new Object(); + } + }; - final AtomicInteger counter = new AtomicInteger(); + final ReusableAtomicInteger counter = new ReusableAtomicInteger(); - for (int i = 0; i < TASK_LIMIT; i++) { - executor.execute((local, currentTime) -> { - counter.incrementAndGet(); - ThreadUtils.sleep(1); - }); - } + for (int i = 0; i < TASK_LIMIT; i++) { + executor.execute((local, currentTime) -> { + counter.incrementAndGet(); + ThreadUtils.sleep(1); + }); + } - ThreadUtils.sleep(30); + ThreadUtils.sleep(30); - Assertions.assertEquals(TASK_LIMIT, counter.get()); + Assertions.assertEquals(TASK_LIMIT, counter.get()); - System.out.println(header + " test executor finished."); - } + System.out.println(header + " test executor finished."); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/concurrent/lock/TestPrimitiveAtomicReadWriteLock.java b/rlib-common/src/test/java/javasabr/rlib/common/concurrent/lock/TestPrimitiveAtomicReadWriteLock.java index 7f50542e..707b3198 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/concurrent/lock/TestPrimitiveAtomicReadWriteLock.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/concurrent/lock/TestPrimitiveAtomicReadWriteLock.java @@ -16,127 +16,128 @@ * * @author JavaSaBr */ -public class TestPrimitiveAtomicReadWriteLock { +public class TestPrimitiveAtomicReadWriteLock { - public void test() throws InterruptedException, ExecutionException { + public void test() throws InterruptedException, ExecutionException { - final String header = TestPrimitiveAtomicReadWriteLock.class.getSimpleName() + ": "; + final String header = TestPrimitiveAtomicReadWriteLock.class.getSimpleName() + ": "; - System.out.println(header + "start test..."); + System.out.println(header + "start test..."); - final AsyncReadSyncWriteLock atomicLock = new AtomicReadWriteLock(); - final AsyncReadSyncWriteLock reentrantLock = new ReentrantARSWLock(); + final AsyncReadSyncWriteLock atomicLock = new AtomicReadWriteLock(); + final AsyncReadSyncWriteLock reentrantLock = new ReentrantARSWLock(); - final ExecutorService service = Executors.newFixedThreadPool(10); + final ExecutorService service = Executors.newFixedThreadPool(10); - long atomicTime = testImpl(service, atomicLock); - System.out.println(header + "atomic lock execute " + atomicTime); - atomicTime = testImpl(service, atomicLock); - System.out.println(header + "atomic lock execute " + atomicTime); - long reentrantTime = testImpl(service, reentrantLock); - System.out.println(header + "reentrant lock execute " + reentrantTime); - reentrantTime = testImpl(service, reentrantLock); - System.out.println(header + "reentrant lock execute " + reentrantTime); + long atomicTime = testImpl(service, atomicLock); + System.out.println(header + "atomic lock execute " + atomicTime); + atomicTime = testImpl(service, atomicLock); + System.out.println(header + "atomic lock execute " + atomicTime); + long reentrantTime = testImpl(service, reentrantLock); + System.out.println(header + "reentrant lock execute " + reentrantTime); + reentrantTime = testImpl(service, reentrantLock); + System.out.println(header + "reentrant lock execute " + reentrantTime); - atomicTime = testImpl(service, atomicLock); - System.out.println(header + "atomic lock execute " + atomicTime); - reentrantTime = testImpl(service, reentrantLock); - System.out.println(header + "reentrant lock execute " + reentrantTime); - } - - @SuppressWarnings("unused") - private long testImpl(final ExecutorService service, final AsyncReadSyncWriteLock lock) throws InterruptedException, ExecutionException { + atomicTime = testImpl(service, atomicLock); + System.out.println(header + "atomic lock execute " + atomicTime); + reentrantTime = testImpl(service, reentrantLock); + System.out.println(header + "reentrant lock execute " + reentrantTime); + } - System.gc(); + @SuppressWarnings("unused") + private long testImpl(final ExecutorService service, final AsyncReadSyncWriteLock lock) + throws InterruptedException, ExecutionException { - final List list = new ArrayList<>(); + System.gc(); - final Runnable writeTask = () -> { + final List list = new ArrayList<>(); - final Random random = new Random(); + final Runnable writeTask = () -> { - for (int i = 0, length = 15; i < length; i++) { + final Random random = new Random(); - lock.syncLock(); - try { + for (int i = 0, length = 15; i < length; i++) { - for (int g = 0; g < 5; g++) { - list.add(random.nextInt(120)); - } + lock.syncLock(); + try { - } finally { - lock.syncUnlock(); - } + for (int g = 0; g < 5; g++) { + list.add(random.nextInt(120)); + } - ThreadUtils.sleep(10); + } finally { + lock.syncUnlock(); + } - lock.syncLock(); - try { + ThreadUtils.sleep(10); - for (int g = 0; g < 5; g++) { - list.add(random.nextInt(120)); - } + lock.syncLock(); + try { - } finally { - lock.syncUnlock(); - } + for (int g = 0; g < 5; g++) { + list.add(random.nextInt(120)); + } - ThreadUtils.sleep(10); - } - }; + } finally { + lock.syncUnlock(); + } - final Runnable readTask = () -> { + ThreadUtils.sleep(10); + } + }; - for (int i = 0, length = 500; i < length; i++) { + final Runnable readTask = () -> { - lock.asyncLock(); - try { + for (int i = 0, length = 500; i < length; i++) { - int sum = 0; + lock.asyncLock(); + try { - for (final int val1 : list) { - sum += val1; - } + int sum = 0; - } finally { - lock.asyncUnlock(); - } + for (final int val1 : list) { + sum += val1; + } - ThreadUtils.sleep(1); + } finally { + lock.asyncUnlock(); + } - lock.asyncLock(); - try { + ThreadUtils.sleep(1); - int sum = 0; + lock.asyncLock(); + try { - for (final int val1 : list) { - sum += val1; - } + int sum = 0; - } finally { - lock.asyncUnlock(); - } + for (final int val1 : list) { + sum += val1; + } - ThreadUtils.sleep(1); - } - }; + } finally { + lock.asyncUnlock(); + } - final long time = System.currentTimeMillis(); + ThreadUtils.sleep(1); + } + }; - final List> futures = new ArrayList<>(); + final long time = System.currentTimeMillis(); - for (int i = 0, length = 3; i < length; i++) { - futures.add(service.submit(writeTask)); - } + final List> futures = new ArrayList<>(); - for (int i = 0, length = 7; i < length; i++) { - futures.add(service.submit(readTask)); - } + for (int i = 0, length = 3; i < length; i++) { + futures.add(service.submit(writeTask)); + } - for (final Future future : futures) { - future.get(); - } + for (int i = 0, length = 7; i < length; i++) { + futures.add(service.submit(readTask)); + } - return System.currentTimeMillis() - time; + for (final Future future : futures) { + future.get(); } + + return System.currentTimeMillis() - time; + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/geom/QuaternionTests.java b/rlib-common/src/test/java/javasabr/rlib/common/geom/QuaternionTests.java index ab2888d8..5d050c72 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/geom/QuaternionTests.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/geom/QuaternionTests.java @@ -5,42 +5,42 @@ /** * QuaternionTests.java - * + * * @author zcxv * @date 18.09.2018 */ public class QuaternionTests { - @Test - void testDirections() { - - var originForward = new Vector3f(0.5f, 0, 1f).normalizeLocal(); - var originBackward = originForward.negate(); - var originRight = new Vector3f(1f, 0, -0.5f).normalizeLocal(); - var originLeft = originRight.negate(); - var originUp = new Vector3f(0, 1f, 0); - var originDown = originUp.negate(); - - var quaternion = new Quaternion4f(); - quaternion.lookAt(originForward, Vector3f.UNIT_Y); - - var side = quaternion.getDirection(DirectionType.FRONT); - - Assertions.assertTrue(originForward.equals(side, 0.001f)); - - quaternion.getDirection(DirectionType.BEHIND, side); - Assertions.assertTrue(originBackward.equals(side, 0.001f)); - - quaternion.getDirection(DirectionType.RIGHT, side); - Assertions.assertTrue(originRight.equals(side, 0.001f)); - - quaternion.getDirection(DirectionType.LEFT, side); - Assertions.assertTrue(originLeft.equals(side, 0.001f)); - - quaternion.getDirection(DirectionType.UP, side); - Assertions.assertTrue(originUp.equals(side, 0.001f)); - - quaternion.getDirection(DirectionType.DOWN, side); - Assertions.assertTrue(originDown.equals(side, 0.001f)); - } + @Test + void testDirections() { + + var originForward = new Vector3f(0.5f, 0, 1f).normalizeLocal(); + var originBackward = originForward.negate(); + var originRight = new Vector3f(1f, 0, -0.5f).normalizeLocal(); + var originLeft = originRight.negate(); + var originUp = new Vector3f(0, 1f, 0); + var originDown = originUp.negate(); + + var quaternion = new Quaternion4f(); + quaternion.lookAt(originForward, Vector3f.UNIT_Y); + + var side = quaternion.getDirection(DirectionType.FRONT); + + Assertions.assertTrue(originForward.equals(side, 0.001f)); + + quaternion.getDirection(DirectionType.BEHIND, side); + Assertions.assertTrue(originBackward.equals(side, 0.001f)); + + quaternion.getDirection(DirectionType.RIGHT, side); + Assertions.assertTrue(originRight.equals(side, 0.001f)); + + quaternion.getDirection(DirectionType.LEFT, side); + Assertions.assertTrue(originLeft.equals(side, 0.001f)); + + quaternion.getDirection(DirectionType.UP, side); + Assertions.assertTrue(originUp.equals(side, 0.001f)); + + quaternion.getDirection(DirectionType.DOWN, side); + Assertions.assertTrue(originDown.equals(side, 0.001f)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/plugin/extension/ExtensionPointTests.java b/rlib-common/src/test/java/javasabr/rlib/common/plugin/extension/ExtensionPointTests.java index a08a272c..8f7afc5a 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/plugin/extension/ExtensionPointTests.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/plugin/extension/ExtensionPointTests.java @@ -11,31 +11,31 @@ */ public class ExtensionPointTests { - @Test - void registerExtensionTest() { + @Test + void registerExtensionTest() { - var point = new ExtensionPoint(); - point.register("a", "b"); - point.register("c"); + var point = new ExtensionPoint(); + point.register("a", "b"); + point.register("c"); - Assertions.assertIterableEquals(Arrays.asList("a", "b", "c"), point.getExtensions()); - } + Assertions.assertIterableEquals(Arrays.asList("a", "b", "c"), point.getExtensions()); + } - @Test - void registerExtensionPointTest() { + @Test + void registerExtensionPointTest() { - var manager = ExtensionPointManager.getInstance(); - manager.addExtension("Test1", 5); - manager.addExtension("Test1", 6, 7); + var manager = ExtensionPointManager.getInstance(); + manager.addExtension("Test1", 5); + manager.addExtension("Test1", 6, 7); - var test2 = ExtensionPointManager.register("Test2"); - test2.register(1, 2); - test2.register(3); + var test2 = ExtensionPointManager.register("Test2"); + test2.register(1, 2); + test2.register(3); - var forTest1 = manager.getExtensionPoint("Test1"); - var forTest2 = manager.getExtensionPoint("Test2"); + var forTest1 = manager.getExtensionPoint("Test1"); + var forTest2 = manager.getExtensionPoint("Test2"); - Assertions.assertIterableEquals(Arrays.asList(5, 6, 7), forTest1.getExtensions()); - Assertions.assertIterableEquals(Arrays.asList(1, 2, 3), forTest2.getExtensions()); - } + Assertions.assertIterableEquals(Arrays.asList(5, 6, 7), forTest1.getExtensions()); + Assertions.assertIterableEquals(Arrays.asList(1, 2, 3), forTest2.getExtensions()); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/plugin/system/PluginSystemTests.java b/rlib-common/src/test/java/javasabr/rlib/common/plugin/system/PluginSystemTests.java index b8da4f48..4096d662 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/plugin/system/PluginSystemTests.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/plugin/system/PluginSystemTests.java @@ -11,15 +11,16 @@ */ public class PluginSystemTests { - @Test - public void test() { + @Test + public void test() { - var pluginSystem = PluginSystemFactory.newBasePluginSystem(); - pluginSystem.setAppVersion(new Version("0.0.1")); - pluginSystem.configureEmbeddedPluginPath(Paths.get("../gradle/")); + var pluginSystem = PluginSystemFactory.newBasePluginSystem(); + pluginSystem.setAppVersion(new Version("0.0.1")); + pluginSystem.configureEmbeddedPluginPath(Paths.get("../gradle/")); - pluginSystem.preLoad(ForkJoinPool.commonPool()) - .thenApply(system -> system.initialize(ForkJoinPool.commonPool())) - .join(); - } + pluginSystem + .preLoad(ForkJoinPool.commonPool()) + .thenApply(system -> system.initialize(ForkJoinPool.commonPool())) + .join(); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/ArrayUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/ArrayUtilsTest.java index 52a96903..d008c665 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/ArrayUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/ArrayUtilsTest.java @@ -17,159 +17,122 @@ */ public class ArrayUtilsTest { - @Test - void convertIntegerArrayToIntArrayTest() { - - Integer[] integers = ArrayFactory.toArray(1, 2, 3, 4, 5); - int[] ints = ArrayUtils.toIntArray(integers); - int[] empty = ArrayUtils.toIntArray(new Integer[0]); - - assertArrayEquals(ints, ArrayFactory.toIntArray(1, 2, 3, 4, 5)); - assertArrayEquals(empty, ArrayFactory.toIntArray()); - } - - @Test - void convertStringToIntArrayTest() { - - assertArrayEquals( - ArrayUtils.toIntArray("1,2,3,4,5", ","), - ArrayFactory.toIntArray(1, 2, 3, 4, 5) - ); - assertArrayEquals( - ArrayUtils.toIntArray(" 1 ,2 , 3,4, 5", ","), - ArrayFactory.toIntArray(1, 2, 3, 4, 5) - ); - assertArrayEquals( - ArrayUtils.toIntArray(" 1 ,2 , 3,4, 5", ","), - ArrayFactory.toIntArray(1, 2, 3, 4, 5) - ); - - assertThrows(NumberFormatException.class, - () -> ArrayUtils.toIntArray(" 1 ,,2 , 3,4, 5,", ",")); - assertThrows(NumberFormatException.class, - () -> ArrayUtils.toIntArray(" 1 ,qwd , 3,4, 5", ",")); - assertThrows(NumberFormatException.class, - () -> ArrayUtils.toIntArray(" 1 ,2.5 , 3,4, 5", ",")); - } - - @Test - void mapNullableTest() { - - String[] nullStrings = null; - String[] emptyStrings = new String[0]; - String[] singleStrings = ArrayFactory.toArray("5"); - String[] strings = ArrayFactory.toArray("8", "1", "6"); - - Assertions.assertNull(ArrayUtils.mapNullable(nullStrings, Integer::parseInt, Integer.class)); - - assertArrayEquals( - new Integer[0], ArrayUtils.mapNullable(emptyStrings, Integer::parseInt, Integer.class) - ); - assertArrayEquals( - ArrayFactory.toArray(5), ArrayUtils.mapNullable(singleStrings, Integer::parseInt, Integer.class) - ); - assertArrayEquals( - ArrayFactory.toArray(8, 1, 6), ArrayUtils.mapNullable(strings, Integer::parseInt, Integer.class) - ); - } - - @Test - void longsToIntsTest() { - - assertArrayEquals( - ArrayFactory.toIntArray(1, 5, 3), - ArrayUtils.longsToInts(ArrayFactory.toLongArray(1, 5, 3)) - ); - - assertArrayEquals( - ArrayUtils.EMPTY_INT_ARRAY, - ArrayUtils.longsToInts(ArrayUtils.EMPTY_LONG_ARRAY) - ); - } - - @Test - void mapTest() { - - String[] emptyStrings = new String[0]; - String[] singleStrings = ArrayFactory.toArray("5"); - String[] strings = ArrayFactory.toArray("8", "1", "6"); - - assertArrayEquals( - new Integer[0], ArrayUtils.map(emptyStrings, Integer::parseInt, Integer.class) - ); - assertArrayEquals( - ArrayFactory.toArray(5), ArrayUtils.map(singleStrings, Integer::parseInt, Integer.class) - ); - assertArrayEquals( - ArrayFactory.toArray(8, 1, 6), ArrayUtils.map(strings, Integer::parseInt, Integer.class) - ); - } - - @Test - void mapWithDefTest() { - - String[] nullStrings = null; - String[] emptyStrings = new String[0]; - String[] singleStrings = ArrayFactory.toArray("5"); - String[] strings = ArrayFactory.toArray("8", "1", "6"); - - assertArrayEquals(new Integer[0], ArrayUtils.map(nullStrings, Integer::parseInt, new Integer[0])); - - assertArrayEquals( - new Integer[0], ArrayUtils.map(emptyStrings, Integer::parseInt, new Integer[0]) - ); - assertArrayEquals( - ArrayFactory.toArray(5), ArrayUtils.map(singleStrings, Integer::parseInt, new Integer[0]) - ); - assertArrayEquals( - ArrayFactory.toArray(8, 1, 6), ArrayUtils.map(strings, Integer::parseInt, new Integer[0]) - ); - } - - @Test - void copyOfAndExtendTest() { - - var array = ArrayFactory.toArray("First", "Second"); - var newArray = ArrayUtils.copyOfAndExtend(array, 2); - - assertEquals(4, newArray.length); - assertArrayEquals(ArrayFactory.toArray("First", "Second", null, null), newArray); - } - - @Test - void isNotEmptyTest() { - - assertTrue(ArrayUtils.isNotEmpty(new byte[1])); - assertFalse(ArrayUtils.isNotEmpty(new byte[0])); - assertFalse(ArrayUtils.isNotEmpty((byte[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new short[1])); - assertFalse(ArrayUtils.isNotEmpty(new short[0])); - assertFalse(ArrayUtils.isNotEmpty((short[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new int[1])); - assertFalse(ArrayUtils.isNotEmpty(new int[0])); - assertFalse(ArrayUtils.isNotEmpty((int[]) null)); - - - assertTrue(ArrayUtils.isNotEmpty(new char[1])); - assertFalse(ArrayUtils.isNotEmpty(new char[0])); - assertFalse(ArrayUtils.isNotEmpty((char[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new long[1])); - assertFalse(ArrayUtils.isNotEmpty(new long[0])); - assertFalse(ArrayUtils.isNotEmpty((long[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new float[1])); - assertFalse(ArrayUtils.isNotEmpty(new float[0])); - assertFalse(ArrayUtils.isNotEmpty((float[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new double[1])); - assertFalse(ArrayUtils.isNotEmpty(new double[0])); - assertFalse(ArrayUtils.isNotEmpty((double[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new Object[1])); - assertFalse(ArrayUtils.isNotEmpty(new Object[0])); - assertFalse(ArrayUtils.isNotEmpty((Object[]) null)); - } + @Test + void convertIntegerArrayToIntArrayTest() { + + Integer[] integers = ArrayFactory.toArray(1, 2, 3, 4, 5); + int[] ints = ArrayUtils.toIntArray(integers); + int[] empty = ArrayUtils.toIntArray(new Integer[0]); + + assertArrayEquals(ints, ArrayFactory.toIntArray(1, 2, 3, 4, 5)); + assertArrayEquals(empty, ArrayFactory.toIntArray()); + } + + @Test + void convertStringToIntArrayTest() { + + assertArrayEquals(ArrayUtils.toIntArray("1,2,3,4,5", ","), ArrayFactory.toIntArray(1, 2, 3, 4, 5)); + assertArrayEquals(ArrayUtils.toIntArray(" 1 ,2 , 3,4, 5", ","), ArrayFactory.toIntArray(1, 2, 3, 4, 5)); + assertArrayEquals(ArrayUtils.toIntArray(" 1 ,2 , 3,4, 5", ","), ArrayFactory.toIntArray(1, 2, 3, 4, 5)); + + assertThrows(NumberFormatException.class, () -> ArrayUtils.toIntArray(" 1 ,,2 , 3,4, 5,", ",")); + assertThrows(NumberFormatException.class, () -> ArrayUtils.toIntArray(" 1 ,qwd , 3,4, 5", ",")); + assertThrows(NumberFormatException.class, () -> ArrayUtils.toIntArray(" 1 ,2.5 , 3,4, 5", ",")); + } + + @Test + void mapNullableTest() { + + String[] nullStrings = null; + String[] emptyStrings = new String[0]; + String[] singleStrings = ArrayFactory.toArray("5"); + String[] strings = ArrayFactory.toArray("8", "1", "6"); + + Assertions.assertNull(ArrayUtils.mapNullable(nullStrings, Integer::parseInt, Integer.class)); + + assertArrayEquals(new Integer[0], ArrayUtils.mapNullable(emptyStrings, Integer::parseInt, Integer.class)); + assertArrayEquals(ArrayFactory.toArray(5), ArrayUtils.mapNullable(singleStrings, Integer::parseInt, Integer.class)); + assertArrayEquals(ArrayFactory.toArray(8, 1, 6), ArrayUtils.mapNullable(strings, Integer::parseInt, Integer.class)); + } + + @Test + void longsToIntsTest() { + + assertArrayEquals(ArrayFactory.toIntArray(1, 5, 3), ArrayUtils.longsToInts(ArrayFactory.toLongArray(1, 5, 3))); + + assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.longsToInts(ArrayUtils.EMPTY_LONG_ARRAY)); + } + + @Test + void mapTest() { + + String[] emptyStrings = new String[0]; + String[] singleStrings = ArrayFactory.toArray("5"); + String[] strings = ArrayFactory.toArray("8", "1", "6"); + + assertArrayEquals(new Integer[0], ArrayUtils.map(emptyStrings, Integer::parseInt, Integer.class)); + assertArrayEquals(ArrayFactory.toArray(5), ArrayUtils.map(singleStrings, Integer::parseInt, Integer.class)); + assertArrayEquals(ArrayFactory.toArray(8, 1, 6), ArrayUtils.map(strings, Integer::parseInt, Integer.class)); + } + + @Test + void mapWithDefTest() { + + String[] nullStrings = null; + String[] emptyStrings = new String[0]; + String[] singleStrings = ArrayFactory.toArray("5"); + String[] strings = ArrayFactory.toArray("8", "1", "6"); + + assertArrayEquals(new Integer[0], ArrayUtils.map(nullStrings, Integer::parseInt, new Integer[0])); + + assertArrayEquals(new Integer[0], ArrayUtils.map(emptyStrings, Integer::parseInt, new Integer[0])); + assertArrayEquals(ArrayFactory.toArray(5), ArrayUtils.map(singleStrings, Integer::parseInt, new Integer[0])); + assertArrayEquals(ArrayFactory.toArray(8, 1, 6), ArrayUtils.map(strings, Integer::parseInt, new Integer[0])); + } + + @Test + void copyOfAndExtendTest() { + + var array = ArrayFactory.toArray("First", "Second"); + var newArray = ArrayUtils.copyOfAndExtend(array, 2); + + assertEquals(4, newArray.length); + assertArrayEquals(ArrayFactory.toArray("First", "Second", null, null), newArray); + } + + @Test + void isNotEmptyTest() { + + assertTrue(ArrayUtils.isNotEmpty(new byte[1])); + assertFalse(ArrayUtils.isNotEmpty(new byte[0])); + assertFalse(ArrayUtils.isNotEmpty((byte[]) null)); + + assertTrue(ArrayUtils.isNotEmpty(new short[1])); + assertFalse(ArrayUtils.isNotEmpty(new short[0])); + assertFalse(ArrayUtils.isNotEmpty((short[]) null)); + + assertTrue(ArrayUtils.isNotEmpty(new int[1])); + assertFalse(ArrayUtils.isNotEmpty(new int[0])); + assertFalse(ArrayUtils.isNotEmpty((int[]) null)); + + assertTrue(ArrayUtils.isNotEmpty(new char[1])); + assertFalse(ArrayUtils.isNotEmpty(new char[0])); + assertFalse(ArrayUtils.isNotEmpty((char[]) null)); + + assertTrue(ArrayUtils.isNotEmpty(new long[1])); + assertFalse(ArrayUtils.isNotEmpty(new long[0])); + assertFalse(ArrayUtils.isNotEmpty((long[]) null)); + + assertTrue(ArrayUtils.isNotEmpty(new float[1])); + assertFalse(ArrayUtils.isNotEmpty(new float[0])); + assertFalse(ArrayUtils.isNotEmpty((float[]) null)); + + assertTrue(ArrayUtils.isNotEmpty(new double[1])); + assertFalse(ArrayUtils.isNotEmpty(new double[0])); + assertFalse(ArrayUtils.isNotEmpty((double[]) null)); + + assertTrue(ArrayUtils.isNotEmpty(new Object[1])); + assertFalse(ArrayUtils.isNotEmpty(new Object[0])); + assertFalse(ArrayUtils.isNotEmpty((Object[]) null)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/BufferUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/BufferUtilsTest.java index 5a880560..15a70f08 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/BufferUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/BufferUtilsTest.java @@ -9,48 +9,57 @@ */ class BufferUtilsTest { - @Test - void shouldLoadDataFromOtherBuffer() { - - var data = ByteBuffer.allocate(32); - data.putInt(1); - data.flip(); - - var source = BufferUtils.loadFrom(data, ByteBuffer.allocate(12)); - - Assertions.assertEquals(0, source.position()); - Assertions.assertEquals(4, source.limit()); - Assertions.assertEquals(1, source.getInt()); - Assertions.assertFalse(data.hasRemaining()); - - data.clear(); - data.putInt(1).putInt(2).putInt(3).putInt(4); - data.putInt(5).putInt(6).putInt(7).putInt(8); - data.flip(); - - BufferUtils.loadFrom(data, source); - - Assertions.assertEquals(source.capacity(), data.position()); - Assertions.assertEquals(0, source.position()); - Assertions.assertEquals(source.capacity(), source.remaining()); - Assertions.assertEquals(1, source.getInt()); - Assertions.assertEquals(2, source.getInt()); - Assertions.assertEquals(3, source.getInt()); - } - - @Test - void shouldPrepareBuffer() { - - var result = BufferUtils.prepareBuffer(512, buffer -> { - buffer.put((byte) 1); - buffer.put((byte) 2); - buffer.put((byte) 3); + @Test + void shouldLoadDataFromOtherBuffer() { + + var data = ByteBuffer.allocate(32); + data.putInt(1); + data.flip(); + + var source = BufferUtils.loadFrom(data, ByteBuffer.allocate(12)); + + Assertions.assertEquals(0, source.position()); + Assertions.assertEquals(4, source.limit()); + Assertions.assertEquals(1, source.getInt()); + Assertions.assertFalse(data.hasRemaining()); + + data.clear(); + data + .putInt(1) + .putInt(2) + .putInt(3) + .putInt(4); + data + .putInt(5) + .putInt(6) + .putInt(7) + .putInt(8); + data.flip(); + + BufferUtils.loadFrom(data, source); + + Assertions.assertEquals(source.capacity(), data.position()); + Assertions.assertEquals(0, source.position()); + Assertions.assertEquals(source.capacity(), source.remaining()); + Assertions.assertEquals(1, source.getInt()); + Assertions.assertEquals(2, source.getInt()); + Assertions.assertEquals(3, source.getInt()); + } + + @Test + void shouldPrepareBuffer() { + + var result = BufferUtils.prepareBuffer( + 512, buffer -> { + buffer.put((byte) 1); + buffer.put((byte) 2); + buffer.put((byte) 3); }); - Assertions.assertEquals(3, result.limit()); - Assertions.assertEquals(0, result.position()); - Assertions.assertEquals(1, result.get()); - Assertions.assertEquals(2, result.get()); - Assertions.assertEquals(3, result.get()); - } + Assertions.assertEquals(3, result.limit()); + Assertions.assertEquals(0, result.position()); + Assertions.assertEquals(1, result.get()); + Assertions.assertEquals(2, result.get()); + Assertions.assertEquals(3, result.get()); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/DateUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/DateUtilsTest.java index c4f9a34f..76fbce56 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/DateUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/DateUtilsTest.java @@ -12,104 +12,64 @@ public class DateUtilsTest { - @Test - void stringToLocalDateTest() { - - Assertions.assertEquals( - LocalDate.of(1800, 5, 20), - DateUtils.toLocalDate("1800-05-20") - ); - - Assertions.assertNull(DateUtils.toLocalDate("2020-1-10")); - Assertions.assertEquals( - LocalDate.of(2020, 1, 10), - DateUtils.toLocalDate("2020-01-10") - ); - - Assertions.assertNull(DateUtils.toLocalDate("2015-5-1")); - Assertions.assertEquals( - LocalDate.of(2015, 5, 1), - DateUtils.toLocalDate("2015-05-01") - ); - - Assertions.assertNull(DateUtils.toLocalDate("invaliddate")); - } - - @Test - void localDateToStringTest() { - - Assertions.assertEquals( - "1800-05-20", - DateUtils.toString(LocalDate.of(1800, 5, 20)) - ); - - Assertions.assertEquals( - "2020-01-10", - DateUtils.toString(LocalDate.of(2020, 1, 10)) - ); - - Assertions.assertEquals( - "2015-05-01", - DateUtils.toString(LocalDate.of(2015, 5, 1)) - ); - - Assertions.assertNull(DateUtils.toString(null)); - } - - @Test - void temporalAccessorToStringTest() { - - Assertions.assertEquals( - "1800-05-20", - DateUtils.toString(LocalDate.of(1800, 5, 20), ISO_LOCAL_DATE) - ); - - Assertions.assertEquals( - "2020-01-10T23:42:00", - DateUtils.toString( - LocalDateTime.of(2020, 1, 10, 23, 42), - ISO_LOCAL_DATE_TIME - ) - ); - - Assertions.assertNull(DateUtils.toString(null, ISO_LOCAL_DATE)); - } - - @Test - void formatTimestampTest() { - - var localDateTime = LocalDateTime.of( - 2010, - 5, - 12, - 23, - 10, - 35, - 0 - ); - - Assertions.assertEquals("23:10:35:000", DateUtils.formatShortTimestamp(localDateTime)); - Assertions.assertEquals("23:10:35:000", DateUtils.formatShortTimestamp(localDateTime + @Test + void stringToLocalDateTest() { + + Assertions.assertEquals(LocalDate.of(1800, 5, 20), DateUtils.toLocalDate("1800-05-20")); + + Assertions.assertNull(DateUtils.toLocalDate("2020-1-10")); + Assertions.assertEquals(LocalDate.of(2020, 1, 10), DateUtils.toLocalDate("2020-01-10")); + + Assertions.assertNull(DateUtils.toLocalDate("2015-5-1")); + Assertions.assertEquals(LocalDate.of(2015, 5, 1), DateUtils.toLocalDate("2015-05-01")); + + Assertions.assertNull(DateUtils.toLocalDate("invaliddate")); + } + + @Test + void localDateToStringTest() { + + Assertions.assertEquals("1800-05-20", DateUtils.toString(LocalDate.of(1800, 5, 20))); + + Assertions.assertEquals("2020-01-10", DateUtils.toString(LocalDate.of(2020, 1, 10))); + + Assertions.assertEquals("2015-05-01", DateUtils.toString(LocalDate.of(2015, 5, 1))); + + Assertions.assertNull(DateUtils.toString(null)); + } + + @Test + void temporalAccessorToStringTest() { + + Assertions.assertEquals("1800-05-20", DateUtils.toString(LocalDate.of(1800, 5, 20), ISO_LOCAL_DATE)); + + Assertions.assertEquals( + "2020-01-10T23:42:00", + DateUtils.toString(LocalDateTime.of(2020, 1, 10, 23, 42), ISO_LOCAL_DATE_TIME)); + + Assertions.assertNull(DateUtils.toString(null, ISO_LOCAL_DATE)); + } + + @Test + void formatTimestampTest() { + + var localDateTime = LocalDateTime.of(2010, 5, 12, 23, 10, 35, 0); + + Assertions.assertEquals("23:10:35:000", DateUtils.formatShortTimestamp(localDateTime)); + Assertions.assertEquals( + "23:10:35:000", + DateUtils.formatShortTimestamp(localDateTime .toInstant(ZoneOffset.UTC) - .toEpochMilli()) - ); - - var zonedDateTime = ZonedDateTime.of( - 2010, - 5, - 12, - 23, - 10, - 35, - 0, - ZoneOffset.ofHours(3) - ); - - Assertions.assertEquals("23:10:35:000", DateUtils.formatShortTimestamp(zonedDateTime)); - Assertions.assertEquals("23:10:35:000", DateUtils.formatShortTimestamp(zonedDateTime + .toEpochMilli())); + + var zonedDateTime = ZonedDateTime.of(2010, 5, 12, 23, 10, 35, 0, ZoneOffset.ofHours(3)); + + Assertions.assertEquals("23:10:35:000", DateUtils.formatShortTimestamp(zonedDateTime)); + Assertions.assertEquals( + "23:10:35:000", + DateUtils.formatShortTimestamp(zonedDateTime .toLocalDateTime() .toInstant(ZoneOffset.UTC) - .toEpochMilli()) - ); - } + .toEpochMilli())); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/FileUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/FileUtilsTest.java index 2416fe71..55147c7d 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/FileUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/FileUtilsTest.java @@ -14,68 +14,68 @@ */ public class FileUtilsTest { - @Test - void shouldGetNameByPath() { - - var path = "/some/folder/some/name.ololo"; - var path2 = "D:\\some\\folder\\some\\name.ololo"; - - Assertions.assertEquals("name.ololo", FileUtils.getName(path, '/')); - assertEquals("name.ololo", FileUtils.getName(path2, '\\')); - } - - @Test - void shouldGetParentByPath() { - - var path = "/some/folder/some/name.ololo"; - var path2 = "D:\\some\\folder\\some\\name.ololo"; - - assertEquals("/some/folder/some", FileUtils.getParent(path, '/')); - assertEquals("D:\\some\\folder\\some", FileUtils.getParent(path2, '\\')); - } - - @Test - void shouldNormalizeFileName() { - var first = FileUtils.normalizeName("file*:?name!!@#$\"\"wefwef<>.png"); - assertEquals("file___name!!@#$__wefwef__.png", first); - } - - @Test - void shouldGetFileExtension() { - - var path1 = "file.txt"; - var path2 = "file.tar.gz"; - var path3 = "folder/folder.subname/file.png"; - var path4 = "D:\\folder\\folder.subname\\file.jpg"; - var path5 = "file.TxT"; - var path6 = "D:\\folder\\folder.folder\\test"; - var path7 = "/folder/folder.folder/test"; - - assertEquals("txt", FileUtils.getExtension(path1)); - assertEquals("gz", FileUtils.getExtension(path2)); - assertEquals("png", FileUtils.getExtension(path3)); - assertEquals("jpg", FileUtils.getExtension(path4)); - assertEquals("TxT", FileUtils.getExtension(path5)); - assertEquals("txt", FileUtils.getExtension(path5, true)); - assertEquals("", FileUtils.getExtension(path6)); - assertEquals("", FileUtils.getExtension(path7)); - } - - @Test - void shouldCheckExistingExtension() { - - var path1 = "file.txt"; - var path2 = "file.tar.gz"; - var path3 = "folder/folder.subname/file.png"; - var path4 = "D:\\folder\\folder.subname\\file.jpg"; - var path6 = "D:\\folder\\folder.folder\\test"; - var path7 = "/folder/folder.folder/test"; - - assertTrue(FileUtils.hasExtension(path1)); - assertTrue(FileUtils.hasExtension(path2)); - assertTrue(FileUtils.hasExtension(path3)); - assertTrue(FileUtils.hasExtension(path4)); - assertFalse(FileUtils.hasExtension(path6)); - assertFalse(FileUtils.hasExtension(path7)); - } + @Test + void shouldGetNameByPath() { + + var path = "/some/folder/some/name.ololo"; + var path2 = "D:\\some\\folder\\some\\name.ololo"; + + Assertions.assertEquals("name.ololo", FileUtils.getName(path, '/')); + assertEquals("name.ololo", FileUtils.getName(path2, '\\')); + } + + @Test + void shouldGetParentByPath() { + + var path = "/some/folder/some/name.ololo"; + var path2 = "D:\\some\\folder\\some\\name.ololo"; + + assertEquals("/some/folder/some", FileUtils.getParent(path, '/')); + assertEquals("D:\\some\\folder\\some", FileUtils.getParent(path2, '\\')); + } + + @Test + void shouldNormalizeFileName() { + var first = FileUtils.normalizeName("file*:?name!!@#$\"\"wefwef<>.png"); + assertEquals("file___name!!@#$__wefwef__.png", first); + } + + @Test + void shouldGetFileExtension() { + + var path1 = "file.txt"; + var path2 = "file.tar.gz"; + var path3 = "folder/folder.subname/file.png"; + var path4 = "D:\\folder\\folder.subname\\file.jpg"; + var path5 = "file.TxT"; + var path6 = "D:\\folder\\folder.folder\\test"; + var path7 = "/folder/folder.folder/test"; + + assertEquals("txt", FileUtils.getExtension(path1)); + assertEquals("gz", FileUtils.getExtension(path2)); + assertEquals("png", FileUtils.getExtension(path3)); + assertEquals("jpg", FileUtils.getExtension(path4)); + assertEquals("TxT", FileUtils.getExtension(path5)); + assertEquals("txt", FileUtils.getExtension(path5, true)); + assertEquals("", FileUtils.getExtension(path6)); + assertEquals("", FileUtils.getExtension(path7)); + } + + @Test + void shouldCheckExistingExtension() { + + var path1 = "file.txt"; + var path2 = "file.tar.gz"; + var path3 = "folder/folder.subname/file.png"; + var path4 = "D:\\folder\\folder.subname\\file.jpg"; + var path6 = "D:\\folder\\folder.folder\\test"; + var path7 = "/folder/folder.folder/test"; + + assertTrue(FileUtils.hasExtension(path1)); + assertTrue(FileUtils.hasExtension(path2)); + assertTrue(FileUtils.hasExtension(path3)); + assertTrue(FileUtils.hasExtension(path4)); + assertFalse(FileUtils.hasExtension(path6)); + assertFalse(FileUtils.hasExtension(path7)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java index b9eba31c..0b098962 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java @@ -16,81 +16,81 @@ */ class IOUtilsTest { - @Test - void shouldConvertInputStreamToString() { + @Test + void shouldConvertInputStreamToString() { - var original = StringUtils.generate(2048); - var source = new ByteArrayInputStream(original.getBytes(StandardCharsets.UTF_8)); + var original = StringUtils.generate(2048); + var source = new ByteArrayInputStream(original.getBytes(StandardCharsets.UTF_8)); - Assertions.assertEquals(original, IOUtils.toString(source), "result string should be the same"); - } + Assertions.assertEquals(original, IOUtils.toString(source), "result string should be the same"); + } - @Test - void shouldConvertSupplierOfInputStreamToString() { + @Test + void shouldConvertSupplierOfInputStreamToString() { - var original = StringUtils.generate(2048); + var original = StringUtils.generate(2048); - Assertions.assertEquals( - original, - IOUtils.toString(() -> new ByteArrayInputStream(original.getBytes(StandardCharsets.UTF_8))), - "result string should be the same" - ); - } + Assertions.assertEquals( + original, + IOUtils.toString(() -> new ByteArrayInputStream(original.getBytes(StandardCharsets.UTF_8))), + "result string should be the same"); + } - @Test - void shouldThrowUncheckedIOExceptionDuringConvertingInputStreamToString() { - Assertions.assertThrows(UncheckedIOException.class, () -> IOUtils.toString(new InputStream() { + @Test + void shouldThrowUncheckedIOExceptionDuringConvertingInputStreamToString() { + Assertions.assertThrows( + UncheckedIOException.class, () -> IOUtils.toString(new InputStream() { - @Override - public int read() throws IOException { - throw new IOException("test"); - } + @Override + public int read() throws IOException { + throw new IOException("test"); + } })); - } + } - @Test - void shouldThrowUncheckedIOExceptionDuringConvertingSupplierOfInputStreamToString() { - Assertions.assertThrows(UncheckedIOException.class, () -> IOUtils.toString(() -> new InputStream() { + @Test + void shouldThrowUncheckedIOExceptionDuringConvertingSupplierOfInputStreamToString() { + Assertions.assertThrows( + UncheckedIOException.class, () -> IOUtils.toString(() -> new InputStream() { - @Override - public int read() throws IOException { - throw new IOException("test"); - } + @Override + public int read() throws IOException { + throw new IOException("test"); + } })); - } - - @Test - void shouldThrowRuntimeExceptionDuringConvertingSupplierOfInputStreamToString() { - Assertions.assertThrows(RuntimeException.class, () -> { - IOUtils.toString(() -> { - throw new RuntimeException("test"); - }); + } + + @Test + void shouldThrowRuntimeExceptionDuringConvertingSupplierOfInputStreamToString() { + Assertions.assertThrows( + RuntimeException.class, () -> { + IOUtils.toString(() -> { + throw new RuntimeException("test"); + }); }); - } + } - @Test - void shouldConvertReaderToStrungUsingTLB() { + @Test + void shouldConvertReaderToStrungUsingTLB() { - var original = StringUtils.generate(2048); + var original = StringUtils.generate(2048); - Assertions.assertEquals( - original, - IOUtils.toStringUsingTLB(new StringReader(original)) - ); - } + Assertions.assertEquals(original, IOUtils.toStringUsingTLB(new StringReader(original))); + } - @Test - void shouldThrownUncheckedIOExceptionDuringConvertingReaderToStrungUsingTLB() { + @Test + void shouldThrownUncheckedIOExceptionDuringConvertingReaderToStrungUsingTLB() { - Assertions.assertThrows(UncheckedIOException.class, () -> IOUtils.toStringUsingTLB(new Reader() { - @Override - public int read(@NotNull char[] cbuf, int off, int len) throws IOException { - throw new IOException("test"); - } + Assertions.assertThrows( + UncheckedIOException.class, () -> IOUtils.toStringUsingTLB(new Reader() { + @Override + public int read(@NotNull char[] cbuf, int off, int len) throws IOException { + throw new IOException("test"); + } - @Override - public void close() { - } + @Override + public void close() { + } })); - } + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/NumberUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/NumberUtilsTest.java index 419a3863..6faeeefb 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/NumberUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/NumberUtilsTest.java @@ -16,225 +16,235 @@ */ class NumberUtilsTest { - @Test - void shouldCheckStringIsLong() { - assertTrue(NumberUtils.isLong("1")); - assertTrue(NumberUtils.isLong("123123213123")); - assertFalse(NumberUtils.isLong("notlong")); - assertFalse(NumberUtils.isLong(null)); - assertFalse(NumberUtils.isLong("2.1234")); + @Test + void shouldCheckStringIsLong() { + assertTrue(NumberUtils.isLong("1")); + assertTrue(NumberUtils.isLong("123123213123")); + assertFalse(NumberUtils.isLong("notlong")); + assertFalse(NumberUtils.isLong(null)); + assertFalse(NumberUtils.isLong("2.1234")); + } + + @Test + void shouldSafetyConvertStringToLong() { + assertNotNull(NumberUtils.safeToLong("1")); + assertNotNull(NumberUtils.safeToLong("123123213123")); + assertNull(NumberUtils.safeToLong("notlong")); + assertNull(NumberUtils.safeToLong(null)); + assertNull(NumberUtils.safeToLong("2.1234")); + } + + @Test + void shouldConvertStringToOptionalLong() { + assertTrue(NumberUtils + .toOptionalLong("1") + .isPresent()); + assertTrue(NumberUtils + .toOptionalLong("123123213123") + .isPresent()); + assertFalse(NumberUtils + .toOptionalLong("notlong") + .isPresent()); + assertFalse(NumberUtils + .toOptionalLong(null) + .isPresent()); + assertFalse(NumberUtils + .toOptionalLong("2.1234") + .isPresent()); + } + + @Test + void shouldSafetyConvertStringToInt() { + assertNotNull(NumberUtils.safeToInt("1")); + assertNotNull(NumberUtils.safeToInt("123124")); + assertNull(NumberUtils.safeToInt("notlong")); + assertNull(NumberUtils.safeToInt(null)); + assertNull(NumberUtils.safeToInt("2.1234")); + } + + @Test + void shouldReadBitsCorrectly() { + + assertTrue(NumberUtils.isSetBit((byte) 0b00000001, 0)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 0)); + + assertTrue(NumberUtils.isSetBit((byte) 0b00000010, 1)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 1)); + + assertTrue(NumberUtils.isSetBit((byte) 0b00000100, 2)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 2)); + + assertTrue(NumberUtils.isSetBit((byte) 0b00001000, 3)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 3)); + + assertTrue(NumberUtils.isSetBit((byte) 0b00010000, 4)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 4)); + + assertTrue(NumberUtils.isSetBit((byte) 0b00100000, 5)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 5)); + + assertTrue(NumberUtils.isSetBit((byte) 0b01000000, 6)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 6)); + + assertTrue(NumberUtils.isSetBit((byte) 0b10000000, 7)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 7)); + + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 0)); + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 1)); + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 2)); + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 3)); + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 4)); + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 5)); + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 6)); + assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 7)); + + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 0)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 1)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 2)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 3)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 4)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 5)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 6)); + assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 7)); + } + + @Test + void shouldWriteHighLowBitsCorrectly() { + + for (int low = 0; low < 16; low++) { + for (int high = 0; high < 16; high++) { + var result = NumberUtils.setHighByteBits(low, high); + assertEquals(high, NumberUtils.getHighByteBits(result)); + assertEquals(low, NumberUtils.getLowByteBits(result)); + } } - @Test - void shouldSafetyConvertStringToLong() { - assertNotNull(NumberUtils.safeToLong("1")); - assertNotNull(NumberUtils.safeToLong("123123213123")); - assertNull(NumberUtils.safeToLong("notlong")); - assertNull(NumberUtils.safeToLong(null)); - assertNull(NumberUtils.safeToLong("2.1234")); + for (int low = 0; low < 16; low++) { + var result = NumberUtils.setLowByteBits(256, low); + assertEquals(16, NumberUtils.getHighByteBits(result)); + assertEquals(low, NumberUtils.getLowByteBits(result)); } + } - @Test - void shouldConvertStringToOptionalLong() { - assertTrue(NumberUtils.toOptionalLong("1").isPresent()); - assertTrue(NumberUtils.toOptionalLong("123123213123").isPresent()); - assertFalse(NumberUtils.toOptionalLong("notlong").isPresent()); - assertFalse(NumberUtils.toOptionalLong(null).isPresent()); - assertFalse(NumberUtils.toOptionalLong("2.1234").isPresent()); - } + @Test + void shouldReadHighLowBitsCorrectly() { - @Test - void shouldSafetyConvertStringToInt() { - assertNotNull(NumberUtils.safeToInt("1")); - assertNotNull(NumberUtils.safeToInt("123124")); - assertNull(NumberUtils.safeToInt("notlong")); - assertNull(NumberUtils.safeToInt(null)); - assertNull(NumberUtils.safeToInt("2.1234")); + for (int i = 0; i < 16; i++) { + assertEquals(i, NumberUtils.getHighByteBits(i << 4)); } - @Test - void shouldReadBitsCorrectly() { - - assertTrue(NumberUtils.isSetBit((byte) 0b00000001, 0)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 0)); - - assertTrue(NumberUtils.isSetBit((byte) 0b00000010, 1)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 1)); - - assertTrue(NumberUtils.isSetBit((byte) 0b00000100, 2)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 2)); - - assertTrue(NumberUtils.isSetBit((byte) 0b00001000, 3)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 3)); - - assertTrue(NumberUtils.isSetBit((byte) 0b00010000, 4)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 4)); - - assertTrue(NumberUtils.isSetBit((byte) 0b00100000, 5)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 5)); - - assertTrue(NumberUtils.isSetBit((byte) 0b01000000, 6)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 6)); - - assertTrue(NumberUtils.isSetBit((byte) 0b10000000, 7)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 7)); + assertEquals(0b0000_1000, NumberUtils.getHighByteBits(0b1000_0100)); + assertEquals(0b0000_0100, NumberUtils.getHighByteBits(0b0100_1000)); + assertEquals(0b0000_0010, NumberUtils.getHighByteBits(0b0010_0010)); + assertEquals(0b0000_0001, NumberUtils.getHighByteBits(0b0001_0001)); + assertEquals(0b0000_0101, NumberUtils.getHighByteBits(0b0101_1000)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 0)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 1)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 2)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 3)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 4)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 5)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 6)); - assertTrue(NumberUtils.isSetBit((byte) 0b11111111, 7)); - - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 0)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 1)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 2)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 3)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 4)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 5)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 6)); - assertTrue(NumberUtils.isNotSetBit((byte) 0b00000000, 7)); - } - - @Test - void shouldWriteHighLowBitsCorrectly() { - - for (int low = 0; low < 16; low++) { - for (int high = 0; high < 16; high++) { - var result = NumberUtils.setHighByteBits(low, high); - assertEquals(high, NumberUtils.getHighByteBits(result)); - assertEquals(low, NumberUtils.getLowByteBits(result)); - } - } - - for (int low = 0; low < 16; low++) { - var result = NumberUtils.setLowByteBits(256, low); - assertEquals(16, NumberUtils.getHighByteBits(result)); - assertEquals(low, NumberUtils.getLowByteBits(result)); - } + for (int i = 0; i < 16; i++) { + assertEquals(i, NumberUtils.getLowByteBits(i & 0x0F)); } - @Test - void shouldReadHighLowBitsCorrectly() { - - for (int i = 0; i < 16; i++) { - assertEquals(i, NumberUtils.getHighByteBits(i << 4)); - } - - assertEquals(0b0000_1000, NumberUtils.getHighByteBits(0b1000_0100)); - assertEquals(0b0000_0100, NumberUtils.getHighByteBits(0b0100_1000)); - assertEquals(0b0000_0010, NumberUtils.getHighByteBits(0b0010_0010)); - assertEquals(0b0000_0001, NumberUtils.getHighByteBits(0b0001_0001)); - assertEquals(0b0000_0101, NumberUtils.getHighByteBits(0b0101_1000)); - - for (int i = 0; i < 16; i++) { - assertEquals(i, NumberUtils.getLowByteBits(i & 0x0F)); - } - - assertEquals(0b0000_1000, NumberUtils.getLowByteBits(0b1000_1000)); - assertEquals(0b0000_0100, NumberUtils.getLowByteBits(0b0100_0100)); - assertEquals(0b0000_0010, NumberUtils.getLowByteBits(0b0010_0010)); - assertEquals(0b0000_0001, NumberUtils.getLowByteBits(0b0001_0001)); - assertEquals(0b0000_0101, NumberUtils.getLowByteBits(0b0101_0101)); - } - - @Test - void shouldChangeBitsInByteCorrectly() { - - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 0), 0)); - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 1), 1)); - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 2), 2)); - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 3), 3)); - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 4), 4)); - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 5), 5)); - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 6), 6)); - assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 7), 7)); - - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 0), 0)); - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 1), 1)); - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 2), 2)); - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 3), 3)); - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 4), 4)); - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 5), 5)); - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 6), 6)); - assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 7), 7)); - } - - @Test - void shouldValidateIntegerCorrectly() { - - // int - assertEquals(10, NumberUtils.validate(10, 1, 20)); - assertEquals(-20, NumberUtils.validate(-20, -21, 10)); - assertEquals(-1000, NumberUtils.validate(-1000, -1050, -1000)); - - assertEquals(10, NumberUtils.validate(10, 1, 20, IllegalArgumentException::new)); - assertEquals(-20, NumberUtils.validate(-20, -21, 10, IllegalArgumentException::new)); - assertEquals(-1000, NumberUtils.validate(-1000, -1050, -1000, IllegalArgumentException::new)); - - assertThrows(IllegalArgumentException.class, () -> - NumberUtils.validate(10, 20, 50, IllegalArgumentException::new)); - assertThrows(IllegalArgumentException.class, () -> - NumberUtils.validate(-50, -70, -51, IllegalArgumentException::new)); - - assertThrows(IllegalArgumentException.class, () -> - NumberUtils.validate(10, 20, 50)); - assertThrows(IllegalArgumentException.class, () -> - NumberUtils.validate(-50, -70, -51)); - - // long - assertEquals(10, NumberUtils.validate(10L, 1, 20)); - assertEquals(-20, NumberUtils.validate(-20L, -21, 10)); - assertEquals(-1000, NumberUtils.validate(-1000L, -1050, -1000)); - - assertEquals(10, NumberUtils.validate(10L, 1, 20, IllegalArgumentException::new)); - assertEquals(-20, NumberUtils.validate(-20L, -21, 10, IllegalArgumentException::new)); - assertEquals(-1000, NumberUtils.validate(-1000L, -1050, -1000, IllegalArgumentException::new)); - - assertThrows(IllegalArgumentException.class, () -> - NumberUtils.validate(10L, 20, 50, IllegalArgumentException::new)); - assertThrows(IllegalArgumentException.class, () -> - NumberUtils.validate(-50L, -70, -51, IllegalArgumentException::new)); - - assertThrows(IllegalArgumentException.class, () -> NumberUtils.validate(10L, 20, 50)); - assertThrows(IllegalArgumentException.class, () -> NumberUtils.validate(-50L, -70, -51)); - } - - @Test - void shouldValidateBooleanCorrectly() { - - assertTrue(NumberUtils.toBoolean(1)); - assertFalse(NumberUtils.toBoolean(0)); - assertTrue(NumberUtils.toBoolean(1L)); - assertFalse(NumberUtils.toBoolean(0L)); - assertTrue(NumberUtils.toBoolean(1, IllegalArgumentException::new)); - assertFalse(NumberUtils.toBoolean(0, IllegalArgumentException::new)); - assertTrue(NumberUtils.toBoolean(1L, IllegalArgumentException::new)); - assertFalse(NumberUtils.toBoolean(0L, IllegalArgumentException::new)); - - assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(2)); - assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(-1)); - assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(2L)); - assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(-1L)); - } - - @Test - void shouldEqualsNumbersCorrectly() { - - assertTrue(NumberUtils.equals((byte) 10, (byte) 10)); - assertTrue(NumberUtils.equals((short) 10, (short) 10)); - assertTrue(NumberUtils.equals(10, 10)); - assertTrue(NumberUtils.equals(10L, 10L)); - assertTrue(NumberUtils.equals(10F, 10F)); - assertTrue(NumberUtils.equals(10D, 10D)); - - assertFalse(NumberUtils.equals((byte) -10, (byte) 10)); - assertFalse(NumberUtils.equals((short) -10, (short) 10)); - assertFalse(NumberUtils.equals(-10, 10)); - assertFalse(NumberUtils.equals(-10L, 10L)); - assertFalse(NumberUtils.equals(-10F, 10F)); - assertFalse(NumberUtils.equals(-10D, 10D)); - } + assertEquals(0b0000_1000, NumberUtils.getLowByteBits(0b1000_1000)); + assertEquals(0b0000_0100, NumberUtils.getLowByteBits(0b0100_0100)); + assertEquals(0b0000_0010, NumberUtils.getLowByteBits(0b0010_0010)); + assertEquals(0b0000_0001, NumberUtils.getLowByteBits(0b0001_0001)); + assertEquals(0b0000_0101, NumberUtils.getLowByteBits(0b0101_0101)); + } + + @Test + void shouldChangeBitsInByteCorrectly() { + + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 0), 0)); + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 1), 1)); + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 2), 2)); + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 3), 3)); + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 4), 4)); + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 5), 5)); + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 6), 6)); + assertTrue(NumberUtils.isSetBit(NumberUtils.setBit(0, 7), 7)); + + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 0), 0)); + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 1), 1)); + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 2), 2)); + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 3), 3)); + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 4), 4)); + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 5), 5)); + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 6), 6)); + assertTrue(NumberUtils.isNotSetBit(NumberUtils.unsetBit(255, 7), 7)); + } + + @Test + void shouldValidateIntegerCorrectly() { + + // int + assertEquals(10, NumberUtils.validate(10, 1, 20)); + assertEquals(-20, NumberUtils.validate(-20, -21, 10)); + assertEquals(-1000, NumberUtils.validate(-1000, -1050, -1000)); + + assertEquals(10, NumberUtils.validate(10, 1, 20, IllegalArgumentException::new)); + assertEquals(-20, NumberUtils.validate(-20, -21, 10, IllegalArgumentException::new)); + assertEquals(-1000, NumberUtils.validate(-1000, -1050, -1000, IllegalArgumentException::new)); + + assertThrows(IllegalArgumentException.class, () -> NumberUtils.validate(10, 20, 50, IllegalArgumentException::new)); + assertThrows( + IllegalArgumentException.class, + () -> NumberUtils.validate(-50, -70, -51, IllegalArgumentException::new)); + + assertThrows(IllegalArgumentException.class, () -> NumberUtils.validate(10, 20, 50)); + assertThrows(IllegalArgumentException.class, () -> NumberUtils.validate(-50, -70, -51)); + + // long + assertEquals(10, NumberUtils.validate(10L, 1, 20)); + assertEquals(-20, NumberUtils.validate(-20L, -21, 10)); + assertEquals(-1000, NumberUtils.validate(-1000L, -1050, -1000)); + + assertEquals(10, NumberUtils.validate(10L, 1, 20, IllegalArgumentException::new)); + assertEquals(-20, NumberUtils.validate(-20L, -21, 10, IllegalArgumentException::new)); + assertEquals(-1000, NumberUtils.validate(-1000L, -1050, -1000, IllegalArgumentException::new)); + + assertThrows( + IllegalArgumentException.class, + () -> NumberUtils.validate(10L, 20, 50, IllegalArgumentException::new)); + assertThrows( + IllegalArgumentException.class, + () -> NumberUtils.validate(-50L, -70, -51, IllegalArgumentException::new)); + + assertThrows(IllegalArgumentException.class, () -> NumberUtils.validate(10L, 20, 50)); + assertThrows(IllegalArgumentException.class, () -> NumberUtils.validate(-50L, -70, -51)); + } + + @Test + void shouldValidateBooleanCorrectly() { + + assertTrue(NumberUtils.toBoolean(1)); + assertFalse(NumberUtils.toBoolean(0)); + assertTrue(NumberUtils.toBoolean(1L)); + assertFalse(NumberUtils.toBoolean(0L)); + assertTrue(NumberUtils.toBoolean(1, IllegalArgumentException::new)); + assertFalse(NumberUtils.toBoolean(0, IllegalArgumentException::new)); + assertTrue(NumberUtils.toBoolean(1L, IllegalArgumentException::new)); + assertFalse(NumberUtils.toBoolean(0L, IllegalArgumentException::new)); + + assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(2)); + assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(-1)); + assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(2L)); + assertThrows(IllegalArgumentException.class, () -> NumberUtils.toBoolean(-1L)); + } + + @Test + void shouldEqualsNumbersCorrectly() { + + assertTrue(NumberUtils.equals((byte) 10, (byte) 10)); + assertTrue(NumberUtils.equals((short) 10, (short) 10)); + assertTrue(NumberUtils.equals(10, 10)); + assertTrue(NumberUtils.equals(10L, 10L)); + assertTrue(NumberUtils.equals(10F, 10F)); + assertTrue(NumberUtils.equals(10D, 10D)); + + assertFalse(NumberUtils.equals((byte) -10, (byte) 10)); + assertFalse(NumberUtils.equals((short) -10, (short) 10)); + assertFalse(NumberUtils.equals(-10, 10)); + assertFalse(NumberUtils.equals(-10L, 10L)); + assertFalse(NumberUtils.equals(-10F, 10F)); + assertFalse(NumberUtils.equals(-10D, 10D)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/ReferencesTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/ReferencesTest.java index ea50dc9a..1510b301 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/ReferencesTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/ReferencesTest.java @@ -9,143 +9,143 @@ */ public class ReferencesTest { - @Test - void shouldReferencesWork() { - - var byteRef = ReferenceFactory.newByteRef((byte) 5); - var charRef = ReferenceFactory.newCharRef('T'); - var doubleRef = ReferenceFactory.newDoubleRef(1.5D); - var floatRef = ReferenceFactory.newFloatRef(2.5F); - var intRef = ReferenceFactory.newIntRef(5); - var longRef = ReferenceFactory.newLongRef(7L); - var objRef = ReferenceFactory.newObjRef("Val"); - var shortRef = ReferenceFactory.newShortRef((short) 7); - - Assertions.assertEquals(5, byteRef.getValue()); - Assertions.assertEquals('T', charRef.getValue()); - Assertions.assertEquals(1.5D, doubleRef.getValue()); - Assertions.assertEquals(2.5F, floatRef.getValue()); - Assertions.assertEquals(5, intRef.getValue()); - Assertions.assertEquals(7L, longRef.getValue()); - Assertions.assertEquals("Val", objRef.getValue()); - Assertions.assertEquals(7, shortRef.getValue()); - } - - @Test - void shouldReusableReferencesWork() { - - var byteRef = ReferenceFactory.newReusableByteRef((byte) 3); - var charRef = ReferenceFactory.newReusableCharRef('d'); - var doubleRef = ReferenceFactory.newReusableDoubleRef(3.5D); - var floatRef = ReferenceFactory.newReusableFloatRef(1.5F); - var intRef = ReferenceFactory.newReusableIntRef(7); - var longRef = ReferenceFactory.newReusableLongRef(4L); - var objRef = ReferenceFactory.newReusableObjRef("Val3"); - var shortRef = ReferenceFactory.newReusableShortRef((short) 2); - - Assertions.assertEquals(3, byteRef.getValue()); - Assertions.assertEquals('d', charRef.getValue()); - Assertions.assertEquals(3.5D, doubleRef.getValue()); - Assertions.assertEquals(1.5F, floatRef.getValue()); - Assertions.assertEquals(7, intRef.getValue()); - Assertions.assertEquals(4L, longRef.getValue()); - Assertions.assertEquals("Val3", objRef.getValue()); - Assertions.assertEquals(2, shortRef.getValue()); - - byteRef.release(); - charRef.release(); - doubleRef.release(); - floatRef.release(); - intRef.release(); - longRef.release(); - objRef.release(); - shortRef.release(); - - Assertions.assertEquals(0, byteRef.getValue()); - Assertions.assertEquals(0, charRef.getValue()); - Assertions.assertEquals(0, doubleRef.getValue()); - Assertions.assertEquals(0, floatRef.getValue()); - Assertions.assertEquals(0, intRef.getValue()); - Assertions.assertEquals(0, longRef.getValue()); - Assertions.assertNull(objRef.getValue()); - Assertions.assertEquals(0, shortRef.getValue()); - Assertions.assertEquals(0, byteRef.getValue()); - - var byteRef2 = ReferenceFactory.newReusableByteRef((byte) 3); - var charRef2 = ReferenceFactory.newReusableCharRef('d'); - var doubleRef2 = ReferenceFactory.newReusableDoubleRef(3.5D); - var floatRef2 = ReferenceFactory.newReusableFloatRef(1.5F); - var intRef2 = ReferenceFactory.newReusableIntRef(7); - var longRef2 = ReferenceFactory.newReusableLongRef(4L); - var objRef2 = ReferenceFactory.newReusableObjRef("Val3"); - var shortRef2 = ReferenceFactory.newReusableShortRef((short) 2); - - Assertions.assertSame(byteRef, byteRef2); - Assertions.assertSame(charRef, charRef2); - Assertions.assertSame(doubleRef, doubleRef2); - Assertions.assertSame(floatRef, floatRef2); - Assertions.assertSame(intRef, intRef2); - Assertions.assertSame(longRef, longRef2); - Assertions.assertSame(objRef, objRef2); - Assertions.assertSame(shortRef, shortRef2); - } - - @Test - void shouldTLReferencesWork() { - - var byteRef = ReferenceFactory.newThreadLocalByteRef((byte) 3); - var charRef = ReferenceFactory.newThreadLocalCharRef('d'); - var doubleRef = ReferenceFactory.newThreadLocalDoubleRef(3.5D); - var floatRef = ReferenceFactory.newThreadLocalFloatRef(1.5F); - var intRef = ReferenceFactory.newThreadLocalIntRef(7); - var longRef = ReferenceFactory.newThreadLocalLongRef(4L); - var objRef = ReferenceFactory.newThreadLocalObjRef("Val3"); - var shortRef = ReferenceFactory.newThreadLocalShortRef((short) 2); - - Assertions.assertEquals(3, byteRef.getValue()); - Assertions.assertEquals('d', charRef.getValue()); - Assertions.assertEquals(3.5D, doubleRef.getValue()); - Assertions.assertEquals(1.5F, floatRef.getValue()); - Assertions.assertEquals(7, intRef.getValue()); - Assertions.assertEquals(4L, longRef.getValue()); - Assertions.assertEquals("Val3", objRef.getValue()); - Assertions.assertEquals(2, shortRef.getValue()); - - byteRef.release(); - charRef.release(); - doubleRef.release(); - floatRef.release(); - intRef.release(); - longRef.release(); - objRef.release(); - shortRef.release(); - - Assertions.assertEquals(0, byteRef.getValue()); - Assertions.assertEquals(0, charRef.getValue()); - Assertions.assertEquals(0, doubleRef.getValue()); - Assertions.assertEquals(0, floatRef.getValue()); - Assertions.assertEquals(0, intRef.getValue()); - Assertions.assertEquals(0, longRef.getValue()); - Assertions.assertNull(objRef.getValue()); - Assertions.assertEquals(0, shortRef.getValue()); - Assertions.assertEquals(0, byteRef.getValue()); - - var byteRef2 = ReferenceFactory.newThreadLocalByteRef((byte) 3); - var charRef2 = ReferenceFactory.newThreadLocalCharRef('d'); - var doubleRef2 = ReferenceFactory.newThreadLocalDoubleRef(3.5D); - var floatRef2 = ReferenceFactory.newThreadLocalFloatRef(1.5F); - var intRef2 = ReferenceFactory.newThreadLocalIntRef(7); - var longRef2 = ReferenceFactory.newThreadLocalLongRef(4L); - var objRef2 = ReferenceFactory.newThreadLocalObjRef("Val3"); - var shortRef2 = ReferenceFactory.newThreadLocalShortRef((short) 2); - - Assertions.assertSame(byteRef, byteRef2); - Assertions.assertSame(charRef, charRef2); - Assertions.assertSame(doubleRef, doubleRef2); - Assertions.assertSame(floatRef, floatRef2); - Assertions.assertSame(intRef, intRef2); - Assertions.assertSame(longRef, longRef2); - Assertions.assertSame(objRef, objRef2); - Assertions.assertSame(shortRef, shortRef2); - } + @Test + void shouldReferencesWork() { + + var byteRef = ReferenceFactory.newByteRef((byte) 5); + var charRef = ReferenceFactory.newCharRef('T'); + var doubleRef = ReferenceFactory.newDoubleRef(1.5D); + var floatRef = ReferenceFactory.newFloatRef(2.5F); + var intRef = ReferenceFactory.newIntRef(5); + var longRef = ReferenceFactory.newLongRef(7L); + var objRef = ReferenceFactory.newObjRef("Val"); + var shortRef = ReferenceFactory.newShortRef((short) 7); + + Assertions.assertEquals(5, byteRef.getValue()); + Assertions.assertEquals('T', charRef.getValue()); + Assertions.assertEquals(1.5D, doubleRef.getValue()); + Assertions.assertEquals(2.5F, floatRef.getValue()); + Assertions.assertEquals(5, intRef.getValue()); + Assertions.assertEquals(7L, longRef.getValue()); + Assertions.assertEquals("Val", objRef.getValue()); + Assertions.assertEquals(7, shortRef.getValue()); + } + + @Test + void shouldReusableReferencesWork() { + + var byteRef = ReferenceFactory.newReusableByteRef((byte) 3); + var charRef = ReferenceFactory.newReusableCharRef('d'); + var doubleRef = ReferenceFactory.newReusableDoubleRef(3.5D); + var floatRef = ReferenceFactory.newReusableFloatRef(1.5F); + var intRef = ReferenceFactory.newReusableIntRef(7); + var longRef = ReferenceFactory.newReusableLongRef(4L); + var objRef = ReferenceFactory.newReusableObjRef("Val3"); + var shortRef = ReferenceFactory.newReusableShortRef((short) 2); + + Assertions.assertEquals(3, byteRef.getValue()); + Assertions.assertEquals('d', charRef.getValue()); + Assertions.assertEquals(3.5D, doubleRef.getValue()); + Assertions.assertEquals(1.5F, floatRef.getValue()); + Assertions.assertEquals(7, intRef.getValue()); + Assertions.assertEquals(4L, longRef.getValue()); + Assertions.assertEquals("Val3", objRef.getValue()); + Assertions.assertEquals(2, shortRef.getValue()); + + byteRef.release(); + charRef.release(); + doubleRef.release(); + floatRef.release(); + intRef.release(); + longRef.release(); + objRef.release(); + shortRef.release(); + + Assertions.assertEquals(0, byteRef.getValue()); + Assertions.assertEquals(0, charRef.getValue()); + Assertions.assertEquals(0, doubleRef.getValue()); + Assertions.assertEquals(0, floatRef.getValue()); + Assertions.assertEquals(0, intRef.getValue()); + Assertions.assertEquals(0, longRef.getValue()); + Assertions.assertNull(objRef.getValue()); + Assertions.assertEquals(0, shortRef.getValue()); + Assertions.assertEquals(0, byteRef.getValue()); + + var byteRef2 = ReferenceFactory.newReusableByteRef((byte) 3); + var charRef2 = ReferenceFactory.newReusableCharRef('d'); + var doubleRef2 = ReferenceFactory.newReusableDoubleRef(3.5D); + var floatRef2 = ReferenceFactory.newReusableFloatRef(1.5F); + var intRef2 = ReferenceFactory.newReusableIntRef(7); + var longRef2 = ReferenceFactory.newReusableLongRef(4L); + var objRef2 = ReferenceFactory.newReusableObjRef("Val3"); + var shortRef2 = ReferenceFactory.newReusableShortRef((short) 2); + + Assertions.assertSame(byteRef, byteRef2); + Assertions.assertSame(charRef, charRef2); + Assertions.assertSame(doubleRef, doubleRef2); + Assertions.assertSame(floatRef, floatRef2); + Assertions.assertSame(intRef, intRef2); + Assertions.assertSame(longRef, longRef2); + Assertions.assertSame(objRef, objRef2); + Assertions.assertSame(shortRef, shortRef2); + } + + @Test + void shouldTLReferencesWork() { + + var byteRef = ReferenceFactory.newThreadLocalByteRef((byte) 3); + var charRef = ReferenceFactory.newThreadLocalCharRef('d'); + var doubleRef = ReferenceFactory.newThreadLocalDoubleRef(3.5D); + var floatRef = ReferenceFactory.newThreadLocalFloatRef(1.5F); + var intRef = ReferenceFactory.newThreadLocalIntRef(7); + var longRef = ReferenceFactory.newThreadLocalLongRef(4L); + var objRef = ReferenceFactory.newThreadLocalObjRef("Val3"); + var shortRef = ReferenceFactory.newThreadLocalShortRef((short) 2); + + Assertions.assertEquals(3, byteRef.getValue()); + Assertions.assertEquals('d', charRef.getValue()); + Assertions.assertEquals(3.5D, doubleRef.getValue()); + Assertions.assertEquals(1.5F, floatRef.getValue()); + Assertions.assertEquals(7, intRef.getValue()); + Assertions.assertEquals(4L, longRef.getValue()); + Assertions.assertEquals("Val3", objRef.getValue()); + Assertions.assertEquals(2, shortRef.getValue()); + + byteRef.release(); + charRef.release(); + doubleRef.release(); + floatRef.release(); + intRef.release(); + longRef.release(); + objRef.release(); + shortRef.release(); + + Assertions.assertEquals(0, byteRef.getValue()); + Assertions.assertEquals(0, charRef.getValue()); + Assertions.assertEquals(0, doubleRef.getValue()); + Assertions.assertEquals(0, floatRef.getValue()); + Assertions.assertEquals(0, intRef.getValue()); + Assertions.assertEquals(0, longRef.getValue()); + Assertions.assertNull(objRef.getValue()); + Assertions.assertEquals(0, shortRef.getValue()); + Assertions.assertEquals(0, byteRef.getValue()); + + var byteRef2 = ReferenceFactory.newThreadLocalByteRef((byte) 3); + var charRef2 = ReferenceFactory.newThreadLocalCharRef('d'); + var doubleRef2 = ReferenceFactory.newThreadLocalDoubleRef(3.5D); + var floatRef2 = ReferenceFactory.newThreadLocalFloatRef(1.5F); + var intRef2 = ReferenceFactory.newThreadLocalIntRef(7); + var longRef2 = ReferenceFactory.newThreadLocalLongRef(4L); + var objRef2 = ReferenceFactory.newThreadLocalObjRef("Val3"); + var shortRef2 = ReferenceFactory.newThreadLocalShortRef((short) 2); + + Assertions.assertSame(byteRef, byteRef2); + Assertions.assertSame(charRef, charRef2); + Assertions.assertSame(doubleRef, doubleRef2); + Assertions.assertSame(floatRef, floatRef2); + Assertions.assertSame(intRef, intRef2); + Assertions.assertSame(longRef, longRef2); + Assertions.assertSame(objRef, objRef2); + Assertions.assertSame(shortRef, shortRef2); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/ReflectionUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/ReflectionUtilsTest.java index e97fffd6..964577ee 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/ReflectionUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/ReflectionUtilsTest.java @@ -7,56 +7,88 @@ public class ReflectionUtilsTest { - private static class Type1 { + private static class Type1 { - private String field1; - private int field2; + private String field1; + private int field2; - private static class Inner1 { - private String field1; - private int field2; - } - - private static class Inner2 extends Inner1 { - private int field3; - private Object field4; - } - } - - private static class Type2 extends Type1 { - private int field3; - private Object field4; + private static class Inner1 { + private String field1; + private int field2; } - @Test - void getAllDeclaredFieldsTest() { - - var allFields = ReflectionUtils.getAllDeclaredFields(Type1.class); - - assertNotNull(allFields.findAny(object -> object.getName().equals("field1"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field2"))); - assertNull(allFields.findAny(object -> object.getName().equals("field3"))); - - allFields = ReflectionUtils.getAllDeclaredFields(Type2.class); - - assertNotNull(allFields.findAny(object -> object.getName().equals("field1"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field2"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field3"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field4"))); - assertNull(allFields.findAny(object -> object.getName().equals("field5"))); - - allFields = ReflectionUtils.getAllDeclaredFields(Type1.Inner1.class); - - assertNotNull(allFields.findAny(object -> object.getName().equals("field1"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field2"))); - assertNull(allFields.findAny(object -> object.getName().equals("field3"))); - - allFields = ReflectionUtils.getAllDeclaredFields(Type1.Inner2.class); - - assertNotNull(allFields.findAny(object -> object.getName().equals("field1"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field2"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field3"))); - assertNotNull(allFields.findAny(object -> object.getName().equals("field4"))); - assertNull(allFields.findAny(object -> object.getName().equals("field5"))); + private static class Inner2 extends Inner1 { + private int field3; + private Object field4; } + } + + private static class Type2 extends Type1 { + private int field3; + private Object field4; + } + + @Test + void getAllDeclaredFieldsTest() { + + var allFields = ReflectionUtils.getAllDeclaredFields(Type1.class); + + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field1"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field2"))); + assertNull(allFields.findAny(object -> object + .getName() + .equals("field3"))); + + allFields = ReflectionUtils.getAllDeclaredFields(Type2.class); + + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field1"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field2"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field3"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field4"))); + assertNull(allFields.findAny(object -> object + .getName() + .equals("field5"))); + + allFields = ReflectionUtils.getAllDeclaredFields(Type1.Inner1.class); + + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field1"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field2"))); + assertNull(allFields.findAny(object -> object + .getName() + .equals("field3"))); + + allFields = ReflectionUtils.getAllDeclaredFields(Type1.Inner2.class); + + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field1"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field2"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field3"))); + assertNotNull(allFields.findAny(object -> object + .getName() + .equals("field4"))); + assertNull(allFields.findAny(object -> object + .getName() + .equals("field5"))); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/StringUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/StringUtilsTest.java index 784ef999..803d2808 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/StringUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/StringUtilsTest.java @@ -10,111 +10,120 @@ */ class StringUtilsTest { - @Test - void shouldConvertStringToHex() { + @Test + void shouldConvertStringToHex() { + + var original = "EWfwefsbrt34532#%#$^$#^@gfh\"P{\">KK - StringUtils.replace("string", "name1", "val1", "name2")); - - Assertions.assertThrows(IllegalArgumentException.class, () -> - StringUtils.replace("string", "name1")); - - Assertions.assertThrows(IllegalArgumentException.class, () -> - StringUtils.replace("string")); - } - - @Test - void shouldVerifyEmails() { - - Assertions.assertTrue(StringUtils.isValidEmail("test@test.com")); - Assertions.assertTrue(StringUtils.isValidEmail("тест@test.com")); - Assertions.assertTrue(StringUtils.isValidEmail("тест@тест.рф")); - Assertions.assertTrue(StringUtils.isValidEmail("my-name.test@test.com")); - - Assertions.assertFalse(StringUtils.isValidEmail("@test.com")); - Assertions.assertFalse(StringUtils.isValidEmail("test@.com")); - Assertions.assertFalse(StringUtils.isValidEmail("%$%&$&%@$%&&%$&.com")); - } - - @Test - void shouldDetectEmails() { - - Assertions.assertTrue(StringUtils.isEmail("test@test.com")); - Assertions.assertTrue(StringUtils.isEmail("test.test@test.com")); - Assertions.assertTrue(StringUtils.isEmail("test.test@test.test.com")); - - Assertions.assertFalse(StringUtils.isEmail("@test.com")); - Assertions.assertFalse(StringUtils.isEmail("test-test.com")); - Assertions.assertFalse(StringUtils.isEmail("test@test")); - Assertions.assertFalse(StringUtils.isEmail("test@test.")); - } + Assertions.assertEquals(original, parsed); + } + + @Test + void shouldConvertHexStringToString() { + + var original = new byte[]{ + 5, + 2, + 8, + 120, + 21, + -40, + -120, + 63, + 70 + }; + var hex = StringUtils.bytesToHexString(original); + var parsed = StringUtils.hexStringToBytes(hex); + + Assertions.assertArrayEquals(original, parsed); + } + + @Test + void shouldReplaceOneVariableInString() { + + var original = "some text ${test_var} with one variable"; + var expected = "some text var_val with one variable"; + + Assertions.assertEquals(expected, StringUtils.replace(original, "${test_var}", "var_val")); + } + + @Test + void shouldReplaceTwoVariablesInString() { + + var original = "some text ${test_var1} with two variable ${test_var2}"; + var expected = "some text var_val_1 with two variable var_val_2"; + + Assertions.assertEquals( + expected, + StringUtils.replace(original, "${test_var1}", "var_val_1", "${test_var2}", "var_val_2")); + } + + @Test + void shouldReplaceTwoVariablesInStringTwice() { + + var original = "some text ${test_var1} with two variable ${test_var2}, and ${test_var1} and ${test_var2}"; + var expected = "some text var_val_1 with two variable var_val_2, and var_val_1 and var_val_2"; + + Assertions.assertEquals( + expected, + StringUtils.replace(original, "${test_var1}", "var_val_1", "${test_var2}", "var_val_2")); + } + + @Test + void shouldReplaceVariablesInString() { + + var original = "some text ${test_var1} with variables ${test_var2}, ${test_var3}"; + var expected = "some text var_val_1 with variables var_val_2, var_val_3"; + + Assertions.assertEquals( + expected, + StringUtils.replace( + original, + "${test_var1}", + "var_val_1", + "${test_var2}", + "var_val_2", + "${test_var3}", + "var_val_3")); + } + + @Test + void shouldThrownIllegalArgumentExceptionDuringReplacingStringWithWrongArgs() { + + Assertions.assertThrows( + IllegalArgumentException.class, + () -> StringUtils.replace("string", "name1", "val1", "name2")); + + Assertions.assertThrows(IllegalArgumentException.class, () -> StringUtils.replace("string", "name1")); + + Assertions.assertThrows(IllegalArgumentException.class, () -> StringUtils.replace("string")); + } + + @Test + void shouldVerifyEmails() { + + Assertions.assertTrue(StringUtils.isValidEmail("test@test.com")); + Assertions.assertTrue(StringUtils.isValidEmail("тест@test.com")); + Assertions.assertTrue(StringUtils.isValidEmail("тест@тест.рф")); + Assertions.assertTrue(StringUtils.isValidEmail("my-name.test@test.com")); + + Assertions.assertFalse(StringUtils.isValidEmail("@test.com")); + Assertions.assertFalse(StringUtils.isValidEmail("test@.com")); + Assertions.assertFalse(StringUtils.isValidEmail("%$%&$&%@$%&&%$&.com")); + } + + @Test + void shouldDetectEmails() { + + Assertions.assertTrue(StringUtils.isEmail("test@test.com")); + Assertions.assertTrue(StringUtils.isEmail("test.test@test.com")); + Assertions.assertTrue(StringUtils.isEmail("test.test@test.test.com")); + + Assertions.assertFalse(StringUtils.isEmail("@test.com")); + Assertions.assertFalse(StringUtils.isEmail("test-test.com")); + Assertions.assertFalse(StringUtils.isEmail("test@test")); + Assertions.assertFalse(StringUtils.isEmail("test@test.")); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/UtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/UtilsTest.java index c1221323..2c3dc26c 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/UtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/UtilsTest.java @@ -10,19 +10,19 @@ */ public class UtilsTest { - @Test - void shouldSafetyTryGet() { + @Test + void shouldSafetyTryGet() { - Assertions.assertEquals(Integer.valueOf(15), Utils.tryGet("15", Integer::valueOf)); - Assertions.assertNull(Utils.tryGet("invalidnumber", Integer::valueOf)); + Assertions.assertEquals(Integer.valueOf(15), Utils.tryGet("15", Integer::valueOf)); + Assertions.assertNull(Utils.tryGet("invalidnumber", Integer::valueOf)); - Assertions.assertEquals(Integer.valueOf(15), Utils.tryGet("15", Integer::valueOf, 2)); - Assertions.assertEquals(Integer.valueOf(2), Utils.tryGet("invalidnumber", Integer::valueOf, 2)); - } + Assertions.assertEquals(Integer.valueOf(15), Utils.tryGet("15", Integer::valueOf, 2)); + Assertions.assertEquals(Integer.valueOf(2), Utils.tryGet("invalidnumber", Integer::valueOf, 2)); + } - @Test - void shouldSafetyTryGetAndConvert() { - Assertions.assertEquals("15", Utils.tryGetAndConvert("15", Integer::valueOf, Object::toString)); - Assertions.assertNull(Utils.tryGetAndConvert("invalidnumber", Integer::valueOf, Object::toString)); - } + @Test + void shouldSafetyTryGetAndConvert() { + Assertions.assertEquals("15", Utils.tryGetAndConvert("15", Integer::valueOf, Object::toString)); + Assertions.assertNull(Utils.tryGetAndConvert("invalidnumber", Integer::valueOf, Object::toString)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/VarTableTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/VarTableTest.java index ba7f22ba..e1976c54 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/VarTableTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/VarTableTest.java @@ -15,152 +15,153 @@ */ public class VarTableTest { - @Test - void testAllGets() { - - var vars = new VarTable(); - vars.put("number", 10); - vars.put("array", toArray(1, 2, 3, 4)); - vars.put("arrayString", "1,2,3,4"); - vars.put("boolean", true); - vars.put("booleanString", "true"); - vars.put("booleanArray", toBooleanArray(true, false, true)); - vars.put("booleanArrayString", "true, false, true"); - - Assertions.assertEquals(vars.get("number"), 10); - - Assertions.assertEquals(vars.get("number", Integer.class), 10); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.get("number", Double.class)); - - Assertions.assertEquals(vars.get("number", Integer.class, 11), 10); - Assertions.assertEquals(vars.get("not_exist", Integer.class, 11), 11); - Assertions.assertEquals(vars.get("number", Double.class, 12D), 12D); - - Assertions.assertEquals(vars.getNullable("number", Integer.class, null), 10); - Assertions.assertNull(vars.getNullable("not_exist", Double.class, null)); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getNullable("number", Double.class, null)); - - Assertions.assertEquals(vars.get("number",11), 10); - Assertions.assertEquals(vars.get("not_exist",11), 11); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.get("number",11D)); - - Assertions.assertNull(vars.getNullable("not_exist", null)); - Assertions.assertEquals(vars.getNullable("number",11D), 11D); - Assertions.assertEquals(vars.getNullable("number",11), 10); - Assertions.assertEquals(vars.getNullable("number",null), 10); - Assertions.assertThrows(ClassCastException.class, () -> { - Double d = vars.getNullable("number",null); + @Test + void testAllGets() { + + var vars = new VarTable(); + vars.put("number", 10); + vars.put("array", toArray(1, 2, 3, 4)); + vars.put("arrayString", "1,2,3,4"); + vars.put("boolean", true); + vars.put("booleanString", "true"); + vars.put("booleanArray", toBooleanArray(true, false, true)); + vars.put("booleanArrayString", "true, false, true"); + + Assertions.assertEquals(vars.get("number"), 10); + + Assertions.assertEquals(vars.get("number", Integer.class), 10); + Assertions.assertThrows(IllegalArgumentException.class, () -> vars.get("number", Double.class)); + + Assertions.assertEquals(vars.get("number", Integer.class, 11), 10); + Assertions.assertEquals(vars.get("not_exist", Integer.class, 11), 11); + Assertions.assertEquals(vars.get("number", Double.class, 12D), 12D); + + Assertions.assertEquals(vars.getNullable("number", Integer.class, null), 10); + Assertions.assertNull(vars.getNullable("not_exist", Double.class, null)); + Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getNullable("number", Double.class, null)); + + Assertions.assertEquals(vars.get("number", 11), 10); + Assertions.assertEquals(vars.get("not_exist", 11), 11); + Assertions.assertThrows(IllegalArgumentException.class, () -> vars.get("number", 11D)); + + Assertions.assertNull(vars.getNullable("not_exist", null)); + Assertions.assertEquals(vars.getNullable("number", 11D), 11D); + Assertions.assertEquals(vars.getNullable("number", 11), 10); + Assertions.assertEquals(vars.getNullable("number", null), 10); + Assertions.assertThrows( + ClassCastException.class, () -> { + Double d = vars.getNullable("number", null); }); - Assertions.assertArrayEquals(vars.getArray("array", Integer[].class, 1, 3, 3), toArray(1, 2, 3, 4)); - Assertions.assertArrayEquals(vars.getArray("not_exist", Integer[].class, 1, 3, 3), toArray(1, 3, 3)); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getArray("array", Double[].class, 1D, 3D, 3D)); + Assertions.assertArrayEquals(vars.getArray("array", Integer[].class, 1, 3, 3), toArray(1, 2, 3, 4)); + Assertions.assertArrayEquals(vars.getArray("not_exist", Integer[].class, 1, 3, 3), toArray(1, 3, 3)); + Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getArray("array", Double[].class, 1D, 3D, 3D)); - Assertions.assertTrue(vars.getBoolean("boolean")); - Assertions.assertTrue(vars.getBoolean("booleanString")); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("not_exist")); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("number")); + Assertions.assertTrue(vars.getBoolean("boolean")); + Assertions.assertTrue(vars.getBoolean("booleanString")); + Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("not_exist")); + Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("number")); - Assertions.assertTrue(vars.getBoolean("boolean", false)); - Assertions.assertTrue(vars.getBoolean("booleanString", false)); - Assertions.assertFalse(vars.getBoolean("not_exist", false)); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("number", false)); + Assertions.assertTrue(vars.getBoolean("boolean", false)); + Assertions.assertTrue(vars.getBoolean("booleanString", false)); + Assertions.assertFalse(vars.getBoolean("not_exist", false)); + Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("number", false)); - Assertions.assertArrayEquals(vars.getBooleanArray("booleanArray", ","), toBooleanArray(true, false, true)); - Assertions.assertArrayEquals(vars.getBooleanArray("booleanArrayString", ","), toBooleanArray(true, false, true)); - } - - @Test - void testGetIntArrays() { + Assertions.assertArrayEquals(vars.getBooleanArray("booleanArray", ","), toBooleanArray(true, false, true)); + Assertions.assertArrayEquals(vars.getBooleanArray("booleanArrayString", ","), toBooleanArray(true, false, true)); + } - var vars = new VarTable(); - vars.put("array", toArray(1, 2, 3, 4)); - vars.put("arrayInt", toIntArray(2, 4, 6, 1)); - vars.put("arrayString", "1, 2, 3, 4"); - - Assertions.assertArrayEquals(vars.getIntArray("array"), toIntArray(1, 2, 3, 4)); - Assertions.assertArrayEquals(vars.getIntArray("arrayInt"), toIntArray(2, 4, 6, 1)); - Assertions.assertArrayEquals(vars.getIntArray("arrayString", ","), toIntArray(1, 2, 3, 4)); - } + @Test + void testGetIntArrays() { - @Test - void testAddAndGetIntegers() { + var vars = new VarTable(); + vars.put("array", toArray(1, 2, 3, 4)); + vars.put("arrayInt", toIntArray(2, 4, 6, 1)); + vars.put("arrayString", "1, 2, 3, 4"); - var vars = new VarTable(); - vars.put("stringInt", "1234"); - vars.put("objectInt", 222); + Assertions.assertArrayEquals(vars.getIntArray("array"), toIntArray(1, 2, 3, 4)); + Assertions.assertArrayEquals(vars.getIntArray("arrayInt"), toIntArray(2, 4, 6, 1)); + Assertions.assertArrayEquals(vars.getIntArray("arrayString", ","), toIntArray(1, 2, 3, 4)); + } - var stringInt = vars.getString("stringInt"); - var stringIntAsInt = vars.getInt("stringInt"); - var objectIntAsInt = vars.getInt("objectInt"); + @Test + void testAddAndGetIntegers() { - Assertions.assertEquals("1234", stringInt); - Assertions.assertEquals(1234, stringIntAsInt); - Assertions.assertEquals(222, objectIntAsInt); - } + var vars = new VarTable(); + vars.put("stringInt", "1234"); + vars.put("objectInt", 222); - @Test - void testCheckExisting() { + var stringInt = vars.getString("stringInt"); + var stringIntAsInt = vars.getInt("stringInt"); + var objectIntAsInt = vars.getInt("objectInt"); - var vars = new VarTable(); - vars.put("value", "1234"); + Assertions.assertEquals("1234", stringInt); + Assertions.assertEquals(1234, stringIntAsInt); + Assertions.assertEquals(222, objectIntAsInt); + } - Assertions.assertTrue(vars.has("value")); - Assertions.assertFalse(vars.has("no value")); - } + @Test + void testCheckExisting() { - @Test - void testCopyingAnotherVarsTable() { + var vars = new VarTable(); + vars.put("value", "1234"); - var vars = new VarTable(); - vars.put("val1", "1"); - vars.put("val2", "2"); + Assertions.assertTrue(vars.has("value")); + Assertions.assertFalse(vars.has("no value")); + } - var anotherVars = new VarTable(); - anotherVars.put("val3", "3"); - anotherVars.put("val4", "4"); + @Test + void testCopyingAnotherVarsTable() { - vars.put(anotherVars); + var vars = new VarTable(); + vars.put("val1", "1"); + vars.put("val2", "2"); - Assertions.assertEquals("3", vars.getString("val3")); - Assertions.assertEquals("4", vars.getString("val4")); + var anotherVars = new VarTable(); + anotherVars.put("val3", "3"); + anotherVars.put("val4", "4"); - try { - vars.put(vars); - throw new IllegalStateException("Can't copy vars recursive."); - } catch (IllegalArgumentException e) { - // it's ok - } - } + vars.put(anotherVars); - enum SimpleEnum { - FIRST, - SECOND, - THIRD - } + Assertions.assertEquals("3", vars.getString("val3")); + Assertions.assertEquals("4", vars.getString("val4")); - @Test - void testAddAndGetSomeTypes() { - - var vars = new VarTable(); - vars.put("string", "Hello"); - vars.put("intArray", toIntArray(1, 2, 3, 5)); - vars.put("floatStringArray", "1.5,4.2,5.5"); - vars.put("stringEnum", "THIRD"); - vars.put("enum", SimpleEnum.SECOND); - - var string = vars.getString("string"); - var array = vars.getIntArray("intArray", ""); - var floatStringArray = vars.getFloatArray("floatStringArray", ","); - var stringEnum = vars.getEnum("stringEnum", SimpleEnum.class); - var anEnum = vars.getEnum("enum", SimpleEnum.class); - var unsafeGet = vars.get("enum"); - - Assertions.assertEquals("Hello", string); - Assertions.assertArrayEquals(array, toIntArray(1, 2, 3, 5)); - Assertions.assertArrayEquals(floatStringArray, ArrayFactory.toFloatArray(1.5F, 4.2F, 5.5F)); - Assertions.assertEquals(SimpleEnum.THIRD, stringEnum); - Assertions.assertEquals(SimpleEnum.SECOND, anEnum); - Assertions.assertEquals(SimpleEnum.SECOND, unsafeGet); + try { + vars.put(vars); + throw new IllegalStateException("Can't copy vars recursive."); + } catch (IllegalArgumentException e) { + // it's ok } + } + + enum SimpleEnum { + FIRST, + SECOND, + THIRD + } + + @Test + void testAddAndGetSomeTypes() { + + var vars = new VarTable(); + vars.put("string", "Hello"); + vars.put("intArray", toIntArray(1, 2, 3, 5)); + vars.put("floatStringArray", "1.5,4.2,5.5"); + vars.put("stringEnum", "THIRD"); + vars.put("enum", SimpleEnum.SECOND); + + var string = vars.getString("string"); + var array = vars.getIntArray("intArray", ""); + var floatStringArray = vars.getFloatArray("floatStringArray", ","); + var stringEnum = vars.getEnum("stringEnum", SimpleEnum.class); + var anEnum = vars.getEnum("enum", SimpleEnum.class); + var unsafeGet = vars.get("enum"); + + Assertions.assertEquals("Hello", string); + Assertions.assertArrayEquals(array, toIntArray(1, 2, 3, 5)); + Assertions.assertArrayEquals(floatStringArray, ArrayFactory.toFloatArray(1.5F, 4.2F, 5.5F)); + Assertions.assertEquals(SimpleEnum.THIRD, stringEnum); + Assertions.assertEquals(SimpleEnum.SECOND, anEnum); + Assertions.assertEquals(SimpleEnum.SECOND, unsafeGet); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ArrayTest.java index cd5e082f..27fd58ae 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ArrayTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ArrayTest.java @@ -2,7 +2,7 @@ import java.util.Objects; import javasabr.rlib.common.BaseTest; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.NumberUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -14,479 +14,433 @@ */ public class ArrayTest extends BaseTest { - @Test - void ofTest() { + @Test + void ofTest() { - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - array.add("Temp"); - array.remove("Temp"); + var array = ArrayFactory.asArray("First", "Second", "Third", " "); + array.add("Temp"); + array.remove("Temp"); - var copy = Array.of(array); + var copy = Array.of(array); - Assertions.assertEquals(array, copy); + Assertions.assertEquals(array, copy); - var array2 = Array.of("First", "Second", "Third", " "); + var array2 = Array.of("First", "Second", "Third", " "); - Assertions.assertEquals(array, array2); + Assertions.assertEquals(array, array2); - var single = ArrayFactory.asArray("First"); - var single2 = Array.of("First"); + var single = ArrayFactory.asArray("First"); + var single2 = Array.of("First"); - Assertions.assertEquals(single, single2); - } + Assertions.assertEquals(single, single2); + } - @Test - void removeIfTest() { + @Test + void removeIfTest() { - var array = ArrayFactory.asArray("First", "Second", "Third", " "); + var array = ArrayFactory.asArray("First", "Second", "Third", " "); - Assertions.assertTrue(array.removeIf(String::isBlank)); - Assertions.assertEquals(3, array.size()); + Assertions.assertTrue(array.removeIf(String::isBlank)); + Assertions.assertEquals(3, array.size()); - Assertions.assertFalse(array.removeIf(Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; + Assertions.assertFalse(array.removeIf( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return false; })); - Assertions.assertTrue(array.removeIf("Third", String::equals)); - Assertions.assertEquals(2, array.size()); + Assertions.assertTrue(array.removeIf("Third", String::equals)); + Assertions.assertEquals(2, array.size()); - array.add("Third"); + array.add("Third"); - Assertions.assertEquals(3, array.size()); + Assertions.assertEquals(3, array.size()); - Assertions.assertFalse(array.removeIf( - Type1.EXAMPLE, - arg -> { - assertType(arg, Type1.class); - return arg; - }, - (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - } - )); + Assertions.assertFalse(array.removeIf( + Type1.EXAMPLE, arg -> { + assertType(arg, Type1.class); + return arg; + }, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return false; + })); - Assertions.assertTrue(array.removeIf( - "Second", - String::hashCode, - (first, second) -> first.equals(second.hashCode()) - )); + Assertions.assertTrue(array.removeIf( + "Second", + String::hashCode, + (first, second) -> first.equals(second.hashCode()))); - Assertions.assertEquals(2, array.size()); + Assertions.assertEquals(2, array.size()); - array = ArrayFactory.asArray("10", "5", "2", "1"); + array = ArrayFactory.asArray("10", "5", "2", "1"); - Assertions.assertTrue(array.removeIfConverted( - 5, - Integer::parseInt, - Integer::equals - )); + Assertions.assertTrue(array.removeIfConverted(5, Integer::parseInt, Integer::equals)); - Assertions.assertEquals(3, array.size()); - } + Assertions.assertEquals(3, array.size()); + } - @Test - void toArrayTest() { + @Test + void toArrayTest() { - var array = ArrayFactory.asArray("First", "Second", "Third", " "); + var array = ArrayFactory.asArray("First", "Second", "Third", " "); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray(String.class) - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray(String.class)); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray(new String[0]) - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray(new String[0])); - //noinspection ToArrayCallWithZeroLengthArrayArgument - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray(new String[array.size()]) - ); - } + //noinspection ToArrayCallWithZeroLengthArrayArgument + Assertions.assertArrayEquals( + ArrayFactory.toArray("First", "Second", "Third", " "), + array.toArray(new String[array.size()])); + } - @Test - void removeTest() { + @Test + void removeTest() { - var array = ArrayFactory.asArray("First", "Second", "Third", " "); + var array = ArrayFactory.asArray("First", "Second", "Third", " "); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - array.remove("Second"); + array.remove("Second"); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Third", " "), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third", " "), array.toArray()); - array.remove(" "); + array.remove(" "); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Third"), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third"), array.toArray()); - array.remove("First"); + array.remove("First"); - Assertions.assertArrayEquals( - ArrayFactory.toArray("Third"), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("Third"), array.toArray()); - array = ArrayFactory.asArray("First", "Second", "Third", " "); + array = ArrayFactory.asArray("First", "Second", "Third", " "); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - array.remove(1); + array.remove(1); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Third", " "), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third", " "), array.toArray()); - array.remove(2); + array.remove(2); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Third"), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third"), array.toArray()); - array.remove(0); + array.remove(0); - Assertions.assertArrayEquals( - ArrayFactory.toArray("Third"), - array.toArray() - ); - } + Assertions.assertArrayEquals(ArrayFactory.toArray("Third"), array.toArray()); + } - @Test - void findAnyTest() { + @Test + void findAnyTest() { - var array = ArrayFactory.asArray("First", "Second", "Third", " "); + var array = ArrayFactory.asArray("First", "Second", "Third", " "); - Assertions.assertNotNull(array.findAny("Second"::equals)); + Assertions.assertNotNull(array.findAny("Second"::equals)); - Assertions.assertNull(array.findAny(Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; + Assertions.assertNull(array.findAny( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return false; })); - Assertions.assertNotNull(array.findAny("Third", String::equals)); + Assertions.assertNotNull(array.findAny("Third", String::equals)); - Assertions.assertNull(array.findAnyR(Type1.EXAMPLE, (element, arg) -> { - assertType(element, String.class); - assertType(arg, Type1.class); - return false; + Assertions.assertNull(array.findAnyR( + Type1.EXAMPLE, (element, arg) -> { + assertType(element, String.class); + assertType(arg, Type1.class); + return false; })); - Assertions.assertNotNull(array.findAnyR("Third", String::equals)); + Assertions.assertNotNull(array.findAnyR("Third", String::equals)); - Assertions.assertNull(array.findAny(Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - return false; + Assertions.assertNull(array.findAny( + Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + assertType(element, String.class); + return false; })); - Assertions.assertNotNull(array.findAny("First", "Second", - (first, second, element) -> first.equals(element) || second.equals(element))); + Assertions.assertNotNull(array.findAny( + "First", + "Second", + (first, second, element) -> first.equals(element) || second.equals(element))); - Assertions.assertNotNull(array.findAny("First".hashCode(), (num, element) -> { - assertIntType(num); - assertType(element, String.class); - return num == element.hashCode(); + Assertions.assertNotNull(array.findAny( + "First".hashCode(), (num, element) -> { + assertIntType(num); + assertType(element, String.class); + return num == element.hashCode(); })); - Assertions.assertNotNull(array.findAny("First".hashCode(), (num, element) -> num == element.hashCode())); + Assertions.assertNotNull(array.findAny("First".hashCode(), (num, element) -> num == element.hashCode())); - Assertions.assertNotNull(array.findAnyL("First".hashCode(), (num, element) -> { - assertLongType(num); - assertType(element, String.class); - return num == element.hashCode(); + Assertions.assertNotNull(array.findAnyL( + "First".hashCode(), (num, element) -> { + assertLongType(num); + assertType(element, String.class); + return num == element.hashCode(); })); - Assertions.assertNotNull(array.findAnyL("First".hashCode(), (num, element) -> num == element.hashCode())); - - Assertions.assertNotNull(array.findAnyConvertedToInt( - "First".hashCode(), - String::hashCode, - NumberUtils::equals - )); - - Assertions.assertNotNull(array.findAnyConvertedToInt( - "MyValue".hashCode(), - object -> "MyValue", - String::hashCode, - NumberUtils::equals - )); - - Assertions.assertNull(array.findAnyConvertedToInt( - "MyValue".hashCode(), - object -> "First", - String::hashCode, - NumberUtils::equals - )); - - Assertions.assertNotNull(array.findAnyConverted( - "First".hashCode(), - String::hashCode, - Objects::equals - )); - } - - @Test - void anyMatchTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertFalse(array.anyMatch(Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; + Assertions.assertNotNull(array.findAnyL("First".hashCode(), (num, element) -> num == element.hashCode())); + + Assertions.assertNotNull(array.findAnyConvertedToInt("First".hashCode(), String::hashCode, NumberUtils::equals)); + + Assertions.assertNotNull(array.findAnyConvertedToInt( + "MyValue".hashCode(), + object -> "MyValue", + String::hashCode, + NumberUtils::equals)); + + Assertions.assertNull(array.findAnyConvertedToInt( + "MyValue".hashCode(), + object -> "First", + String::hashCode, + NumberUtils::equals)); + + Assertions.assertNotNull(array.findAnyConverted("First".hashCode(), String::hashCode, Objects::equals)); + } + + @Test + void anyMatchTest() { + + var array = ArrayFactory.asArray("First", "Second", "Third", " "); + + Assertions.assertFalse(array.anyMatch( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return false; })); - Assertions.assertTrue(array.anyMatch("Second", String::equals)); - Assertions.assertFalse(array.anyMatch("None", String::equals)); + Assertions.assertTrue(array.anyMatch("Second", String::equals)); + Assertions.assertFalse(array.anyMatch("None", String::equals)); - Assertions.assertFalse(array.anyMatch("None".hashCode(), (arg, element) -> { - assertIntType(arg); - assertType(element, String.class); - return arg == element.hashCode(); + Assertions.assertFalse(array.anyMatch( + "None".hashCode(), (arg, element) -> { + assertIntType(arg); + assertType(element, String.class); + return arg == element.hashCode(); })); - Assertions.assertTrue(array.anyMatch("Second".hashCode(), (num, element) -> num == element.hashCode())); - Assertions.assertFalse(array.anyMatch("None".hashCode(), (num, element) -> num == element.hashCode())); + Assertions.assertTrue(array.anyMatch("Second".hashCode(), (num, element) -> num == element.hashCode())); + Assertions.assertFalse(array.anyMatch("None".hashCode(), (num, element) -> num == element.hashCode())); - Assertions.assertFalse(array.anyMatchR(Type1.EXAMPLE, (element, arg) -> { - assertType(element, String.class); - assertType(arg, Type1.class); - return false; + Assertions.assertFalse(array.anyMatchR( + Type1.EXAMPLE, (element, arg) -> { + assertType(element, String.class); + assertType(arg, Type1.class); + return false; })); - Assertions.assertTrue(array.anyMatchR("Second".hashCode(), (element, num) -> element.hashCode() == num)); - Assertions.assertFalse(array.anyMatchR("None".hashCode(), (element, num) -> element.hashCode() == num)); + Assertions.assertTrue(array.anyMatchR("Second".hashCode(), (element, num) -> element.hashCode() == num)); + Assertions.assertFalse(array.anyMatchR("None".hashCode(), (element, num) -> element.hashCode() == num)); - Assertions.assertTrue(array.anyMatchConverted("Second".hashCode(), String::hashCode, Objects::equals)); - Assertions.assertFalse(array.anyMatchConverted("None".hashCode(), String::hashCode, Objects::equals)); - } + Assertions.assertTrue(array.anyMatchConverted("Second".hashCode(), String::hashCode, Objects::equals)); + Assertions.assertFalse(array.anyMatchConverted("None".hashCode(), String::hashCode, Objects::equals)); + } - @Test - void replaceTest() { + @Test + void replaceTest() { - var array = ArrayFactory.asArray("First", "Second", "Third", " "); + var array = ArrayFactory.asArray("First", "Second", "Third", " "); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - array.replace(1, "NotSecond"); + array.replace(1, "NotSecond"); - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "NotSecond", "Third", " "), - array.toArray() - ); + Assertions.assertEquals(4, array.size()); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "NotSecond", "Third", " "), array.toArray()); - array.replace(3, "NotEmpty"); + array.replace(3, "NotEmpty"); - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "NotSecond", "Third", "NotEmpty"), - array.toArray() - ); - } + Assertions.assertEquals(4, array.size()); + Assertions.assertArrayEquals(ArrayFactory.toArray("First", "NotSecond", "Third", "NotEmpty"), array.toArray()); + } - @Test - void countTest() { + @Test + void countTest() { - var array = ArrayFactory.asArray("First", "Second", "First", "Third"); + var array = ArrayFactory.asArray("First", "Second", "First", "Third"); - Assertions.assertEquals(2, array.count("First"::equals)); - Assertions.assertEquals(1, array.count("Second"::equals)); + Assertions.assertEquals(2, array.count("First"::equals)); + Assertions.assertEquals(1, array.count("Second"::equals)); - Assertions.assertEquals(2, array.count("First", String::equals)); - Assertions.assertEquals(1, array.count("Second", String::equals)); + Assertions.assertEquals(2, array.count("First", String::equals)); + Assertions.assertEquals(1, array.count("Second", String::equals)); - Assertions.assertEquals(2, array.countR("First", String::equals)); - Assertions.assertEquals(1, array.countR("Second", String::equals)); - } + Assertions.assertEquals(2, array.countR("First", String::equals)); + Assertions.assertEquals(1, array.countR("Second", String::equals)); + } - @Test - void forEachTest() { + @Test + void forEachTest() { - var array = Array.of("First", "Second", "Third", " ", "Third"); - var counter = new AtomicInteger(0); + var array = Array.of("First", "Second", "Third", " ", "Third"); + var counter = new ReusableAtomicInteger(0); - array.forEach(element -> counter.incrementAndGet()); + array.forEach(element -> counter.incrementAndGet()); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); - array.forEachFiltered("First"::equals, el -> counter.incrementAndGet()); + array.forEachFiltered("First"::equals, el -> counter.incrementAndGet()); - Assertions.assertEquals(1, counter.getAndSet(0)); + Assertions.assertEquals(1, counter.getAndSet(0)); - array.forEach(Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); + array.forEach( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); - array.forEachR(Type1.EXAMPLE, (element, arg) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); + array.forEachR( + Type1.EXAMPLE, (element, arg) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); - array.forEachConverted(Type1.EXAMPLE, String::getBytes, (arg, converted) -> { - assertType(arg, Type1.class); - assertType(converted, byte[].class); - counter.incrementAndGet(); + array.forEachConverted( + Type1.EXAMPLE, String::getBytes, (arg, converted) -> { + assertType(arg, Type1.class); + assertType(converted, byte[].class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); - array.forEachConverted(Type1.EXAMPLE, Type2.EXAMPLE, String::getBytes, (arg1, arg2, converted) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(converted, byte[].class); - counter.incrementAndGet(); + array.forEachConverted( + Type1.EXAMPLE, Type2.EXAMPLE, String::getBytes, (arg1, arg2, converted) -> { + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + assertType(converted, byte[].class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); + + array.forEach( + "Arg", String::getBytes, (arg, element) -> { + assertType(arg, byte[].class); + assertType(element, String.class); + counter.incrementAndGet(); + }); - array.forEach("Arg", String::getBytes, (arg, element) -> { - assertType(arg, byte[].class); - assertType(element, String.class); - counter.incrementAndGet(); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); + + array.forEachFiltered( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return "Second".equals(element); + }, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachFiltered(Type1.EXAMPLE, - (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return "Second".equals(element); - }, - (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - } - ); - - Assertions.assertEquals(1, counter.getAndSet(0)); - - array.forEach(Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); + Assertions.assertEquals(1, counter.getAndSet(0)); + + array.forEach( + Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); - array.forEachR(Type1.EXAMPLE, Type2.EXAMPLE, (element, arg1, arg2) -> { - assertType(element, String.class); - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - counter.incrementAndGet(); + array.forEachR( + Type1.EXAMPLE, Type2.EXAMPLE, (element, arg1, arg2) -> { + assertType(element, String.class); + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachFiltered( - Type1.EXAMPLE, - Type2.EXAMPLE, - (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - return "First".equals(element) || "Second".equals(element); - }, - (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); - } - ); - - Assertions.assertEquals(2, counter.getAndSet(0)); - - array.forEachL(1L, Type1.EXAMPLE, (arg1, arg2, element) -> { - assertLongType(arg1); - assertType(arg2, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); + + array.forEachFiltered( + Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + assertType(element, String.class); + return "First".equals(element) || "Second".equals(element); + }, (arg1, arg2, element) -> { + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + assertType(element, String.class); + counter.incrementAndGet(); + }); + + Assertions.assertEquals(2, counter.getAndSet(0)); + + array.forEachL( + 1L, Type1.EXAMPLE, (arg1, arg2, element) -> { + assertLongType(arg1); + assertType(arg2, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); - array.forEachF(1F, Type1.EXAMPLE, (arg1, arg2, element) -> { - assertFloatType(arg1); - assertType(arg2, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); + array.forEachF( + 1F, Type1.EXAMPLE, (arg1, arg2, element) -> { + assertFloatType(arg1); + assertType(arg2, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); + Assertions.assertEquals(array.size(), counter.getAndSet(0)); - array.forEach(0, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertIntType(arg1); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); + array.forEach( + 0, Type2.EXAMPLE, (arg1, arg2, element) -> { + assertIntType(arg1); + assertType(arg2, Type2.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - } + Assertions.assertEquals(array.size(), counter.getAndSet(0)); + } - @Test - void fastRemoveAllTest() { + @Test + void fastRemoveAllTest() { - var array = ArrayFactory.asArray("First", "Second", "Third", " ", "55", "66", "22", "22", "11"); - var toRemove = ArrayFactory.asArray("First", "Third", "66", "22"); - var result = ArrayFactory.asArray("Second", " ", "55", "11"); - result.sort(String::compareTo); + var array = ArrayFactory.asArray("First", "Second", "Third", " ", "55", "66", "22", "22", "11"); + var toRemove = ArrayFactory.asArray("First", "Third", "66", "22"); + var result = ArrayFactory.asArray("Second", " ", "55", "11"); + result.sort(String::compareTo); - array.fastRemoveAll(toRemove); - array.sort(String::compareTo); + array.fastRemoveAll(toRemove); + array.sort(String::compareTo); - Assertions.assertEquals(result, array); - } + Assertions.assertEquals(result, array); + } - @Test - void copyToTest() { + @Test + void copyToTest() { - var toCopy = ArrayFactory.asArray("123", "321", "555"); - var toCombine = ArrayFactory.asArray("First", "Second"); - var result = ArrayFactory.asArray("First", "Second", "123", "321", "555"); + var toCopy = ArrayFactory.asArray("123", "321", "555"); + var toCombine = ArrayFactory.asArray("First", "Second"); + var result = ArrayFactory.asArray("First", "Second", "123", "321", "555"); - toCopy.copyTo(toCombine); + toCopy.copyTo(toCombine); - Assertions.assertEquals(result, toCombine); - } + Assertions.assertEquals(result, toCombine); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ConcurrentArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ConcurrentArrayTest.java index 2c71c99e..b108bddb 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ConcurrentArrayTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ConcurrentArrayTest.java @@ -9,7 +9,7 @@ import java.util.Collections; import java.util.Objects; import javasabr.rlib.common.BaseTest; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.NumberUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -19,361 +19,337 @@ */ public class ConcurrentArrayTest extends BaseTest { - @Test - void addTest() { + @Test + void addTest() { - var array = ConcurrentArray.ofType(String.class); + var array = ConcurrentArray.ofType(String.class); - assertEquals(0, array.size()); + assertEquals(0, array.size()); - array.add("First"); + array.add("First"); - assertEquals(1, array.size()); - assertEquals(Array.of("First"), array); - assertEquals(array, Array.of("First")); + assertEquals(1, array.size()); + assertEquals(Array.of("First"), array); + assertEquals(array, Array.of("First")); - array.addAll(ArrayFactory.toArray("Second", "Third")); + array.addAll(ArrayFactory.toArray("Second", "Third")); - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Second", "Third"), array); + assertEquals(3, array.size()); + assertEquals(Array.of("First", "Second", "Third"), array); - array.addAll(ArrayFactory.asArray("Fourth", "Fifth")); + array.addAll(ArrayFactory.asArray("Fourth", "Fifth")); - assertEquals(5, array.size()); - assertEquals(Array.of("First", "Second", "Third", "Fourth", "Fifth"), array); - } + assertEquals(5, array.size()); + assertEquals(Array.of("First", "Second", "Third", "Fourth", "Fifth"), array); + } - @Test - void removeTest() { + @Test + void removeTest() { - var array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); + var array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - assertEquals(4, array.size()); + assertEquals(4, array.size()); - array.remove("Second"); + array.remove("Second"); - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Third", "Fourth"), array); + assertEquals(3, array.size()); + assertEquals(Array.of("First", "Third", "Fourth"), array); - array.removeAll(ArrayFactory.asArray("First", "Fourth")); + array.removeAll(ArrayFactory.asArray("First", "Fourth")); - assertEquals(1, array.size()); - assertEquals(Array.of("Third"), array); + assertEquals(1, array.size()); + assertEquals(Array.of("Third"), array); - array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); + array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - assertEquals(4, array.size()); + assertEquals(4, array.size()); - array.remove(2); + array.remove(2); - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Second", "Fourth"), array); + assertEquals(3, array.size()); + assertEquals(Array.of("First", "Second", "Fourth"), array); - array.removeAll(Collections.singletonList("First")); + array.removeAll(Collections.singletonList("First")); - assertEquals(2, array.size()); - assertEquals(Array.of("Second", "Fourth"), array); - } + assertEquals(2, array.size()); + assertEquals(Array.of("Second", "Fourth"), array); + } - @Test - void fastRemoveTest() { + @Test + void fastRemoveTest() { - var array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); + var array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - assertEquals(4, array.size()); + assertEquals(4, array.size()); - array.fastRemove("Second"); + array.fastRemove("Second"); - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Fourth", "Third"), array); + assertEquals(3, array.size()); + assertEquals(Array.of("First", "Fourth", "Third"), array); - array.fastRemoveAll(ArrayFactory.asArray("First", "Fourth")); + array.fastRemoveAll(ArrayFactory.asArray("First", "Fourth")); - assertEquals(1, array.size()); - assertEquals(Array.of("Third"), array); + assertEquals(1, array.size()); + assertEquals(Array.of("Third"), array); - array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); + array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - assertEquals(4, array.size()); + assertEquals(4, array.size()); - array.fastRemove(1); + array.fastRemove(1); - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Fourth", "Third"), array); + assertEquals(3, array.size()); + assertEquals(Array.of("First", "Fourth", "Third"), array); - array.fastRemoveAll(ArrayFactory.toArray("First", "Third")); + array.fastRemoveAll(ArrayFactory.toArray("First", "Third")); - assertEquals(1, array.size()); - assertEquals(Array.of("Fourth"), array); - } + assertEquals(1, array.size()); + assertEquals(Array.of("Fourth"), array); + } - @Test - void removeIfInWriteLockTest() { + @Test + void removeIfInWriteLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " "); + var array = ConcurrentArray.of("First", "Second", "Third", " "); - assertTrue(array.removeIfInWriteLock(String::isBlank)); - assertEquals(3, array.size()); + assertTrue(array.removeIfInWriteLock(String::isBlank)); + assertEquals(3, array.size()); - assertFalse(array.removeIfInWriteLock(Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; + assertFalse(array.removeIfInWriteLock( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return false; })); - assertTrue(array.removeIfInWriteLock("Third", String::equals)); - assertEquals(2, array.size()); + assertTrue(array.removeIfInWriteLock("Third", String::equals)); + assertEquals(2, array.size()); - array.add("Third"); + array.add("Third"); - assertEquals(3, array.size()); + assertEquals(3, array.size()); - assertFalse(array.removeIfInWriteLock( - Type1.EXAMPLE, - arg -> { - assertType(arg, Type1.class); - return arg; - }, - (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - } - )); + assertFalse(array.removeIfInWriteLock( + Type1.EXAMPLE, arg -> { + assertType(arg, Type1.class); + return arg; + }, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return false; + })); - assertTrue(array.removeIfInWriteLock( - "Second", - String::hashCode, - (first, second) -> first.equals(second.hashCode()) - )); + assertTrue(array.removeIfInWriteLock( + "Second", + String::hashCode, + (first, second) -> first.equals(second.hashCode()))); - assertEquals(2, array.size()); + assertEquals(2, array.size()); - array = ConcurrentArray.of("10", "5", "2", "1"); + array = ConcurrentArray.of("10", "5", "2", "1"); - assertTrue(array.removeIfConvertedInWriteLock( - 5, - Integer::parseInt, - Integer::equals - )); + assertTrue(array.removeIfConvertedInWriteLock(5, Integer::parseInt, Integer::equals)); - assertEquals(3, array.size()); - } + assertEquals(3, array.size()); + } - @Test - void anyMatchInReadLockTest() { + @Test + void anyMatchInReadLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " "); + var array = ConcurrentArray.of("First", "Second", "Third", " "); - assertFalse(array.anyMatchInReadLock(Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; + assertFalse(array.anyMatchInReadLock( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + return false; })); - assertTrue(array.anyMatchInReadLock("Second", String::equals)); - assertFalse(array.anyMatchInReadLock("None", String::equals)); + assertTrue(array.anyMatchInReadLock("Second", String::equals)); + assertFalse(array.anyMatchInReadLock("None", String::equals)); - assertFalse(array.anyMatchInReadLock("None".hashCode(), (arg, element) -> { - assertIntType(arg); - assertType(element, String.class); - return arg == element.hashCode(); + assertFalse(array.anyMatchInReadLock( + "None".hashCode(), (arg, element) -> { + assertIntType(arg); + assertType(element, String.class); + return arg == element.hashCode(); })); - assertTrue(array.anyMatchInReadLock("Second".hashCode(), (val, string) -> val == string.hashCode())); - assertFalse(array.anyMatchInReadLock("None".hashCode(), (val, string) -> val == string.hashCode())); + assertTrue(array.anyMatchInReadLock("Second".hashCode(), (val, string) -> val == string.hashCode())); + assertFalse(array.anyMatchInReadLock("None".hashCode(), (val, string) -> val == string.hashCode())); - assertTrue(array.anyMatchConvertedInReadLock( - "Second".hashCode(), - String::hashCode, - Objects::equals - )); + assertTrue(array.anyMatchConvertedInReadLock("Second".hashCode(), String::hashCode, Objects::equals)); - assertFalse(array.anyMatchConvertedInReadLock( - "None".hashCode(), - String::hashCode, - Objects::equals - )); - } + assertFalse(array.anyMatchConvertedInReadLock("None".hashCode(), String::hashCode, Objects::equals)); + } - @Test - void findAnyInReadLockTest() { + @Test + void findAnyInReadLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " "); + var array = ConcurrentArray.of("First", "Second", "Third", " "); - assertNull(array.findAnyInReadLock("None".hashCode(), (arg, element) -> { - assertIntType(arg); - assertType(element, String.class); - return arg == element.hashCode(); + assertNull(array.findAnyInReadLock( + "None".hashCode(), (arg, element) -> { + assertIntType(arg); + assertType(element, String.class); + return arg == element.hashCode(); })); - assertNotNull(array.findAnyInReadLock("Second".hashCode(), (val, string) -> val == string.hashCode())); - assertNull(array.findAnyInReadLock("None".hashCode(), (val, string) -> val == string.hashCode())); + assertNotNull(array.findAnyInReadLock("Second".hashCode(), (val, string) -> val == string.hashCode())); + assertNull(array.findAnyInReadLock("None".hashCode(), (val, string) -> val == string.hashCode())); - assertNotNull(array.findAnyConvertedToIntInReadLock( - "First".hashCode(), - String::hashCode, - NumberUtils::equals - )); + assertNotNull(array.findAnyConvertedToIntInReadLock("First".hashCode(), String::hashCode, NumberUtils::equals)); - assertNotNull(array.findAnyConvertedInReadLock( - "First".hashCode(), - String::hashCode, - Objects::equals - )); + assertNotNull(array.findAnyConvertedInReadLock("First".hashCode(), String::hashCode, Objects::equals)); - Assertions.assertNotNull(array.findAnyConvertedToIntInReadLock( - "MyValue".hashCode(), - object -> "MyValue", - String::hashCode, - NumberUtils::equals - )); + Assertions.assertNotNull(array.findAnyConvertedToIntInReadLock( + "MyValue".hashCode(), + object -> "MyValue", + String::hashCode, + NumberUtils::equals)); - Assertions.assertNull(array.findAnyConvertedToIntInReadLock( - "MyValue".hashCode(), - object -> "First", - String::hashCode, - NumberUtils::equals - )); - } + Assertions.assertNull(array.findAnyConvertedToIntInReadLock( + "MyValue".hashCode(), + object -> "First", + String::hashCode, + NumberUtils::equals)); + } - @Test - void runInWriteLockTest() { + @Test + void runInWriteLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " "); + var array = ConcurrentArray.of("First", "Second", "Third", " "); - array.runInWriteLock(1, "Second", (arr, first, second) -> assertEquals(second, arr.get(first))); + array.runInWriteLock(1, "Second", (arr, first, second) -> assertEquals(second, arr.get(first))); - array.runInWriteLock(object -> object.remove("Second")); + array.runInWriteLock(object -> object.remove("Second")); - assertEquals(3, array.size()); + assertEquals(3, array.size()); - array.runInWriteLock(Type1.EXAMPLE, (arr, arg) -> { - assertType(arr, Array.class); - assertType(arg, Type1.class); + array.runInWriteLock( + Type1.EXAMPLE, (arr, arg) -> { + assertType(arr, Array.class); + assertType(arg, Type1.class); }); - array.runInWriteLock("Third", Array::remove); + array.runInWriteLock("Third", Array::remove); - assertEquals(2, array.size()); - } + assertEquals(2, array.size()); + } - @Test - void runInReadLockTest() { + @Test + void runInReadLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); + var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - array.runInReadLock(arr -> assertEquals(2, arr.count(el -> el.equals("Third")))); + array.runInReadLock(arr -> assertEquals(2, arr.count(el -> el.equals("Third")))); - array.runInReadLock("Third", (arr, arg) -> { - assertType(arr, Array.class); - assertType(arg, String.class); - assertEquals(2, arr.count(arg, String::equals)); + array.runInReadLock( + "Third", (arr, arg) -> { + assertType(arr, Array.class); + assertType(arg, String.class); + assertEquals(2, arr.count(arg, String::equals)); }); - array.runInReadLock("Third", (arr, arg) -> - assertEquals(2, arr.count(arg, String::equals))); + array.runInReadLock("Third", (arr, arg) -> assertEquals(2, arr.count(arg, String::equals))); - array.runInReadLock(2, "Third", (arr, first, second) -> { - assertType(arr, Array.class); - assertIntType(first); - assertType(second, String.class); - assertEquals(first, arr.count(second, String::equals)); + array.runInReadLock( + 2, "Third", (arr, first, second) -> { + assertType(arr, Array.class); + assertIntType(first); + assertType(second, String.class); + assertEquals(first, arr.count(second, String::equals)); }); - } + } - @Test - void getInWriteLockTest() { + @Test + void getInWriteLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); + var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - assertEquals("Third", array.getInWriteLock(arr -> arr.get(2))); - assertEquals("Second", array.getInWriteLock(1, Array::get)); - assertEquals( - "FirstSecond", - array.getInWriteLock(0, 1, (arr, first, second) -> arr.get(first) + arr.get(second)) - ); - } + assertEquals("Third", array.getInWriteLock(arr -> arr.get(2))); + assertEquals("Second", array.getInWriteLock(1, Array::get)); + assertEquals("FirstSecond", array.getInWriteLock(0, 1, (arr, first, second) -> arr.get(first) + arr.get(second))); + } - @Test - void getInReadLockTest() { + @Test + void getInReadLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); + var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - assertEquals("Third", array.getInReadLock(arr -> arr.get(2))); - assertEquals("Second", array.getInReadLock(1, Array::get)); - assertEquals( - "FirstSecond", - array.getInReadLock(0, 1, (arr, first, second) -> arr.get(first) + arr.get(second)) - ); - } + assertEquals("Third", array.getInReadLock(arr -> arr.get(2))); + assertEquals("Second", array.getInReadLock(1, Array::get)); + assertEquals("FirstSecond", array.getInReadLock(0, 1, (arr, first, second) -> arr.get(first) + arr.get(second))); + } - @Test - void forEachInReadLockTest() { + @Test + void forEachInReadLockTest() { - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - var counter = new AtomicInteger(0); + var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); + var counter = new ReusableAtomicInteger(0); - array.forEachInReadLock(element -> counter.incrementAndGet()); + array.forEachInReadLock(element -> counter.incrementAndGet()); - assertEquals(array.size(), counter.getAndSet(0)); + assertEquals(array.size(), counter.getAndSet(0)); - array.forEachInReadLock(Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); + array.forEachInReadLock( + Type1.EXAMPLE, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachInReadLock( - Type1.EXAMPLE, - arg -> { - assertType(arg, Type1.class); - return arg; - }, - (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - } - ); - - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachConvertedInReadLock(Type1.EXAMPLE, String::hashCode, (arg, element) -> { - assertType(arg, Type1.class); - assertIntType(element); - counter.incrementAndGet(); + assertEquals(array.size(), counter.getAndSet(0)); + + array.forEachInReadLock( + Type1.EXAMPLE, arg -> { + assertType(arg, Type1.class); + return arg; + }, (arg, element) -> { + assertType(arg, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); + }); + + assertEquals(array.size(), counter.getAndSet(0)); + + array.forEachConvertedInReadLock( + Type1.EXAMPLE, String::hashCode, (arg, element) -> { + assertType(arg, Type1.class); + assertIntType(element); + counter.incrementAndGet(); }); - assertEquals(array.size(), counter.getAndSet(0)); + assertEquals(array.size(), counter.getAndSet(0)); - array.forEachConvertedInReadLock(Type1.EXAMPLE, Type2.EXAMPLE, String::hashCode, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertIntType(element); - counter.incrementAndGet(); + array.forEachConvertedInReadLock( + Type1.EXAMPLE, Type2.EXAMPLE, String::hashCode, (arg1, arg2, element) -> { + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + assertIntType(element); + counter.incrementAndGet(); }); - assertEquals(array.size(), counter.getAndSet(0)); + assertEquals(array.size(), counter.getAndSet(0)); - array.forEachInReadLock(0, Type1.EXAMPLE, (arg1, arg2, element) -> { - assertIntType(arg1); - assertType(arg2, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); + array.forEachInReadLock( + 0, Type1.EXAMPLE, (arg1, arg2, element) -> { + assertIntType(arg1); + assertType(arg2, Type1.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - assertEquals(array.size(), counter.getAndSet(0)); + assertEquals(array.size(), counter.getAndSet(0)); - array.forEachInReadLock(Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); + array.forEachInReadLock( + Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { + assertType(arg1, Type1.class); + assertType(arg2, Type2.class); + assertType(element, String.class); + counter.incrementAndGet(); }); - assertEquals(array.size(), counter.getAndSet(0)); - } + assertEquals(array.size(), counter.getAndSet(0)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/CopyOnModifyArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/CopyOnModifyArrayTest.java index 91d7a668..2b7cc66e 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/CopyOnModifyArrayTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/array/CopyOnModifyArrayTest.java @@ -9,238 +9,238 @@ public class CopyOnModifyArrayTest { - @Test - void addTest() { + @Test + void addTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); - Assertions.assertEquals(1, array.size()); + Assertions.assertEquals(1, array.size()); - array.add("Second"); + array.add("Second"); - Assertions.assertEquals(2, array.size()); + Assertions.assertEquals(2, array.size()); - array.add("Third"); + array.add("Third"); - Assertions.assertEquals(3, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third"), array.array()); - Assertions.assertEquals("Second", array.get(1)); - } + Assertions.assertEquals(3, array.size()); + Assertions.assertArrayEquals(toArray("First", "Second", "Third"), array.array()); + Assertions.assertEquals("Second", array.get(1)); + } - @Test - void addArrayTest() { + @Test + void addArrayTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.addAll(Array.of("Third", "Fourth")); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); + array.add("Second"); + array.addAll(Array.of("Third", "Fourth")); - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - Assertions.assertEquals("Second", array.get(1)); + Assertions.assertEquals(4, array.size()); + Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); + Assertions.assertEquals("Second", array.get(1)); - array.addAll(Array.of("Fifth", "Six")); + array.addAll(Array.of("Fifth", "Six")); - Assertions.assertEquals(6, array.size()); - Assertions.assertEquals("Fifth", array.get(4)); - } + Assertions.assertEquals(6, array.size()); + Assertions.assertEquals("Fifth", array.get(4)); + } - @Test - void addCollectionTest() { + @Test + void addCollectionTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.addAll(List.of("Third", "Fourth")); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); + array.add("Second"); + array.addAll(List.of("Third", "Fourth")); - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - Assertions.assertEquals("Second", array.get(1)); + Assertions.assertEquals(4, array.size()); + Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); + Assertions.assertEquals("Second", array.get(1)); - array.addAll(List.of("Fifth", "Six")); + array.addAll(List.of("Fifth", "Six")); - Assertions.assertEquals(6, array.size()); - Assertions.assertEquals("Fifth", array.get(4)); - } + Assertions.assertEquals(6, array.size()); + Assertions.assertEquals("Fifth", array.get(4)); + } - @Test - void addNativeArrayTest() { + @Test + void addNativeArrayTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.addAll(toArray("Third", "Fourth")); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); + array.add("Second"); + array.addAll(toArray("Third", "Fourth")); - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - Assertions.assertEquals("Second", array.get(1)); + Assertions.assertEquals(4, array.size()); + Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); + Assertions.assertEquals("Second", array.get(1)); - array.addAll(toArray("Fifth", "Six")); + array.addAll(toArray("Fifth", "Six")); - Assertions.assertEquals(6, array.size()); - Assertions.assertEquals("Fifth", array.get(4)); - } + Assertions.assertEquals(6, array.size()); + Assertions.assertEquals("Fifth", array.get(4)); + } - @Test - void arrayTest() { + @Test + void arrayTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); - Assertions.assertArrayEquals(toArray("First"), array.array()); + Assertions.assertArrayEquals(toArray("First"), array.array()); - array.add("Second"); + array.add("Second"); - Assertions.assertArrayEquals(toArray("First", "Second"), array.array()); + Assertions.assertArrayEquals(toArray("First", "Second"), array.array()); - array.addAll(toArray("Third", "Fourth")); + array.addAll(toArray("Third", "Fourth")); - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); + Assertions.assertEquals(4, array.size()); + Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - array.remove("Second"); + array.remove("Second"); - Assertions.assertArrayEquals(toArray("First", "Third", "Fourth"), array.array()); + Assertions.assertArrayEquals(toArray("First", "Third", "Fourth"), array.array()); - array.removeAll(asArray("First", "Fourth")); + array.removeAll(asArray("First", "Fourth")); - Assertions.assertArrayEquals(toArray("Third"), array.array()); + Assertions.assertArrayEquals(toArray("Third"), array.array()); - Assertions.assertEquals(1, array.size()); - } + Assertions.assertEquals(1, array.size()); + } - @Test - void removeArrayTest() { + @Test + void removeArrayTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.add("Third"); - array.add("Fourth"); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); + array.add("Second"); + array.add("Third"); + array.add("Fourth"); - array.removeAll(Array.of("Second", "Third")); + array.removeAll(Array.of("Second", "Third")); - Assertions.assertEquals(2, array.size()); - Assertions.assertArrayEquals(toArray("First", "Fourth"), array.array()); + Assertions.assertEquals(2, array.size()); + Assertions.assertArrayEquals(toArray("First", "Fourth"), array.array()); - array.add("Second"); - array.add("Third"); + array.add("Second"); + array.add("Third"); - array.removeAll(Array.of("First")); + array.removeAll(Array.of("First")); - Assertions.assertArrayEquals(toArray("Fourth", "Second", "Third"), array.array()); + Assertions.assertArrayEquals(toArray("Fourth", "Second", "Third"), array.array()); - array.removeAll(Array.of("Second", "Third")); + array.removeAll(Array.of("Second", "Third")); - Assertions.assertArrayEquals(toArray("Fourth"), array.array()); + Assertions.assertArrayEquals(toArray("Fourth"), array.array()); - array.clear(); + array.clear(); - Assertions.assertArrayEquals(toArray(), array.array()); + Assertions.assertArrayEquals(toArray(), array.array()); - array.add("First"); - array.add("First"); - array.add("First"); - array.add("Second"); - array.add("Second"); + array.add("First"); + array.add("First"); + array.add("First"); + array.add("Second"); + array.add("Second"); - array.removeAll(Array.of("First", "Second")); + array.removeAll(Array.of("First", "Second")); - Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); - } + Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); + } - @Test - void removeCollectionTest() { + @Test + void removeCollectionTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.add("Third"); - array.add("Fourth"); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); + array.add("Second"); + array.add("Third"); + array.add("Fourth"); - array.removeAll(List.of("Second", "Third")); + array.removeAll(List.of("Second", "Third")); - Assertions.assertEquals(2, array.size()); - Assertions.assertArrayEquals(toArray("First", "Fourth"), array.array()); + Assertions.assertEquals(2, array.size()); + Assertions.assertArrayEquals(toArray("First", "Fourth"), array.array()); - array.add("Second"); - array.add("Third"); + array.add("Second"); + array.add("Third"); - array.removeAll(List.of("First")); + array.removeAll(List.of("First")); - Assertions.assertArrayEquals(toArray("Fourth", "Second", "Third"), array.array()); + Assertions.assertArrayEquals(toArray("Fourth", "Second", "Third"), array.array()); - array.removeAll(List.of("Second", "Third")); + array.removeAll(List.of("Second", "Third")); - Assertions.assertArrayEquals(toArray("Fourth"), array.array()); + Assertions.assertArrayEquals(toArray("Fourth"), array.array()); - array.clear(); + array.clear(); - Assertions.assertArrayEquals(toArray(), array.array()); + Assertions.assertArrayEquals(toArray(), array.array()); - array.add("First"); - array.add("First"); - array.add("First"); - array.add("Second"); - array.add("Second"); + array.add("First"); + array.add("First"); + array.add("First"); + array.add("Second"); + array.add("Second"); - array.removeAll(List.of("First", "Second")); + array.removeAll(List.of("First", "Second")); - Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); - } + Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); + } - @Test - void removeElementTest(){ + @Test + void removeElementTest() { - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.add("Third"); - array.add("Fourth"); + var array = ArrayFactory.newCopyOnModifyArray(String.class); + array.add("First"); + array.add("Second"); + array.add("Third"); + array.add("Fourth"); - array.remove("Second"); + array.remove("Second"); - Assertions.assertEquals(3, array.size()); - Assertions.assertArrayEquals(toArray("First", "Third", "Fourth"), array.array()); + Assertions.assertEquals(3, array.size()); + Assertions.assertArrayEquals(toArray("First", "Third", "Fourth"), array.array()); - array.add("Second"); + array.add("Second"); - array.remove("First"); + array.remove("First"); - Assertions.assertArrayEquals(toArray("Third", "Fourth", "Second"), array.array()); + Assertions.assertArrayEquals(toArray("Third", "Fourth", "Second"), array.array()); - array.remove("Third"); - array.remove("Second"); + array.remove("Third"); + array.remove("Second"); - Assertions.assertArrayEquals(toArray("Fourth"), array.array()); + Assertions.assertArrayEquals(toArray("Fourth"), array.array()); - array.clear(); + array.clear(); - Assertions.assertArrayEquals(toArray(), array.array()); + Assertions.assertArrayEquals(toArray(), array.array()); - array.add("First"); - array.add("First"); - array.add("First"); - array.add("Second"); - array.add("Second"); + array.add("First"); + array.add("First"); + array.add("First"); + array.add("Second"); + array.add("Second"); - array.remove("First"); - array.remove("Second"); + array.remove("First"); + array.remove("Second"); - Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); - } + Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); + } - @Test - void sortTest() { + @Test + void sortTest() { - var array = ArrayFactory.newCopyOnModifyArray(Integer.class); - array.add(10); - array.add(5); - array.add(9); - array.add(1); - array.sort(Integer::compareTo); + var array = ArrayFactory.newCopyOnModifyArray(Integer.class); + array.add(10); + array.add(5); + array.add(9); + array.add(1); + array.sort(Integer::compareTo); - Assertions.assertArrayEquals(toArray(1, 5, 9, 10), array.array()); - } + Assertions.assertArrayEquals(toArray(1, 5, 9, 10), array.array()); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/DefaultIntegerArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/DefaultIntegerArrayTest.java index d0bcd604..fa1bc11d 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/DefaultIntegerArrayTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/array/DefaultIntegerArrayTest.java @@ -5,202 +5,197 @@ public class DefaultIntegerArrayTest { - @Test - void addElementsTest() { + @Test + void addElementsTest() { - var array = ArrayFactory.newMutableIntegerArray(); + var array = ArrayFactory.newMutableIntegerArray(); - Assertions.assertEquals(0, array.size()); + Assertions.assertEquals(0, array.size()); - array.add(5); + array.add(5); - Assertions.assertEquals(1, array.size()); - Assertions.assertEquals(5, array.get(0)); + Assertions.assertEquals(1, array.size()); + Assertions.assertEquals(5, array.get(0)); - array.add(-5); + array.add(-5); - Assertions.assertEquals(2, array.size()); - Assertions.assertEquals(-5, array.get(1)); + Assertions.assertEquals(2, array.size()); + Assertions.assertEquals(-5, array.get(1)); - array.addAll(new int[]{-20, 4}); + array.addAll(new int[]{ + -20, + 4 + }); - Assertions.assertEquals(4, array.size()); - Assertions.assertEquals(-20, array.get(2)); - Assertions.assertEquals(4, array.get(3)); + Assertions.assertEquals(4, array.size()); + Assertions.assertEquals(-20, array.get(2)); + Assertions.assertEquals(4, array.get(3)); - array.addAll(ArrayFactory.newMutableIntegerArray(66, -22)); + array.addAll(ArrayFactory.newMutableIntegerArray(66, -22)); - Assertions.assertEquals(6, array.size()); - Assertions.assertEquals(66, array.get(4)); - Assertions.assertEquals(-22, array.get(5)); - } + Assertions.assertEquals(6, array.size()); + Assertions.assertEquals(66, array.get(4)); + Assertions.assertEquals(-22, array.get(5)); + } - @Test - void removeElementsTest() { + @Test + void removeElementsTest() { - var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - Assertions.assertEquals(5, array.size()); - Assertions.assertEquals(2, array.indexOf(25)); + Assertions.assertEquals(5, array.size()); + Assertions.assertEquals(2, array.indexOf(25)); - array.remove(25); + array.remove(25); - Assertions.assertEquals(4, array.size()); - Assertions.assertEquals(-1, array.indexOf(25)); + Assertions.assertEquals(4, array.size()); + Assertions.assertEquals(-1, array.indexOf(25)); - array.fastRemove(5); + array.fastRemove(5); - Assertions.assertEquals(3, array.size()); - Assertions.assertEquals(-1, array.indexOf(5)); - Assertions.assertEquals(0, array.indexOf(70)); + Assertions.assertEquals(3, array.size()); + Assertions.assertEquals(-1, array.indexOf(5)); + Assertions.assertEquals(0, array.indexOf(70)); - array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - array.removeByIndex(3); + array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + array.removeByIndex(3); - Assertions.assertEquals(4, array.size()); - Assertions.assertEquals(-1, array.indexOf(-1)); - Assertions.assertEquals(3, array.indexOf(70)); + Assertions.assertEquals(4, array.size()); + Assertions.assertEquals(-1, array.indexOf(-1)); + Assertions.assertEquals(3, array.indexOf(70)); - array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - array.fastRemoveByIndex(1); + array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + array.fastRemoveByIndex(1); - Assertions.assertEquals(4, array.size()); - Assertions.assertEquals(-1, array.indexOf(-4)); - Assertions.assertEquals(1, array.indexOf(70)); + Assertions.assertEquals(4, array.size()); + Assertions.assertEquals(-1, array.indexOf(-4)); + Assertions.assertEquals(1, array.indexOf(70)); - array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - array.removeAll(ArrayFactory.newMutableIntegerArray(-4, 70)); + array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + array.removeAll(ArrayFactory.newMutableIntegerArray(-4, 70)); - Assertions.assertEquals(3, array.size()); - Assertions.assertEquals(-1, array.indexOf(-4)); - Assertions.assertEquals(-1, array.indexOf(40)); - Assertions.assertEquals(2, array.indexOf(25)); + Assertions.assertEquals(3, array.size()); + Assertions.assertEquals(-1, array.indexOf(-4)); + Assertions.assertEquals(-1, array.indexOf(40)); + Assertions.assertEquals(2, array.indexOf(25)); - array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - array.retainAll(ArrayFactory.newMutableIntegerArray(25, -1)); + array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + array.retainAll(ArrayFactory.newMutableIntegerArray(25, -1)); - Assertions.assertEquals(2, array.size()); - Assertions.assertEquals(-1, array.indexOf(5)); - Assertions.assertEquals(-1, array.indexOf(-4)); - Assertions.assertEquals(-1, array.indexOf(70)); - Assertions.assertEquals(0, array.indexOf(25)); - Assertions.assertEquals(1, array.indexOf(-1)); - } + Assertions.assertEquals(2, array.size()); + Assertions.assertEquals(-1, array.indexOf(5)); + Assertions.assertEquals(-1, array.indexOf(-4)); + Assertions.assertEquals(-1, array.indexOf(70)); + Assertions.assertEquals(0, array.indexOf(25)); + Assertions.assertEquals(1, array.indexOf(-1)); + } - @Test - void getElementsTest() { + @Test + void getElementsTest() { - var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - Assertions.assertEquals(25, array.get(2)); - Assertions.assertEquals(5, array.first()); - Assertions.assertEquals(70, array.last()); + Assertions.assertEquals(25, array.get(2)); + Assertions.assertEquals(5, array.first()); + Assertions.assertEquals(70, array.last()); - array.clear(); + array.clear(); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> array.get(2)); - Assertions.assertThrows(IllegalStateException.class, array::first); - Assertions.assertThrows(IllegalStateException.class, array::last); - } + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> array.get(2)); + Assertions.assertThrows(IllegalStateException.class, array::first); + Assertions.assertThrows(IllegalStateException.class, array::last); + } - @Test - void sortTest() { + @Test + void sortTest() { - var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - array.sort(); + var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + array.sort(); - Assertions.assertEquals(-4, array.first()); - Assertions.assertEquals(70, array.last()); - Assertions.assertEquals(IntegerArray.of(-4, -1, 5, 25, 70), array); - } + Assertions.assertEquals(-4, array.first()); + Assertions.assertEquals(70, array.last()); + Assertions.assertEquals(IntegerArray.of(-4, -1, 5, 25, 70), array); + } - @Test - void equalsTest() { + @Test + void equalsTest() { - var first = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - var second = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + var first = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + var second = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - Assertions.assertEquals(first, second); + Assertions.assertEquals(first, second); - first.add(14); - second.add(14); + first.add(14); + second.add(14); - Assertions.assertEquals(first, second); + Assertions.assertEquals(first, second); - first.add(33); - second.add(33); + first.add(33); + second.add(33); - Assertions.assertEquals(first, second); + Assertions.assertEquals(first, second); - first.add(55); - second.add(45); + first.add(55); + second.add(45); - Assertions.assertNotEquals(first, second); + Assertions.assertNotEquals(first, second); - first.pop(); - second.pop(); + first.pop(); + second.pop(); - Assertions.assertEquals(first, second); + Assertions.assertEquals(first, second); - first.removeByIndex(0); - second.removeByIndex(0); + first.removeByIndex(0); + second.removeByIndex(0); - Assertions.assertEquals(first, second); - } + Assertions.assertEquals(first, second); + } - @Test - void toArrayTest() { + @Test + void toArrayTest() { - var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toIntArray(5, -4, 25, -1, 70), array.toArray()); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.toArray(new int[0]) - ); + Assertions.assertArrayEquals(ArrayFactory.toIntArray(5, -4, 25, -1, 70), array.toArray(new int[0])); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.toArray(new int[array.size()]) - ); - } + Assertions.assertArrayEquals(ArrayFactory.toIntArray(5, -4, 25, -1, 70), array.toArray(new int[array.size()])); + } - @Test - void streamTest() { + @Test + void streamTest() { - var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.stream().toArray() - ); - } + Assertions.assertArrayEquals( + ArrayFactory.toIntArray(5, -4, 25, -1, 70), + array + .stream() + .toArray()); + } - @Test - void forEachTest() { + @Test + void forEachTest() { - var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); - var toCollect = ArrayFactory.newMutableIntegerArray(); + var array = ArrayFactory.newMutableIntegerArray(5, -4, 25, -1, 70); + var toCollect = ArrayFactory.newMutableIntegerArray(); - array.forEachInt(toCollect::add); + array.forEachInt(toCollect::add); - Assertions.assertEquals(toCollect, array); + Assertions.assertEquals(toCollect, array); - array = ArrayFactory.newMutableIntegerArray(); - array.add(5); - array.add(-4); - array.add(25); - array.add(-1); - array.add(70); + array = ArrayFactory.newMutableIntegerArray(); + array.add(5); + array.add(-4); + array.add(25); + array.add(-1); + array.add(70); - var toCollect2 = ArrayFactory.newMutableIntegerArray(); + var toCollect2 = ArrayFactory.newMutableIntegerArray(); - array.forEachInt(toCollect2::add); + array.forEachInt(toCollect2::add); - Assertions.assertEquals(toCollect2, array); - } + Assertions.assertEquals(toCollect2, array); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/FastArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/FastArrayTest.java index 4aac6c3b..94b40d49 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/FastArrayTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/array/FastArrayTest.java @@ -8,19 +8,19 @@ */ public class FastArrayTest { - @Test - void equalsTest() { + @Test + void equalsTest() { - var integerArray = ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4); - var stringArray = ArrayFactory.asArray("third", "first", "fifth"); + var integerArray = ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4); + var stringArray = ArrayFactory.asArray("third", "first", "fifth"); - Assertions.assertEquals(ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4), integerArray); - Assertions.assertNotEquals(ArrayFactory.asArray(2, 5, 1, 2, 6, 8, 4), integerArray); + Assertions.assertEquals(ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4), integerArray); + Assertions.assertNotEquals(ArrayFactory.asArray(2, 5, 1, 2, 6, 8, 4), integerArray); - Assertions.assertEquals(ArrayFactory.asArray("third", "first", "fifth"), stringArray); - Assertions.assertNotEquals(ArrayFactory.asArray("third", "first", "fi2fth"), stringArray); + Assertions.assertEquals(ArrayFactory.asArray("third", "first", "fifth"), stringArray); + Assertions.assertNotEquals(ArrayFactory.asArray("third", "first", "fi2fth"), stringArray); - Assertions.assertEquals(ArrayFactory.newArray(String.class), ArrayFactory.newArray(String.class)); - Assertions.assertEquals(Array.empty(), ArrayFactory.newArray(String.class)); - } + Assertions.assertEquals(ArrayFactory.newArray(String.class), ArrayFactory.newArray(String.class)); + Assertions.assertEquals(Array.empty(), ArrayFactory.newArray(String.class)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ReadOnlyIntegerArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ReadOnlyIntegerArrayTest.java index 47d11571..0601594e 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ReadOnlyIntegerArrayTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ReadOnlyIntegerArrayTest.java @@ -5,72 +5,64 @@ public class ReadOnlyIntegerArrayTest { - @Test - void getElementsTest() { + @Test + void getElementsTest() { - var array = IntegerArray.of(5, -4, 25, -1, 70); + var array = IntegerArray.of(5, -4, 25, -1, 70); - Assertions.assertEquals(25, array.get(2)); - Assertions.assertEquals(5, array.first()); - Assertions.assertEquals(70, array.last()); + Assertions.assertEquals(25, array.get(2)); + Assertions.assertEquals(5, array.first()); + Assertions.assertEquals(70, array.last()); - var empty = IntegerArray.EMPTY; + var empty = IntegerArray.EMPTY; - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> empty.get(2)); - Assertions.assertThrows(IllegalStateException.class, empty::first); - Assertions.assertThrows(IllegalStateException.class, empty::last); - } + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> empty.get(2)); + Assertions.assertThrows(IllegalStateException.class, empty::first); + Assertions.assertThrows(IllegalStateException.class, empty::last); + } - @Test - void equalsTest() { + @Test + void equalsTest() { - var first = IntegerArray.of(5, -4, 25, -1, 70); - var second = IntegerArray.of(5, -4, 25, -1, 70); + var first = IntegerArray.of(5, -4, 25, -1, 70); + var second = IntegerArray.of(5, -4, 25, -1, 70); - Assertions.assertEquals(first, second); - Assertions.assertNotEquals(IntegerArray.of(5, -4, 4, -1, 70), second); - } + Assertions.assertEquals(first, second); + Assertions.assertNotEquals(IntegerArray.of(5, -4, 4, -1, 70), second); + } - @Test - void toArrayTest() { + @Test + void toArrayTest() { - var array = IntegerArray.of(5, -4, 25, -1, 70); + var array = IntegerArray.of(5, -4, 25, -1, 70); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.toArray() - ); + Assertions.assertArrayEquals(ArrayFactory.toIntArray(5, -4, 25, -1, 70), array.toArray()); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.toArray(new int[0]) - ); + Assertions.assertArrayEquals(ArrayFactory.toIntArray(5, -4, 25, -1, 70), array.toArray(new int[0])); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.toArray(new int[array.size()]) - ); - } + Assertions.assertArrayEquals(ArrayFactory.toIntArray(5, -4, 25, -1, 70), array.toArray(new int[array.size()])); + } - @Test - void streamTest() { + @Test + void streamTest() { - var array = IntegerArray.of(5, -4, 25, -1, 70); + var array = IntegerArray.of(5, -4, 25, -1, 70); - Assertions.assertArrayEquals( - ArrayFactory.toIntArray(5, -4, 25, -1, 70), - array.stream().toArray() - ); - } + Assertions.assertArrayEquals( + ArrayFactory.toIntArray(5, -4, 25, -1, 70), + array + .stream() + .toArray()); + } - @Test - void forEachTest() { + @Test + void forEachTest() { - var array = IntegerArray.of(5, -4, 25, -1, 70); - var toCollect = ArrayFactory.newMutableIntegerArray(); + var array = IntegerArray.of(5, -4, 25, -1, 70); + var toCollect = ArrayFactory.newMutableIntegerArray(); - array.forEachInt(toCollect::add); + array.forEachInt(toCollect::add); - Assertions.assertEquals(toCollect, array); - } + Assertions.assertEquals(toCollect, array); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionaryTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionaryTest.java index fadc0492..b5324a3c 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionaryTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionaryTest.java @@ -6,119 +6,114 @@ public class ConcurrentObjectDictionaryTest extends BaseTest { - @Test - void runInWriteLockTest() { + @Test + void runInWriteLockTest() { - var dictionary = ConcurrentObjectDictionary.ofType( - String.class, - Integer.class - ); + var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - Assertions.assertEquals(0, dictionary.size()); + Assertions.assertEquals(0, dictionary.size()); - dictionary.runInWriteLock(dic -> { - dic.put("1", 1); - dic.put("2", 2); - dic.put("3", 3); - }); + dictionary.runInWriteLock(dic -> { + dic.put("1", 1); + dic.put("2", 2); + dic.put("3", 3); + }); - Assertions.assertEquals(3, dictionary.size()); + Assertions.assertEquals(3, dictionary.size()); - dictionary.runInWriteLock("4", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - dic.put(arg, Integer.valueOf(arg)); + dictionary.runInWriteLock( + "4", (dic, arg) -> { + assertType(dic, ConcurrentObjectDictionary.class); + assertType(arg, String.class); + dic.put(arg, Integer.valueOf(arg)); }); - Assertions.assertEquals(4, dictionary.size()); + Assertions.assertEquals(4, dictionary.size()); - dictionary.runInWriteLock("5", 5, ObjectDictionary::put); + dictionary.runInWriteLock("5", 5, ObjectDictionary::put); - Assertions.assertEquals(5, dictionary.size()); + Assertions.assertEquals(5, dictionary.size()); - dictionary.runInWriteLock("6", 6, (dic, arg1, arg2) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg1, String.class); - assertType(arg2, Integer.class); + dictionary.runInWriteLock( + "6", 6, (dic, arg1, arg2) -> { + assertType(dic, ConcurrentObjectDictionary.class); + assertType(arg1, String.class); + assertType(arg2, Integer.class); }); - } + } - @Test - void runInReadLockTest() { + @Test + void runInReadLockTest() { - var dictionary = ConcurrentObjectDictionary.ofType( - String.class, - Integer.class - ); + var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - dictionary.runInReadLock("4", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - dic.get(arg); + dictionary.runInReadLock( + "4", (dic, arg) -> { + assertType(dic, ConcurrentObjectDictionary.class); + assertType(arg, String.class); + dic.get(arg); }); - } + } - @Test - void getInWriteLockTest() { + @Test + void getInWriteLockTest() { - var dictionary = ConcurrentObjectDictionary.ofType( - String.class, - Integer.class - ); + var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - dictionary.runInWriteLock(dic -> { - dic.put("1", 1); - dic.put("2", 2); - dic.put("3", 3); - }); + dictionary.runInWriteLock(dic -> { + dic.put("1", 1); + dic.put("2", 2); + dic.put("3", 3); + }); - Integer val1 = dictionary.getInWriteLock("1", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - return dic.get(arg); + Integer val1 = dictionary.getInWriteLock( + "1", (dic, arg) -> { + assertType(dic, ConcurrentObjectDictionary.class); + assertType(arg, String.class); + return dic.get(arg); }); - Assertions.assertEquals(1, val1); + Assertions.assertEquals(1, val1); - Integer val2 = dictionary.getInWriteLock("2", Type1.EXAMPLE, (dic, arg1, arg2) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg1, String.class); - assertType(arg2, Type1.class); - return dic.get(arg1); + Integer val2 = dictionary.getInWriteLock( + "2", Type1.EXAMPLE, (dic, arg1, arg2) -> { + assertType(dic, ConcurrentObjectDictionary.class); + assertType(arg1, String.class); + assertType(arg2, Type1.class); + return dic.get(arg1); }); - Assertions.assertEquals(2, val2); - } + Assertions.assertEquals(2, val2); + } - @Test - void getInReadLockTest() { + @Test + void getInReadLockTest() { - var dictionary = ConcurrentObjectDictionary.ofType( - String.class, - Integer.class - ); + var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - dictionary.runInWriteLock(dic -> { - dic.put("1", 1); - dic.put("2", 2); - dic.put("3", 3); - }); + dictionary.runInWriteLock(dic -> { + dic.put("1", 1); + dic.put("2", 2); + dic.put("3", 3); + }); - Integer val1 = dictionary.getInReadLock("1", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - return dic.get(arg); + Integer val1 = dictionary.getInReadLock( + "1", (dic, arg) -> { + assertType(dic, ConcurrentObjectDictionary.class); + assertType(arg, String.class); + return dic.get(arg); }); - Assertions.assertEquals(1, val1); + Assertions.assertEquals(1, val1); - Integer val2 = dictionary.getInReadLock("2", Type1.EXAMPLE, (dic, arg1, arg2) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg1, String.class); - assertType(arg2, Type1.class); - return dic.get(arg1); + Integer val2 = dictionary.getInReadLock( + "2", Type1.EXAMPLE, (dic, arg1, arg2) -> { + assertType(dic, ConcurrentObjectDictionary.class); + assertType(arg1, String.class); + assertType(arg2, Type1.class); + return dic.get(arg1); }); - Assertions.assertEquals(2, val2); - } + Assertions.assertEquals(2, val2); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionaryTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionaryTest.java index adce2518..06ee1fcf 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionaryTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionaryTest.java @@ -11,70 +11,70 @@ */ public class ConcurrentStampedLockObjectDictionaryTest { - @Test - void writeLockTest() { + @Test + void writeLockTest() { - var dictionary = DictionaryFactory.newConcurrentStampedLockObjectDictionary(); - dictionary.runInWriteLock(dic -> { - dic.put("Key1", 1); - dic.put("Key2", 2); - dic.put("Key3", 3); - dic.put("Key4", 4); - }); + var dictionary = DictionaryFactory.newConcurrentStampedLockObjectDictionary(); + dictionary.runInWriteLock(dic -> { + dic.put("Key1", 1); + dic.put("Key2", 2); + dic.put("Key3", 3); + dic.put("Key4", 4); + }); - long stamp = dictionary.writeLock(); + long stamp = dictionary.writeLock(); - Assertions.assertNotEquals(0, stamp); + Assertions.assertNotEquals(0, stamp); - var pendingWrite = CompletableFuture.runAsync(() -> dictionary.runInWriteLock(dic -> dic.put("Key5", 5))); + var pendingWrite = CompletableFuture.runAsync(() -> dictionary.runInWriteLock(dic -> dic.put("Key5", 5))); - Utils.tryGet(() -> pendingWrite.get(10, TimeUnit.MILLISECONDS)); + Utils.tryGet(() -> pendingWrite.get(10, TimeUnit.MILLISECONDS)); - Assertions.assertEquals(4, dictionary.size()); + Assertions.assertEquals(4, dictionary.size()); - dictionary.writeUnlock(stamp); + dictionary.writeUnlock(stamp); - pendingWrite.join(); + pendingWrite.join(); - Assertions.assertEquals(5, dictionary.size()); + Assertions.assertEquals(5, dictionary.size()); - stamp = dictionary.readLock(); + stamp = dictionary.readLock(); - Assertions.assertNotEquals(0, stamp); + Assertions.assertNotEquals(0, stamp); - var pendingWrite2 = CompletableFuture.runAsync(() -> dictionary.runInWriteLock(dic -> dic.put("Key6", 6))); + var pendingWrite2 = CompletableFuture.runAsync(() -> dictionary.runInWriteLock(dic -> dic.put("Key6", 6))); - Utils.tryGet(() -> pendingWrite2.get(10, TimeUnit.MILLISECONDS)); + Utils.tryGet(() -> pendingWrite2.get(10, TimeUnit.MILLISECONDS)); - Assertions.assertEquals(5, dictionary.size()); + Assertions.assertEquals(5, dictionary.size()); - dictionary.readUnlock(stamp); + dictionary.readUnlock(stamp); - pendingWrite2.join(); + pendingWrite2.join(); - Assertions.assertEquals(6, dictionary.size()); - } + Assertions.assertEquals(6, dictionary.size()); + } - @Test - void writeReadLockTest() { + @Test + void writeReadLockTest() { - var dictionary = DictionaryFactory.newConcurrentStampedLockObjectDictionary(); - dictionary.runInWriteLock(dic -> { - dic.put("Key1", 1); - dic.put("Key2", 2); - dic.put("Key3", 3); - dic.put("Key4", 4); - }); + var dictionary = DictionaryFactory.newConcurrentStampedLockObjectDictionary(); + dictionary.runInWriteLock(dic -> { + dic.put("Key1", 1); + dic.put("Key2", 2); + dic.put("Key3", 3); + dic.put("Key4", 4); + }); - long stamp = dictionary.readLock(); + long stamp = dictionary.readLock(); - Assertions.assertNotEquals(0, stamp); + Assertions.assertNotEquals(0, stamp); - var asyncRead = CompletableFuture.supplyAsync(() -> dictionary.getInReadLock("Key1", ObjectDictionary::get)); - var result = Utils.uncheckedGet(() -> asyncRead.get(100, TimeUnit.MILLISECONDS)); + var asyncRead = CompletableFuture.supplyAsync(() -> dictionary.getInReadLock("Key1", ObjectDictionary::get)); + var result = Utils.uncheckedGet(() -> asyncRead.get(100, TimeUnit.MILLISECONDS)); - Assertions.assertEquals(dictionary.get("Key1"), result); + Assertions.assertEquals(dictionary.get("Key1"), result); - dictionary.readUnlock(stamp); - } + dictionary.readUnlock(stamp); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/FastLongDictionaryTests.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/FastLongDictionaryTests.java index 3e1f2e42..29e38577 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/FastLongDictionaryTests.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/FastLongDictionaryTests.java @@ -16,62 +16,63 @@ */ public class FastLongDictionaryTests { - @Test - void generalTest() { + @Test + void generalTest() { - var dictionary = DictionaryFactory.newLongDictionary(); - dictionary.put(5, "5"); - dictionary.put(6, "6"); + var dictionary = DictionaryFactory.newLongDictionary(); + dictionary.put(5, "5"); + dictionary.put(6, "6"); - assertEquals(2, dictionary.size()); + assertEquals(2, dictionary.size()); - dictionary.put(7, "7"); + dictionary.put(7, "7"); - assertEquals(3, dictionary.size()); - assertEquals("7", dictionary.get(7)); + assertEquals(3, dictionary.size()); + assertEquals("7", dictionary.get(7)); - assertEquals("8", dictionary.getOrCompute(8, () -> "8")); - assertEquals("9", dictionary.getOrCompute(9, key -> "9")); + assertEquals("8", dictionary.getOrCompute(8, () -> "8")); + assertEquals("9", dictionary.getOrCompute(9, key -> "9")); - assertEquals(5, dictionary.size()); + assertEquals(5, dictionary.size()); - assertEquals("8", dictionary.remove(8)); + assertEquals("8", dictionary.remove(8)); - assertEquals(4, dictionary.size()); - } + assertEquals(4, dictionary.size()); + } - @Test - void emptyDictionaryTest() { + @Test + void emptyDictionaryTest() { - var emptyDictionary = LongDictionary.empty(); + var emptyDictionary = LongDictionary.empty(); - assertThrows(IllegalStateException.class, () -> emptyDictionary.put(1, "1")); - assertThrows(IllegalStateException.class, () -> emptyDictionary.remove(1)); - assertThrows(IllegalStateException.class, () -> emptyDictionary.put(newLongDictionary())); - assertThrows(IllegalStateException.class, emptyDictionary::clear); - } + assertThrows(IllegalStateException.class, () -> emptyDictionary.put(1, "1")); + assertThrows(IllegalStateException.class, () -> emptyDictionary.remove(1)); + assertThrows(IllegalStateException.class, () -> emptyDictionary.put(newLongDictionary())); + assertThrows(IllegalStateException.class, emptyDictionary::clear); + } - @Test - void dictionaryOfTest() { + @Test + void dictionaryOfTest() { - var dictionary = LongDictionary.of(1, "val1", 2, "val2", 3, "val3"); + var dictionary = LongDictionary.of(1, "val1", 2, "val2", 3, "val3"); - assertEquals(3, dictionary.size()); - assertEquals("val1", dictionary.get(1)); - assertEquals("val3", dictionary.get(3)); + assertEquals(3, dictionary.size()); + assertEquals("val1", dictionary.get(1)); + assertEquals("val3", dictionary.get(3)); - assertThrows(IllegalArgumentException.class, () -> LongDictionary.of("Key1", 1, "Key2", 2, "Key3")); - assertThrows(IllegalArgumentException.class, () -> LongDictionary.of("Key1")); - } + assertThrows(IllegalArgumentException.class, () -> LongDictionary.of("Key1", 1, "Key2", 2, "Key3")); + assertThrows(IllegalArgumentException.class, () -> LongDictionary.of("Key1")); + } - @Test - void collectorTest() { + @Test + void collectorTest() { - var dictionary = List.of(1, 2, 3, 4, 5) - .stream() - .collect(toLongDictionary(Function.identity(), Function.identity())); + var dictionary = List + .of(1, 2, 3, 4, 5) + .stream() + .collect(toLongDictionary(Function.identity(), Function.identity())); - assertEquals(5, dictionary.size()); - assertEquals(3, (int) dictionary.get(3)); - } + assertEquals(5, dictionary.size()); + assertEquals(3, (int) dictionary.get(3)); + } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryTest.java index c1c7803e..e08c1694 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryTest.java @@ -10,55 +10,49 @@ */ public class ObjectDictionaryTest { - @Test - void generalTest() { + @Test + void generalTest() { - var dictionary = DictionaryFactory.newObjectDictionary(); - dictionary.put("Key5", 5); - dictionary.put("Key6", 6); + var dictionary = DictionaryFactory.newObjectDictionary(); + dictionary.put("Key5", 5); + dictionary.put("Key6", 6); - Assertions.assertEquals(2, dictionary.size()); + Assertions.assertEquals(2, dictionary.size()); - dictionary.put("Key7", 7); + dictionary.put("Key7", 7); - Assertions.assertEquals(3, dictionary.size()); - Assertions.assertEquals(7, (int) dictionary.get("Key7")); + Assertions.assertEquals(3, dictionary.size()); + Assertions.assertEquals(7, (int) dictionary.get("Key7")); - Assertions.assertEquals(8, (int) dictionary.getOrCompute("Key8", () -> 8)); - Assertions.assertEquals(9, (int) dictionary.getOrCompute("Key9", key -> 9)); + Assertions.assertEquals(8, (int) dictionary.getOrCompute("Key8", () -> 8)); + Assertions.assertEquals(9, (int) dictionary.getOrCompute("Key9", key -> 9)); - Assertions.assertEquals(5, dictionary.size()); + Assertions.assertEquals(5, dictionary.size()); - Assertions.assertEquals(8, (int) dictionary.remove("Key8")); + Assertions.assertEquals(8, (int) dictionary.remove("Key8")); - Assertions.assertEquals(4, dictionary.size()); - } + Assertions.assertEquals(4, dictionary.size()); + } - @Test - void dictionaryOfTest() { + @Test + void dictionaryOfTest() { - var dictionary = ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3", 3); + var dictionary = ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3", 3); - Assertions.assertEquals(3, dictionary.size()); + Assertions.assertEquals(3, dictionary.size()); - Assertions.assertThrows( - IllegalArgumentException.class, - () -> ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3") - ); + Assertions.assertThrows(IllegalArgumentException.class, () -> ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3")); - Assertions.assertThrows( - IllegalArgumentException.class, - () -> ObjectDictionary.of("Key1") - ); - } + Assertions.assertThrows(IllegalArgumentException.class, () -> ObjectDictionary.of("Key1")); + } - @Test - void getOrDefaultTest() { + @Test + void getOrDefaultTest() { - var dictionary = ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3", 3); + var dictionary = ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3", 3); - Assertions.assertEquals(1, dictionary.get("Key1")); - Assertions.assertNull(dictionary.get("Key10")); - Assertions.assertEquals(10, dictionary.getOrDefault("Key10", 10)); - } + Assertions.assertEquals(1, dictionary.get("Key1")); + Assertions.assertNull(dictionary.get("Key10")); + Assertions.assertEquals(10, dictionary.getOrDefault("Key10", 10)); + } } diff --git a/rlib-common/src/test/resources/java/source/TestCompileJavaSource.java b/rlib-common/src/test/resources/java/source/TestCompileJavaSource.java index e47e64f1..97de166b 100644 --- a/rlib-common/src/test/resources/java/source/TestCompileJavaSource.java +++ b/rlib-common/src/test/resources/java/source/TestCompileJavaSource.java @@ -1,5 +1,5 @@ public class TestCompileJavaSource { - public String makeString() { - return "testString"; - } + public String makeString() { + return "testString"; + } } \ No newline at end of file diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/CssClasses.java b/rlib-fx/src/main/java/javasabr/rlib/fx/CssClasses.java index a3f98180..3b9bf04a 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/CssClasses.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/CssClasses.java @@ -5,16 +5,16 @@ */ public interface CssClasses { - String CSS_FILE = "/com/ss/rlib/fx/css/classes.css"; + String CSS_FILE = "/com/ss/rlib/fx/css/classes.css"; - String SIMPLE_POPUP_DIALOG = "simple-popup-dialog"; - String CONTROL_DIALOG = "control-dialog"; + String SIMPLE_POPUP_DIALOG = "simple-popup-dialog"; + String CONTROL_DIALOG = "control-dialog"; - String DIALOG_HEADER = "dialog-header"; - String DIALOG_CONTENT = "dialog-content"; - String DIALOG_ACTIONS = "dialog-actions"; - String DIALOG_TITLE = "dialog-title"; + String DIALOG_HEADER = "dialog-header"; + String DIALOG_CONTENT = "dialog-content"; + String DIALOG_ACTIONS = "dialog-actions"; + String DIALOG_TITLE = "dialog-title"; - String BUTTON_CLOSE = "button-close"; - String BUTTON_ACTION = "button-action"; + String BUTTON_CLOSE = "button-close"; + String BUTTON_ACTION = "button-action"; } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/LoggerClass.java b/rlib-fx/src/main/java/javasabr/rlib/fx/LoggerClass.java index 178d22c7..0cb8c36b 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/LoggerClass.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/LoggerClass.java @@ -3,5 +3,4 @@ /** * @author JavaSaBr */ -public interface LoggerClass { -} +public interface LoggerClass {} diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java index 19be2c60..6c570a1b 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java @@ -23,262 +23,264 @@ */ public abstract class ControlDialog extends VBox { - /** - * The dialog's header. - */ - @NotNull - protected final H header; - - /** - * The dialog's content container. - */ - @NotNull - protected final C container; - - /** - * The dialog's actions container. - */ - @NotNull - protected final A actions; - - /** - * The owner dialog. - */ - @Nullable - private ControlDialog ownerDialog; - - /** - * The flat about that this dialog was full constructed. - */ - private volatile boolean ready; - - private final BooleanProperty showing; - - protected ControlDialog() { - this.showing = new SimpleBooleanProperty(this, "showing", false); - this.header = createHeader(); - this.container = createContainer(); - this.actions = createActions(); + /** + * The dialog's header. + */ + @NotNull + protected final H header; + + /** + * The dialog's content container. + */ + @NotNull + protected final C container; + + /** + * The dialog's actions container. + */ + @NotNull + protected final A actions; + + /** + * The owner dialog. + */ + @Nullable + private ControlDialog ownerDialog; + + /** + * The flat about that this dialog was full constructed. + */ + private volatile boolean ready; + + private final BooleanProperty showing; + + protected ControlDialog() { + this.showing = new SimpleBooleanProperty(this, "showing", false); + this.header = createHeader(); + this.container = createContainer(); + this.actions = createActions(); + } + + /** + * Get the showing property. + * + * @return the showing property. + */ + public @NotNull BooleanProperty showingProperty() { + return showing; + } + + /** + * Create a header container. + * + * @return the header container. + */ + protected abstract @NotNull H createHeader(); + + /** + * Create a content container. + * + * @return the content container. + */ + protected abstract @NotNull C createContainer(); + + /** + * Create an actions container. + * + * @return the actions container. + */ + protected abstract @NotNull A createActions(); + + /** + * Construct content of this dialog after constructor. + */ + public void postConstruct() { + + if (ready) { + return; } - /** - * Get the showing property. - * - * @return the showing property. - */ - public @NotNull BooleanProperty showingProperty() { - return showing; + configure(); + fillHeader(header); + fillContent(container); + fillActions(actions); + + ready = true; + } + + /** + * Apply the size to this dialog. + * + * @param size the new size. + */ + public void applySize(@NotNull Point2D size) { + applySize(size.getX(), size.getY()); + } + + /** + * Apply the size to this dialog. + * + * @param width the new width. + * @param height the new height. + */ + public void applySize(double width, double height) { + setPrefWidth(width); + setPrefHeight(height); + } + + /** + * Configure this dialog. + */ + protected void configure() { + + if (getPrefHeight() == USE_COMPUTED_SIZE) { + setPrefHeight(100); } - /** - * Create a header container. - * - * @return the header container. - */ - protected abstract @NotNull H createHeader(); - - /** - * Create a content container. - * - * @return the content container. - */ - protected abstract @NotNull C createContainer(); - - /** - * Create an actions container. - * - * @return the actions container. - */ - protected abstract @NotNull A createActions(); - - /** - * Construct content of this dialog after constructor. - */ - public void postConstruct() { - - if (ready) { - return; - } - - configure(); - fillHeader(header); - fillContent(container); - fillActions(actions); - - ready = true; + if (getPrefWidth() == USE_COMPUTED_SIZE) { + setPrefWidth(100); } - /** - * Apply the size to this dialog. - * - * @param size the new size. - */ - public void applySize(@NotNull Point2D size) { - applySize(size.getX(), size.getY()); - } - - /** - * Apply the size to this dialog. - * - * @param width the new width. - * @param height the new height. - */ - public void applySize(double width, double height) { - setPrefWidth(width); - setPrefHeight(height); - } - - /** - * Configure this dialog. - */ - protected void configure() { - - if (getPrefHeight() == USE_COMPUTED_SIZE) { - setPrefHeight(100); - } - - if (getPrefWidth() == USE_COMPUTED_SIZE) { - setPrefWidth(100); - } - - header.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> toFront()); - - if (canDrag()) { - ControlDragHandler.install(this, header); - } - - if (canResize()) { - ControlResizeHandler.install(this); - } - - FxUtils.addChild(this, - header, container, actions); - } - - /** - * Return true if this dialog can be resized. - * - * @return true if this dialog can be resized. - */ - protected boolean canResize() { - return true; - } - - /** - * Return true if this dialog can be dragged. - * - * @return true if this dialog can be dragged. - */ - protected boolean canDrag() { - return true; - } - - /** - * Fill header of this dialog. - * - * @param header the header container. - */ - protected void fillHeader(@NotNull H header) { + header.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> toFront()); + if (canDrag()) { + ControlDragHandler.install(this, header); } - /** - * Fill content of this dialog. - * - * @param content the content's container. - */ - protected void fillContent(@NotNull C content) { - + if (canResize()) { + ControlResizeHandler.install(this); } - /** - * Fill actions of this dialog. - * - * @param actions the actions. - */ - protected void fillActions(@NotNull A actions) { - + FxUtils.addChild(this, header, container, actions); + } + + /** + * Return true if this dialog can be resized. + * + * @return true if this dialog can be resized. + */ + protected boolean canResize() { + return true; + } + + /** + * Return true if this dialog can be dragged. + * + * @return true if this dialog can be dragged. + */ + protected boolean canDrag() { + return true; + } + + /** + * Fill header of this dialog. + * + * @param header the header container. + */ + protected void fillHeader(@NotNull H header) { + + } + + /** + * Fill content of this dialog. + * + * @param content the content's container. + */ + protected void fillContent(@NotNull C content) { + + } + + /** + * Fill actions of this dialog. + * + * @param actions the actions. + */ + protected void fillActions(@NotNull A actions) { + + } + + /** + * Show this dialog over the node. + * + * @param node the node. + */ + public void show(@NotNull Node node) { + + var parent = node.getParent(); + var bounds = node.getBoundsInParent(); + var scene = node.getScene(); + var inScene = parent.localToScene( + bounds.getMinX() + bounds.getWidth() / 2, + bounds.getMinY() + bounds.getHeight() / 2); + + var prefHeight = max(max(getWidth(), getMinWidth()), getPrefHeight()) / 2; + var prefWidth = max(max(getHeight(), getMinHeight()), getPrefWidth()) / 2; + + show(scene, inScene.getX() - prefWidth, inScene.getY() - prefHeight); + } + + /** + * Show this dialog on the scene. + * + * @param scene the scene. + */ + public void show(@NotNull Scene scene) { + + var prefHeight = max(max(getWidth(), getMinWidth()), getPrefHeight()) / 2; + var prefWidth = max(max(getHeight(), getMinHeight()), getPrefWidth()) / 2; + + show(scene, (scene.getWidth() / 2) - prefWidth, (scene.getHeight() / 2) - prefHeight); + } + + /** + * Show this dialog on the scene by the coords. + * + * @param scene the scene. + * @param x the X coord. + * @param y the Y coord. + */ + public void show(@NotNull Scene scene, double x, double y) { + + if (showing.get()) { + return; } - /** - * Show this dialog over the node. - * - * @param node the node. - */ - public void show(@NotNull Node node) { + postConstruct(); - var parent = node.getParent(); - var bounds = node.getBoundsInParent(); - var scene = node.getScene(); - var inScene = parent.localToScene(bounds.getMinX() + bounds.getWidth() / 2, - bounds.getMinY() + bounds.getHeight() / 2); + ControlDialogSupport + .getDialogsLayer(scene) + .getChildren() + .add(this); - var prefHeight = max(max(getWidth(), getMinWidth()), getPrefHeight()) / 2; - var prefWidth = max(max(getHeight(), getMinHeight()), getPrefWidth()) / 2; + setTranslateX(x); + setTranslateY(y); - show(scene, inScene.getX() - prefWidth, inScene.getY() - prefHeight); + if (ownerDialog != null) { + ownerDialog.setDisabled(true); } - /** - * Show this dialog on the scene. - * - * @param scene the scene. - */ - public void show(@NotNull Scene scene) { + showing.setValue(true); + } - var prefHeight = max(max(getWidth(), getMinWidth()), getPrefHeight()) / 2; - var prefWidth = max(max(getHeight(), getMinHeight()), getPrefWidth()) / 2; + /** + * Hide this dialog. + */ + public void hide() { - show(scene, (scene.getWidth() / 2) - prefWidth, (scene.getHeight() / 2) - prefHeight); + if (!showing.get()) { + return; } - /** - * Show this dialog on the scene by the coords. - * - * @param scene the scene. - * @param x the X coord. - * @param y the Y coord. - */ - public void show(@NotNull Scene scene, double x, double y) { - - if (showing.get()) { - return; - } - - postConstruct(); - - ControlDialogSupport.getDialogsLayer(scene) - .getChildren() - .add(this); + ControlDialogSupport + .getDialogsLayer(getScene()) + .getChildren() + .remove(this); - setTranslateX(x); - setTranslateY(y); - - if (ownerDialog != null) { - ownerDialog.setDisabled(true); - } - - showing.setValue(true); + if (ownerDialog != null) { + ownerDialog.setDisabled(false); + ownerDialog = null; } - /** - * Hide this dialog. - */ - public void hide() { - - if (!showing.get()) { - return; - } - - ControlDialogSupport.getDialogsLayer(getScene()) - .getChildren() - .remove(this); - - if (ownerDialog != null) { - ownerDialog.setDisabled(false); - ownerDialog = null; - } - - showing.setValue(false); - } + showing.setValue(false); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialogSupport.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialogSupport.java index d4c77550..a627dba2 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialogSupport.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialogSupport.java @@ -12,46 +12,50 @@ */ public class ControlDialogSupport { - private static final String DIALOGS_LAYER = "ControlDialogSupport.dialogsLayer"; - - /** - * Add supporting {@link ControlDialog} in the scene. - * - * @param scene the scene. - */ - public static void addSupport(@NotNull Scene scene) { - - var dialogsLayer = new Pane(); - dialogsLayer.setPickOnBounds(false); - dialogsLayer.prefWidthProperty() - .bind(scene.widthProperty()); - dialogsLayer.prefHeightProperty() - .bind(scene.heightProperty()); - - var wrapper = new StackPane(scene.getRoot(), dialogsLayer); - - scene.getProperties() - .put(DIALOGS_LAYER, dialogsLayer); - - scene.setRoot(wrapper); + private static final String DIALOGS_LAYER = "ControlDialogSupport.dialogsLayer"; + + /** + * Add supporting {@link ControlDialog} in the scene. + * + * @param scene the scene. + */ + public static void addSupport(@NotNull Scene scene) { + + var dialogsLayer = new Pane(); + dialogsLayer.setPickOnBounds(false); + dialogsLayer + .prefWidthProperty() + .bind(scene.widthProperty()); + dialogsLayer + .prefHeightProperty() + .bind(scene.heightProperty()); + + var wrapper = new StackPane(scene.getRoot(), dialogsLayer); + + scene + .getProperties() + .put(DIALOGS_LAYER, dialogsLayer); + + scene.setRoot(wrapper); + } + + /** + * Get dialogs layer on the scene. + * + * @param scene the scene. + * @return the dialogs layer. + */ + static @NotNull Pane getDialogsLayer(@NotNull Scene scene) { + + var layer = (Pane) scene + .getProperties() + .get(DIALOGS_LAYER); + + if (layer == null) { + throw new IllegalStateException("The scene " + scene + " doesn't support control dialogs, " + + "please apply #addSupport(scene) method to your scene to add supporting control dialogs."); } - /** - * Get dialogs layer on the scene. - * - * @param scene the scene. - * @return the dialogs layer. - */ - static @NotNull Pane getDialogsLayer(@NotNull Scene scene) { - - var layer = (Pane) scene.getProperties() - .get(DIALOGS_LAYER); - - if (layer == null) { - throw new IllegalStateException("The scene " + scene + " doesn't support control dialogs, " + - "please apply #addSupport(scene) method to your scene to add supporting control dialogs."); - } - - return layer; - } + return layer; + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/DefaultControlDialog.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/DefaultControlDialog.java index 4588b52a..ed86cc7d 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/DefaultControlDialog.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/DefaultControlDialog.java @@ -14,74 +14,78 @@ */ public class DefaultControlDialog extends ControlDialog { - @NotNull - protected final Label titleLabel; + @NotNull + protected final Label titleLabel; - @NotNull - protected final Button closeButton; + @NotNull + protected final Button closeButton; - public DefaultControlDialog() { - this.titleLabel = new Label("No title"); - this.closeButton = createCloseButton(); - } + public DefaultControlDialog() { + this.titleLabel = new Label("No title"); + this.closeButton = createCloseButton(); + } - protected @NotNull Button createCloseButton() { - return new Button("X"); - } + protected @NotNull Button createCloseButton() { + return new Button("X"); + } - @Override - protected @NotNull GridPane createHeader() { - return new GridPane(); - } + @Override + protected @NotNull GridPane createHeader() { + return new GridPane(); + } - @Override - protected @NotNull GridPane createContainer() { - return new GridPane(); - } + @Override + protected @NotNull GridPane createContainer() { + return new GridPane(); + } - @Override - protected @NotNull GridPane createActions() { - return new GridPane(); - } + @Override + protected @NotNull GridPane createActions() { + return new GridPane(); + } - @Override - protected void configure() { - super.configure(); + @Override + protected void configure() { + super.configure(); - container.prefHeightProperty() - .bind(heightProperty()); + container + .prefHeightProperty() + .bind(heightProperty()); - closeButton.setOnAction(event -> hide()); + closeButton.setOnAction(event -> hide()); - FxUtils.addClass(this, CssClasses.CONTROL_DIALOG) - .addClass(header, CssClasses.DIALOG_HEADER) - .addClass(container, CssClasses.DIALOG_CONTENT) - .addClass(actions, CssClasses.DIALOG_ACTIONS); - } + FxUtils + .addClass(this, CssClasses.CONTROL_DIALOG) + .addClass(header, CssClasses.DIALOG_HEADER) + .addClass(container, CssClasses.DIALOG_CONTENT) + .addClass(actions, CssClasses.DIALOG_ACTIONS); + } - @Override - protected void fillHeader(@NotNull GridPane header) { - super.fillHeader(header); + @Override + protected void fillHeader(@NotNull GridPane header) { + super.fillHeader(header); - titleLabel.prefWidthProperty() - .bind(header.widthProperty()); + titleLabel + .prefWidthProperty() + .bind(header.widthProperty()); - FxUtils.addClass(titleLabel, CssClasses.DIALOG_TITLE) - .addClass(closeButton, CssClasses.BUTTON_CLOSE); + FxUtils + .addClass(titleLabel, CssClasses.DIALOG_TITLE) + .addClass(closeButton, CssClasses.BUTTON_CLOSE); - header.add(titleLabel, 0, 0); - header.add(closeButton, 1, 0); - } + header.add(titleLabel, 0, 0); + header.add(closeButton, 1, 0); + } - @Override - protected void fillContent(@NotNull GridPane content) { + @Override + protected void fillContent(@NotNull GridPane content) { - super.fillContent(content); - } + super.fillContent(content); + } - @Override - protected void fillActions(@NotNull GridPane actions) { + @Override + protected void fillActions(@NotNull GridPane actions) { - super.fillActions(actions); - } + super.fillActions(actions); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java index 6b4d56ce..f0976735 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java @@ -10,8 +10,8 @@ */ public final class FloatArrayTextField extends TypedTextField { - @Override - protected @NotNull FloatArrayStringConverter createValueConverter() { - return new FloatArrayStringConverter(); - } + @Override + protected @NotNull FloatArrayStringConverter createValueConverter() { + return new FloatArrayStringConverter(); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java index 54207d24..10f02556 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java @@ -12,47 +12,47 @@ */ public final class FloatTextField extends NumberTextField { - public FloatTextField() { - setValue(0F); - } - - @Override - protected @NotNull LimitedNumberStringConverter createValueConverter() { - return new LimitedFloatStringConverter(); - } + public FloatTextField() { + setValue(0F); + } - @Override - protected void scrollValueImpl(@NotNull ScrollEvent event) { - super.scrollValueImpl(event); + @Override + protected @NotNull LimitedNumberStringConverter createValueConverter() { + return new LimitedFloatStringConverter(); + } - var value = getValue(); + @Override + protected void scrollValueImpl(@NotNull ScrollEvent event) { + super.scrollValueImpl(event); - var longValue = (long) (value * 1000); - longValue += event.getDeltaY() * (getScrollPower() * (event.isShiftDown() ? 0.5F : 1F)); + var value = getValue(); - var resultValue = longValue / 1000F; - var stringValue = String.valueOf(resultValue); + var longValue = (long) (value * 1000); + longValue += event.getDeltaY() * (getScrollPower() * (event.isShiftDown() ? 0.5F : 1F)); - var textFormatter = getTextFormatter(); - var valueConverter = textFormatter.getValueConverter(); - try { - valueConverter.fromString(stringValue); - } catch (RuntimeException e) { - return; - } + var resultValue = longValue / 1000F; + var stringValue = String.valueOf(resultValue); - setText(stringValue); - positionCaret(stringValue.length()); + var textFormatter = getTextFormatter(); + var valueConverter = textFormatter.getValueConverter(); + try { + valueConverter.fromString(stringValue); + } catch (RuntimeException e) { + return; } - /** - * Gets a primitive current value. - * - * @return the current value or 0. - */ - public float getPrimitiveValue() { - var textFormatter = getTypedTextFormatter(); - var value = textFormatter.getValue(); - return value == null ? 0F : value; - } + setText(stringValue); + positionCaret(stringValue.length()); + } + + /** + * Gets a primitive current value. + * + * @return the current value or 0. + */ + public float getPrimitiveValue() { + var textFormatter = getTypedTextFormatter(); + var value = textFormatter.getValue(); + return value == null ? 0F : value; + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java index 22ef1a13..479b30d1 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java @@ -10,8 +10,8 @@ */ public final class IntegerArrayTextField extends TypedTextField { - @Override - protected @NotNull IntegerArrayStringConverter createValueConverter() { - return new IntegerArrayStringConverter(); - } + @Override + protected @NotNull IntegerArrayStringConverter createValueConverter() { + return new IntegerArrayStringConverter(); + } } \ No newline at end of file diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java index 7978bec0..ca9a6970 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java @@ -12,49 +12,48 @@ */ public final class IntegerTextField extends NumberTextField { - public IntegerTextField() { - setValue(0); - } - - @Override - protected @NotNull LimitedNumberStringConverter createValueConverter() { - return new LimitedIntegerStringConverter(); - } + public IntegerTextField() { + setValue(0); + } - @Override - protected void scrollValueImpl(@NotNull ScrollEvent event) { - super.scrollValueImpl(event); + @Override + protected @NotNull LimitedNumberStringConverter createValueConverter() { + return new LimitedIntegerStringConverter(); + } - var value = getValue(); + @Override + protected void scrollValueImpl(@NotNull ScrollEvent event) { + super.scrollValueImpl(event); - var longValue = (long) (value * 1000); - longValue += event.getDeltaY() * (getScrollPower() * (event.isShiftDown() ? 0.5F : 1F)); + var value = getValue(); - var resultValue = (int) (longValue / 1000F); - var stringValue = String.valueOf(resultValue); + var longValue = (long) (value * 1000); + longValue += event.getDeltaY() * (getScrollPower() * (event.isShiftDown() ? 0.5F : 1F)); - var textFormatter = getTextFormatter(); - var valueConverter = textFormatter.getValueConverter(); - try { - valueConverter.fromString(stringValue); - } catch (final RuntimeException e) { - return; - } + var resultValue = (int) (longValue / 1000F); + var stringValue = String.valueOf(resultValue); - setText(stringValue); - positionCaret(stringValue.length()); + var textFormatter = getTextFormatter(); + var valueConverter = textFormatter.getValueConverter(); + try { + valueConverter.fromString(stringValue); + } catch (final RuntimeException e) { + return; } - /** - * Get the current primitive value. - * - * @return the current value or 0. - */ - public int getPrimitiveValue() { + setText(stringValue); + positionCaret(stringValue.length()); + } - var value = getTypedTextFormatter() - .getValue(); + /** + * Get the current primitive value. + * + * @return the current value or 0. + */ + public int getPrimitiveValue() { - return value == null ? 0 : value; - } + var value = getTypedTextFormatter().getValue(); + + return value == null ? 0 : value; + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java index d49adc86..6cdf3359 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java @@ -11,85 +11,80 @@ */ public abstract class NumberTextField extends ScrollableTypedTextField { - public NumberTextField() { - super(); - setScrollPower(30); - } - - public NumberTextField(@NotNull String text) { - super(text); - setScrollPower(30); - } - - @Override - protected @NotNull LimitedNumberStringConverter createValueConverter() { - throw new UnsupportedOperationException(); - } - - /** - * Set value limits for this field. - * - * @param min the min value. - * @param max the max value. - */ - public void setMinMax(@Nullable T min, @Nullable T max) { - - var converter = (LimitedNumberStringConverter) getTypedTextFormatter() - .getValueConverter(); - - converter.setMaxValue(max); - converter.setMinValue(min); - } - - /** - * Set the min value of this field. - * - * @param value the min value of this field. - */ - public void setMinValue(@Nullable T value) { - - var converter = (LimitedNumberStringConverter) getTypedTextFormatter() - .getValueConverter(); - - converter.setMinValue(value); - } - - /** - * Get a min value of this field. - * - * @return the min value of this field. - */ - public @Nullable T getMinValue() { - - var converter = (LimitedNumberStringConverter) getTypedTextFormatter() - .getValueConverter(); - - return converter.getMinValue(); - } - - /** - * Set the max value of this field. - * - * @param value the max value of this field. - */ - public void setMaxValue(@Nullable T value) { - - var converter = (LimitedNumberStringConverter) getTypedTextFormatter() - .getValueConverter(); - - converter.setMaxValue(value); - } - - /** - * Get a max value of this field. - * - * @return the min value of this field. - */ - public @Nullable T getMaxValue() { - - var converter = (LimitedNumberStringConverter) getTypedTextFormatter() - .getValueConverter(); - - return converter.getMaxValue(); - } + public NumberTextField() { + super(); + setScrollPower(30); + } + + public NumberTextField(@NotNull String text) { + super(text); + setScrollPower(30); + } + + @Override + protected @NotNull LimitedNumberStringConverter createValueConverter() { + throw new UnsupportedOperationException(); + } + + /** + * Set value limits for this field. + * + * @param min the min value. + * @param max the max value. + */ + public void setMinMax(@Nullable T min, @Nullable T max) { + + var converter = (LimitedNumberStringConverter) getTypedTextFormatter().getValueConverter(); + + converter.setMaxValue(max); + converter.setMinValue(min); + } + + /** + * Set the min value of this field. + * + * @param value the min value of this field. + */ + public void setMinValue(@Nullable T value) { + + var converter = (LimitedNumberStringConverter) getTypedTextFormatter().getValueConverter(); + + converter.setMinValue(value); + } + + /** + * Get a min value of this field. + * + * @return the min value of this field. + */ + public @Nullable T getMinValue() { + + var converter = (LimitedNumberStringConverter) getTypedTextFormatter().getValueConverter(); + + return converter.getMinValue(); + } + + /** + * Set the max value of this field. + * + * @param value the max value of this field. + */ + public void setMaxValue(@Nullable T value) { + + var converter = (LimitedNumberStringConverter) getTypedTextFormatter().getValueConverter(); + + converter.setMaxValue(value); + } + + /** + * Get a max value of this field. + * + * @return the min value of this field. + */ + public @Nullable T getMaxValue() { + + var converter = (LimitedNumberStringConverter) getTypedTextFormatter().getValueConverter(); + + return converter.getMaxValue(); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java index d70b1726..341c5778 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java @@ -10,55 +10,55 @@ */ public class ScrollableTypedTextField extends TypedTextField { - /** - * The scroll power. - */ - private float scrollPower; + /** + * The scroll power. + */ + private float scrollPower; - public ScrollableTypedTextField() { - setOnScroll(this::scrollValue); - } + public ScrollableTypedTextField() { + setOnScroll(this::scrollValue); + } - public ScrollableTypedTextField(@NotNull String text) { - super(text); - setOnScroll(this::scrollValue); - } + public ScrollableTypedTextField(@NotNull String text) { + super(text); + setOnScroll(this::scrollValue); + } - /** - * Set the scroll power. - * - * @param scrollPower the scroll power. - */ - public void setScrollPower(float scrollPower) { - this.scrollPower = scrollPower; - } + /** + * Set the scroll power. + * + * @param scrollPower the scroll power. + */ + public void setScrollPower(float scrollPower) { + this.scrollPower = scrollPower; + } - /** - * Get the scroll power. - * - * @return the scroll power. - */ - public float getScrollPower() { - return scrollPower; - } + /** + * Get the scroll power. + * + * @return the scroll power. + */ + public float getScrollPower() { + return scrollPower; + } - /** - * Scroll the current value. - * - * @param event the scroll event. - */ - protected void scrollValue(@NotNull ScrollEvent event) { - if (event.isControlDown()) { - event.consume(); - scrollValueImpl(event); - } + /** + * Scroll the current value. + * + * @param event the scroll event. + */ + protected void scrollValue(@NotNull ScrollEvent event) { + if (event.isControlDown()) { + event.consume(); + scrollValueImpl(event); } + } - /** - * Scroll the current value. - * - * @param event the scroll event. - */ - protected void scrollValueImpl(@NotNull ScrollEvent event) { - } + /** + * Scroll the current value. + * + * @param event the scroll event. + */ + protected void scrollValueImpl(@NotNull ScrollEvent event) { + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java index 45db876b..e6e92d6a 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java @@ -17,68 +17,68 @@ */ public class TypedTextField extends TextField { - public TypedTextField() { - setTextFormatter(new TextFormatter<>(createValueConverter())); - } + public TypedTextField() { + setTextFormatter(new TextFormatter<>(createValueConverter())); + } - public TypedTextField(@NotNull String text) { - super(text); - setTextFormatter(new TextFormatter<>(createValueConverter())); - } + public TypedTextField(@NotNull String text) { + super(text); + setTextFormatter(new TextFormatter<>(createValueConverter())); + } - /** - * Create a new value converter. - * - * @return the new value converter. - */ - protected @NotNull StringConverter createValueConverter() { - throw new UnsupportedOperationException(); - } + /** + * Create a new value converter. + * + * @return the new value converter. + */ + protected @NotNull StringConverter createValueConverter() { + throw new UnsupportedOperationException(); + } - /** - * Add a new change listener. - * - * @param listener the change listener. - */ - public void addChangeListener(@NotNull ChangeListener listener) { - getTypedTextFormatter() - .valueProperty() - .addListener(listener); - } + /** + * Add a new change listener. + * + * @param listener the change listener. + */ + public void addChangeListener(@NotNull ChangeListener listener) { + getTypedTextFormatter() + .valueProperty() + .addListener(listener); + } - /** - * Get the typed text formatter. - * - * @return the typed text formatter. - */ - protected @NotNull TextFormatter getTypedTextFormatter() { - return unsafeCast(getTextFormatter()); - } + /** + * Get the typed text formatter. + * + * @return the typed text formatter. + */ + protected @NotNull TextFormatter getTypedTextFormatter() { + return unsafeCast(getTextFormatter()); + } - /** - * Get the value property. - * - * @return the value property. - */ - public @NotNull ReadOnlyObjectProperty valueProperty() { - return getTypedTextFormatter().valueProperty(); - } + /** + * Get the value property. + * + * @return the value property. + */ + public @NotNull ReadOnlyObjectProperty valueProperty() { + return getTypedTextFormatter().valueProperty(); + } - /** - * Get a current value. - * - * @return the current value. - */ - public @Nullable T getValue() { - return getTypedTextFormatter().getValue(); - } + /** + * Get a current value. + * + * @return the current value. + */ + public @Nullable T getValue() { + return getTypedTextFormatter().getValue(); + } - /** - * Set a new value. - * - * @param value the new value. - */ - public void setValue(@Nullable T value) { - getTypedTextFormatter().setValue(value); - } + /** + * Set a new value. + * + * @param value the new value. + */ + public void setValue(@Nullable T value) { + getTypedTextFormatter().setValue(value); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java index db845ee0..42216cf3 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java @@ -13,122 +13,123 @@ */ public abstract class AbstractPopupDialog extends Popup { - protected static final Point2D DEFAULT_DIALOG_SIZE = - new Point2D(500, 500); - - /** - * The dialog's root container. - */ - @NotNull - private final C container; - - /** - * The owner dialog. - */ - @Nullable - private AbstractPopupDialog ownerDialog; - - /** - * The flat about that this dialog was full constructed. - */ - private volatile boolean ready; - - public AbstractPopupDialog() { - container = createRoot(); - getContent().add(container); + protected static final Point2D DEFAULT_DIALOG_SIZE = new Point2D(500, 500); + + /** + * The dialog's root container. + */ + @NotNull + private final C container; + + /** + * The owner dialog. + */ + @Nullable + private AbstractPopupDialog ownerDialog; + + /** + * The flat about that this dialog was full constructed. + */ + private volatile boolean ready; + + public AbstractPopupDialog() { + container = createRoot(); + getContent().add(container); + } + + /** + * Create a root container of this dialog. + * + * @return the root container of this dialog. + */ + protected abstract @NotNull C createRoot(); + + /** + * Construct content of this dialog after constructor. + */ + public void postConstruct() { + + if (ready) { + return; } - /** - * Create a root container of this dialog. - * - * @return the root container of this dialog. - */ - protected abstract @NotNull C createRoot(); - - /** - * Construct content of this dialog after constructor. - */ - public void postConstruct() { - - if (ready) { - return; - } - - createControls(container); - configureSize(container, getSize()); - - ready = true; - } - - /** - * Configure a size of this dialog. - * - * @param container the root container. - * @param size the size. - */ - protected void configureSize(@NotNull C container, @NotNull Point2D size) { - } - - /** - * Create content of this dialog. - * - * @param root the root. - */ - protected void createControls(@NotNull C root) { - } - - /** - * Get the content container. - * - * @return the content container. - */ - protected @NotNull C getContainer() { - return container; - } - - /** - * Get the owner dialog. - * - * @return the owner dialog. - */ - protected @Nullable AbstractPopupDialog getOwnerDialog() { - return ownerDialog; - } - - /** - * Set the owner dialog. - * - * @param ownerDialog the owner dialog. - */ - protected void setOwnerDialog(@Nullable AbstractPopupDialog ownerDialog) { - this.ownerDialog = ownerDialog; + createControls(container); + configureSize(container, getSize()); + + ready = true; + } + + /** + * Configure a size of this dialog. + * + * @param container the root container. + * @param size the size. + */ + protected void configureSize(@NotNull C container, @NotNull Point2D size) { + } + + /** + * Create content of this dialog. + * + * @param root the root. + */ + protected void createControls(@NotNull C root) { + } + + /** + * Get the content container. + * + * @return the content container. + */ + protected @NotNull C getContainer() { + return container; + } + + /** + * Get the owner dialog. + * + * @return the owner dialog. + */ + protected @Nullable AbstractPopupDialog getOwnerDialog() { + return ownerDialog; + } + + /** + * Set the owner dialog. + * + * @param ownerDialog the owner dialog. + */ + protected void setOwnerDialog(@Nullable AbstractPopupDialog ownerDialog) { + this.ownerDialog = ownerDialog; + } + + /** + * Get the dialog size. + * + * @return the dialog size. + */ + protected @NotNull Point2D getSize() { + return DEFAULT_DIALOG_SIZE; + } + + @Override + protected void show() { + postConstruct(); + super.show(); + } + + @Override + public void hide() { + super.hide(); + + var dialog = getOwnerDialog(); + + if (dialog != null) { + dialog + .getContainer() + .setDisable(false); } - /** - * Get the dialog size. - * - * @return the dialog size. - */ - protected @NotNull Point2D getSize() { - return DEFAULT_DIALOG_SIZE; - } - - @Override - protected void show() { - postConstruct(); - super.show(); - } - - @Override - public void hide() { - super.hide(); - - var dialog = getOwnerDialog(); - - if (dialog != null) { - dialog.getContainer().setDisable(false); - } - - setOwnerDialog(null); - } + setOwnerDialog(null); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java index 84709c18..ee570b6f 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java @@ -16,85 +16,88 @@ */ public class SimplePopupDialog extends AbstractPopupDialog { - @NotNull - private final Label titleLabel; + @NotNull + private final Label titleLabel; - @NotNull - private final Button closeButton; + @NotNull + private final Button closeButton; - public SimplePopupDialog() { - this.titleLabel = new Label("Title"); - this.closeButton = new Button("X"); + public SimplePopupDialog() { + this.titleLabel = new Label("Title"); + this.closeButton = new Button("X"); - FxUtils.addClass(titleLabel, CssClasses.DIALOG_TITLE) - .addClass(closeButton, CssClasses.BUTTON_CLOSE); - } + FxUtils + .addClass(titleLabel, CssClasses.DIALOG_TITLE) + .addClass(closeButton, CssClasses.BUTTON_CLOSE); + } - @Override - protected @NotNull VBox createRoot() { - var root = new VBox(); - FxUtils.addClass(root, CssClasses.SIMPLE_POPUP_DIALOG); - return root; - } + @Override + protected @NotNull VBox createRoot() { + var root = new VBox(); + FxUtils.addClass(root, CssClasses.SIMPLE_POPUP_DIALOG); + return root; + } - @Override - protected void configureSize(@NotNull VBox container, @NotNull Point2D size) { - super.configureSize(container, size); - FxUtils.setFixedSize(container, size); - } + @Override + protected void configureSize(@NotNull VBox container, @NotNull Point2D size) { + super.configureSize(container, size); + FxUtils.setFixedSize(container, size); + } - @Override - protected void createControls(@NotNull VBox root) { - super.createControls(root); + @Override + protected void createControls(@NotNull VBox root) { + super.createControls(root); - var header = new GridPane(); - var content = new GridPane(); - var actions = new GridPane(); + var header = new GridPane(); + var content = new GridPane(); + var actions = new GridPane(); - WindowDragHandler.install(header); + WindowDragHandler.install(header); - fillHeader(header); - fillContent(content); - fillActions(actions); + fillHeader(header); + fillContent(content); + fillActions(actions); - FxUtils.addClass(header, CssClasses.DIALOG_HEADER) - .addClass(content, CssClasses.DIALOG_CONTENT) - .addClass(actions, CssClasses.DIALOG_ACTIONS); + FxUtils + .addClass(header, CssClasses.DIALOG_HEADER) + .addClass(content, CssClasses.DIALOG_CONTENT) + .addClass(actions, CssClasses.DIALOG_ACTIONS); - FxUtils.addChild(root, header, content, actions); - } + FxUtils.addChild(root, header, content, actions); + } - public void setTitle(@NotNull String title) { - this.titleLabel.setText(title); - } + public void setTitle(@NotNull String title) { + this.titleLabel.setText(title); + } - protected void fillHeader(@NotNull GridPane container) { + protected void fillHeader(@NotNull GridPane container) { - titleLabel.prefWidthProperty() - .bind(container.widthProperty()); + titleLabel + .prefWidthProperty() + .bind(container.widthProperty()); - var closeButton = new Button("X"); - closeButton.setOnAction(event -> hide()); + var closeButton = new Button("X"); + closeButton.setOnAction(event -> hide()); - FxUtils.addClass(closeButton, CssClasses.BUTTON_CLOSE); + FxUtils.addClass(closeButton, CssClasses.BUTTON_CLOSE); - container.add(titleLabel, 0, 0); - container.add(closeButton, 1, 0); - } + container.add(titleLabel, 0, 0); + container.add(closeButton, 1, 0); + } - protected void fillContent(@NotNull GridPane container) { + protected void fillContent(@NotNull GridPane container) { - var textArea = new TextArea(); + var textArea = new TextArea(); - container.add(textArea, 0, 0); - } + container.add(textArea, 0, 0); + } - protected void fillActions(@NotNull GridPane container) { + protected void fillActions(@NotNull GridPane container) { - var buttonYes = new Button("Yes"); - var buttonNo = new Button("No"); + var buttonYes = new Button("Yes"); + var buttonNo = new Button("No"); - container.add(buttonYes, 0,0); - container.add(buttonNo, 1, 0); - } + container.add(buttonYes, 0, 0); + container.add(buttonNo, 1, 0); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java index 69b5af33..5567f8ec 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java @@ -15,130 +15,129 @@ */ public class ControlDragHandler { - private static final Logger LOGGER = LoggerManager.getLogger(LoggerClass.class); - - /** - * Install the handler to the node. - * - * @param draggableNode the node which should be moved. - * @param draggableControl the node which should be like a handle. - */ - public static void install(@NotNull Node draggableNode, @NotNull Node draggableControl) { - new ControlDragHandler(draggableNode, draggableControl); + private static final Logger LOGGER = LoggerManager.getLogger(LoggerClass.class); + + /** + * Install the handler to the node. + * + * @param draggableNode the node which should be moved. + * @param draggableControl the node which should be like a handle. + */ + public static void install(@NotNull Node draggableNode, @NotNull Node draggableControl) { + new ControlDragHandler(draggableNode, draggableControl); + } + + /** + * The draggable node. + */ + @NotNull + private final Node draggableNode; + + /** + * The draggable control. + */ + @NotNull + private final Node draggableControl; + + /** + * The offset X coord. + */ + private double offsetX; + + /** + * The offset Y coord. + */ + private double offsetY; + + /** + * The started X coord. + */ + private double startX; + + /** + * The started Y coord. + */ + private double startY; + + public ControlDragHandler(@NotNull Node draggableNode, @NotNull Node draggableControl) { + this.draggableNode = draggableNode; + this.draggableControl = draggableControl; + this.draggableControl.setOnMousePressed(this::processStartDrag); + this.draggableControl.setOnMouseDragged(this::processMove); + this.draggableControl.setOnMouseReleased(this::processStopDrag); + } + + /** + * Handle moving. + * + * @param event the mouse event + */ + protected void processMove(@NotNull MouseEvent event) { + + LOGGER.debug(event, ev -> "processMove -> " + ev); + + if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { + LOGGER.debug("processMove -> dragOffset -> " + offsetX + "," + offsetY); } - /** - * The draggable node. - */ - @NotNull - private final Node draggableNode; - - /** - * The draggable control. - */ - @NotNull - private final Node draggableControl; - - /** - * The offset X coord. - */ - private double offsetX; - - /** - * The offset Y coord. - */ - private double offsetY; - - /** - * The started X coord. - */ - private double startX; - - /** - * The started Y coord. - */ - private double startY; - - public ControlDragHandler(@NotNull Node draggableNode, @NotNull Node draggableControl) { - this.draggableNode = draggableNode; - this.draggableControl = draggableControl; - this.draggableControl.setOnMousePressed(this::processStartDrag); - this.draggableControl.setOnMouseDragged(this::processMove); - this.draggableControl.setOnMouseReleased(this::processStopDrag); - } - - /** - * Handle moving. - * - * @param event the mouse event - */ - protected void processMove(@NotNull MouseEvent event) { - - LOGGER.debug(event, ev -> "processMove -> " + ev); - - if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { - LOGGER.debug("processMove -> dragOffset -> " + offsetX + "," + offsetY); - } - - var dragPosition = draggableNode.getParent() - .sceneToLocal(draggableControl.localToScene(event.getX(), event.getY())); + var dragPosition = draggableNode + .getParent() + .sceneToLocal(draggableControl.localToScene(event.getX(), event.getY())); - var dragX = dragPosition.getX() - offsetX; - var dragY = dragPosition.getY() - offsetY; + var dragX = dragPosition.getX() - offsetX; + var dragY = dragPosition.getY() - offsetY; - if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { - LOGGER.debug("processMove -> dragXY -> " + (dragX - offsetX) + "-" + (dragY - offsetY)); - } - - var newXPos = startX + dragX; - var newYPos = startY + dragY; + if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { + LOGGER.debug("processMove -> dragXY -> " + (dragX - offsetX) + "-" + (dragY - offsetY)); + } - if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { - LOGGER.debug("processMove -> newXY -> " + newXPos + ", " + newYPos); - } + var newXPos = startX + dragX; + var newYPos = startY + dragY; - draggableNode.setTranslateX(newXPos); - draggableNode.setTranslateY(newYPos); + if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { + LOGGER.debug("processMove -> newXY -> " + newXPos + ", " + newYPos); } - /** - * Handle starting moving. - * - * @param event the mouse event. - */ - protected void processStartDrag(@NotNull MouseEvent event) { + draggableNode.setTranslateX(newXPos); + draggableNode.setTranslateY(newYPos); + } - LOGGER.debug(event, - ev -> "processStartDrag -> " + ev); + /** + * Handle starting moving. + * + * @param event the mouse event. + */ + protected void processStartDrag(@NotNull MouseEvent event) { - startX = draggableNode.getTranslateX(); - startY = draggableNode.getTranslateY(); + LOGGER.debug(event, ev -> "processStartDrag -> " + ev); - LOGGER.debug(this, handler -> - "processStartDrag -> initXY -> " + handler.startX + ", " + handler.startY); + startX = draggableNode.getTranslateX(); + startY = draggableNode.getTranslateY(); - var offset = draggableNode.getParent() - .sceneToLocal(draggableControl.localToScene(event.getX(), event.getY())); + LOGGER.debug(this, handler -> "processStartDrag -> initXY -> " + handler.startX + ", " + handler.startY); - LOGGER.debug(offset, - point -> "processStartDrag -> dragOffset -> " + point); + var offset = draggableNode + .getParent() + .sceneToLocal(draggableControl.localToScene(event.getX(), event.getY())); - offsetX = offset.getX(); - offsetY = offset.getY(); - } + LOGGER.debug(offset, point -> "processStartDrag -> dragOffset -> " + point); - /** - * Handle finishing moving. - * - * @param event the event - */ - protected void processStopDrag(@NotNull MouseEvent event) { + offsetX = offset.getX(); + offsetY = offset.getY(); + } - startX = 0; - startY = 0; - offsetX = 0; - offsetY = 0; + /** + * Handle finishing moving. + * + * @param event the event + */ + protected void processStopDrag(@NotNull MouseEvent event) { - LOGGER.debug(event, ev -> "processStopDrag -> " + ev); - } + startX = 0; + startY = 0; + offsetX = 0; + offsetY = 0; + + LOGGER.debug(event, ev -> "processStopDrag -> " + ev); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java index 8a1d703c..b2cbbc6b 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java @@ -19,114 +19,114 @@ */ public class ControlResizeHandler implements EventHandler { - /** - * Install resize handler to the region. - * - * @param node the region. - */ - public static void install(@NotNull Region node) { - install(node, 4); + /** + * Install resize handler to the region. + * + * @param node the region. + */ + public static void install(@NotNull Region node) { + install(node, 4); + } + + /** + * Install resize handler to the region. + * + * @param node the region. + * @param borderWidth the border width. + */ + public static void install(@NotNull Region node, int borderWidth) { + + var handler = new ControlResizeHandler(node, borderWidth); + + node.addEventHandler(MOUSE_MOVED, handler); + node.addEventHandler(MOUSE_PRESSED, handler); + node.addEventHandler(MOUSE_DRAGGED, handler); + node.addEventHandler(MOUSE_EXITED, handler); + node.addEventHandler(MOUSE_EXITED_TARGET, handler); + } + + @NotNull + private final Region node; + + @NotNull + private Cursor cursor; + + private double startX; + private double startY; + + private int border; + + public ControlResizeHandler(@NotNull Region node, int borderWidth) { + this.node = node; + this.border = borderWidth; + this.startX = 0; + this.startY = 0; + this.cursor = Cursor.DEFAULT; + } + + @Override + public void handle(@NotNull MouseEvent mouseEvent) { + + var eventType = mouseEvent.getEventType(); + var eventX = mouseEvent.getX(); + var eventY = mouseEvent.getY(); + + var nodeWidth = node.getWidth(); + var nodeHeight = node.getHeight(); + + if (MOUSE_MOVED.equals(eventType)) { + handleMoving(eventX, eventY, nodeWidth, nodeHeight); + } else if (MOUSE_EXITED.equals(eventType) || MOUSE_EXITED_TARGET.equals(eventType)) { + node.setCursor(Cursor.DEFAULT); + } else if (MOUSE_PRESSED.equals(eventType)) { + startX = nodeWidth - eventX; + startY = nodeHeight - eventY; + } else if (MOUSE_DRAGGED.equals(eventType)) { + + if (Cursor.DEFAULT.equals(cursor)) { + return; + } else if (!Cursor.W_RESIZE.equals(cursor) && !Cursor.E_RESIZE.equals(cursor)) { + resizeHeight(eventY); + } + + if (!Cursor.N_RESIZE.equals(cursor) && !Cursor.S_RESIZE.equals(cursor)) { + resizeWidth(eventX); + } } + } - /** - * Install resize handler to the region. - * - * @param node the region. - * @param borderWidth the border width. - */ - public static void install(@NotNull Region node, int borderWidth) { - - var handler = new ControlResizeHandler(node, borderWidth); - - node.addEventHandler(MOUSE_MOVED, handler); - node.addEventHandler(MOUSE_PRESSED, handler); - node.addEventHandler(MOUSE_DRAGGED, handler); - node.addEventHandler(MOUSE_EXITED, handler); - node.addEventHandler(MOUSE_EXITED_TARGET, handler); - } - - @NotNull - private final Region node; - - @NotNull - private Cursor cursor; + private void resizeWidth(double eventX) { - private double startX; - private double startY; - - private int border; - - public ControlResizeHandler(@NotNull Region node, int borderWidth) { - this.node = node; - this.border = borderWidth; - this.startX = 0; - this.startY = 0; - this.cursor = Cursor.DEFAULT; - } + var minWidth = node.getMinWidth() > (border * 2) ? node.getMinWidth() : (border * 2); + var newWidth = eventX + startX; - @Override - public void handle(@NotNull MouseEvent mouseEvent) { - - var eventType = mouseEvent.getEventType(); - var eventX = mouseEvent.getX(); - var eventY = mouseEvent.getY(); - - var nodeWidth = node.getWidth(); - var nodeHeight = node.getHeight(); - - if (MOUSE_MOVED.equals(eventType)) { - handleMoving(eventX, eventY, nodeWidth, nodeHeight); - } else if (MOUSE_EXITED.equals(eventType) || MOUSE_EXITED_TARGET.equals(eventType)) { - node.setCursor(Cursor.DEFAULT); - } else if (MOUSE_PRESSED.equals(eventType)) { - startX = nodeWidth - eventX; - startY = nodeHeight - eventY; - } else if (MOUSE_DRAGGED.equals(eventType)) { - - if (Cursor.DEFAULT.equals(cursor)) { - return; - } else if (!Cursor.W_RESIZE.equals(cursor) && !Cursor.E_RESIZE.equals(cursor)) { - resizeHeight(eventY); - } - - if (!Cursor.N_RESIZE.equals(cursor) && !Cursor.S_RESIZE.equals(cursor)) { - resizeWidth(eventX); - } - } + if (node.getWidth() > minWidth || newWidth - node.getWidth() > 0) { + node.setPrefWidth(newWidth); } + } - private void resizeWidth(double eventX) { + private void resizeHeight(double eventY) { - var minWidth = node.getMinWidth() > (border * 2) ? node.getMinWidth() : (border * 2); - var newWidth = eventX + startX; + var minHeight = node.getMinHeight() > (border * 2) ? node.getMinHeight() : (border * 2); + var newHeight = eventY + startY; - if (node.getWidth() > minWidth || newWidth - node.getWidth() > 0) { - node.setPrefWidth(newWidth); - } + if (node.getHeight() > minHeight || newHeight - node.getHeight() > 0) { + node.setPrefHeight(newHeight); } - - private void resizeHeight(double eventY) { - - var minHeight = node.getMinHeight() > (border * 2) ? node.getMinHeight() : (border * 2); - var newHeight = eventY + startY; - - if (node.getHeight() > minHeight || newHeight - node.getHeight() > 0) { - node.setPrefHeight(newHeight); - } + } + + private void handleMoving(double eventX, double eventY, double nodeWidth, double nodeHeight) { + + if (eventX > nodeWidth - border && eventY > nodeHeight - border) { + cursor = Cursor.SE_RESIZE; + } else if (eventX > nodeWidth - border) { + cursor = Cursor.E_RESIZE; + } else if (eventY > nodeHeight - border) { + cursor = Cursor.S_RESIZE; + } else { + cursor = Cursor.DEFAULT; } - private void handleMoving(double eventX, double eventY, double nodeWidth, double nodeHeight) { - - if (eventX > nodeWidth - border && eventY > nodeHeight - border) { - cursor = Cursor.SE_RESIZE; - } else if (eventX > nodeWidth - border) { - cursor = Cursor.E_RESIZE; - } else if (eventY > nodeHeight - border) { - cursor = Cursor.S_RESIZE; - } else { - cursor = Cursor.DEFAULT; - } - - node.setCursor(cursor); - } + node.setCursor(cursor); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java index a11dd1ac..e1582ddb 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java @@ -17,184 +17,184 @@ */ public class WindowDragHandler { - private static final Logger LOGGER = LoggerManager.getLogger(LoggerClass.class); - - /** - * Install the handler to the node. - * - * @param node the node. - */ - public static void install(@NotNull Node node) { - new WindowDragHandler(node); + private static final Logger LOGGER = LoggerManager.getLogger(LoggerClass.class); + + /** + * Install the handler to the node. + * + * @param node the node. + */ + public static void install(@NotNull Node node) { + new WindowDragHandler(node); + } + + /** + * The node. + */ + @NotNull + private final Node node; + + /** + * The drag offset. + */ + @Nullable + private Point2D dragOffset; + + /** + * The started X coord. + */ + private double startX; + + /** + * The started Y coord. + */ + private double startY; + + public WindowDragHandler(@NotNull Node node) { + this.node = node; + this.node.setOnMousePressed(this::processStartDrag); + this.node.setOnMouseDragged(this::processMove); + this.node.setOnMouseReleased(this::processStopDrag); + } + + /** + * Get the drag offset. + * + * @return the drag offset. + */ + protected @Nullable Point2D getDragOffset() { + return dragOffset; + } + + /** + * Set the drag offset. + * + * @param dragOffset the drag offset. + */ + public void setDragOffset(@Nullable Point2D dragOffset) { + this.dragOffset = dragOffset; + } + + /** + * Get the start X coord. + * + * @return the start X coord. + */ + protected double getStartX() { + return startX; + } + + /** + * Set the start X coord. + * + * @param startX the start X coord. + */ + public void setStartX(double startX) { + this.startX = startX; + } + + /** + * Get start Y coord. + * + * @return the start Y coord. + */ + protected double getStartY() { + return startY; + } + + /** + * Set the start Y coord. + * + * @param startY the start Y coord. + */ + public void setStartY(double startY) { + this.startY = startY; + } + + /** + * Get the handled node. + * + * @return the handled node. + */ + public @NotNull Node getNode() { + return node; + } + + /** + * Handle moving. + * + * @param event the event + */ + protected void processMove(@NotNull MouseEvent event) { + + LOGGER.debug(event, ev -> "processMove -> " + ev); + + var node = getNode(); + var scene = node.getScene(); + var window = scene.getWindow(); + + var dragOffset = getDragOffset(); + if (dragOffset == null) { + LOGGER.debug("processMove -> dragOffset -> null"); + return; } - /** - * The node. - */ - @NotNull - private final Node node; - - /** - * The drag offset. - */ - @Nullable - private Point2D dragOffset; - - /** - * The started X coord. - */ - private double startX; - - /** - * The started Y coord. - */ - private double startY; - - public WindowDragHandler(@NotNull Node node) { - this.node = node; - this.node.setOnMousePressed(this::processStartDrag); - this.node.setOnMouseDragged(this::processMove); - this.node.setOnMouseReleased(this::processStopDrag); - } - - /** - * Get the drag offset. - * - * @return the drag offset. - */ - protected @Nullable Point2D getDragOffset() { - return dragOffset; - } + LOGGER.debug(dragOffset, offset -> "processMove -> dragOffset -> " + offset); - /** - * Set the drag offset. - * - * @param dragOffset the drag offset. - */ - public void setDragOffset(@Nullable Point2D dragOffset) { - this.dragOffset = dragOffset; - } + var dragX = event.getScreenX() - dragOffset.getX(); + var dragY = event.getScreenY() - dragOffset.getY(); - /** - * Get the start X coord. - * - * @return the start X coord. - */ - protected double getStartX() { - return startX; - } + LOGGER.debug( + dragOffset, + event, + (offset, ev) -> "processMove -> dragXY -> " + (ev.getScreenX() - offset.getX()) + "-" + (ev.getScreenY() + - offset.getY())); - /** - * Set the start X coord. - * - * @param startX the start X coord. - */ - public void setStartX(double startX) { - this.startX = startX; - } + var newXPos = startX + dragX; + var newYPos = startY + dragY; - /** - * Get start Y coord. - * - * @return the start Y coord. - */ - protected double getStartY() { - return startY; + if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { + LOGGER.debug("processMove -> newXY -> " + newXPos + ", " + newYPos); } - /** - * Set the start Y coord. - * - * @param startY the start Y coord. - */ - public void setStartY(double startY) { - this.startY = startY; - } - - /** - * Get the handled node. - * - * @return the handled node. - */ - public @NotNull Node getNode() { - return node; - } - - /** - * Handle moving. - * - * @param event the event - */ - protected void processMove(@NotNull MouseEvent event) { - - LOGGER.debug( event, ev -> "processMove -> " + ev); + window.setX(newXPos); + window.setY(newYPos); + } - var node = getNode(); - var scene = node.getScene(); - var window = scene.getWindow(); + /** + * Handle starting moving. + * + * @param event the event. + */ + protected void processStartDrag(@NotNull MouseEvent event) { - var dragOffset = getDragOffset(); - if (dragOffset == null) { - LOGGER.debug("processMove -> dragOffset -> null"); - return; - } + LOGGER.debug(event, ev -> "processStartDrag -> " + ev); - LOGGER.debug(dragOffset, offset -> "processMove -> dragOffset -> " + offset); + var node = getNode(); + var scene = node.getScene(); + var window = scene.getWindow(); - var dragX = event.getScreenX() - dragOffset.getX(); - var dragY = event.getScreenY() - dragOffset.getY(); + setStartX(window.getX()); + setStartY(window.getY()); - LOGGER.debug(dragOffset, event, (offset, ev) -> - "processMove -> dragXY -> " + (ev.getScreenX() - offset.getX()) + - "-" + (ev.getScreenY() - offset.getY())); + LOGGER.debug(this, handler -> "processStartDrag -> initXY -> " + handler.getStartX() + ", " + handler.getStartY()); - var newXPos = startX + dragX; - var newYPos = startY + dragY; + var dragOffset = new Point2D(event.getScreenX(), event.getScreenY()); - if (LOGGER.isEnabled(LoggerLevel.DEBUG)) { - LOGGER.debug("processMove -> newXY -> " + newXPos + ", " + newYPos); - } + LOGGER.debug(dragOffset, offset -> "processStartDrag -> dragOffset -> " + offset); - window.setX(newXPos); - window.setY(newYPos); - } - - /** - * Handle starting moving. - * - * @param event the event. - */ - protected void processStartDrag(@NotNull MouseEvent event) { - - LOGGER.debug(event, ev -> "processStartDrag -> " + ev); - - var node = getNode(); - var scene = node.getScene(); - var window = scene.getWindow(); - - setStartX(window.getX()); - setStartY(window.getY()); - - LOGGER.debug(this, handler -> - "processStartDrag -> initXY -> " + handler.getStartX() + ", " + handler.getStartY()); + setDragOffset(dragOffset); + } - var dragOffset = new Point2D(event.getScreenX(), event.getScreenY()); - - LOGGER.debug(dragOffset, - offset -> "processStartDrag -> dragOffset -> " + offset); - - setDragOffset(dragOffset); - } - - /** - * Handle finishing moving. - * - * @param event the event - */ - protected void processStopDrag(@NotNull MouseEvent event) { - LOGGER.debug(event, ev -> "processStopDrag -> " + ev); - setStartX(0); - setStartY(0); - setDragOffset(null); - } + /** + * Handle finishing moving. + * + * @param event the event + */ + protected void processStopDrag(@NotNull MouseEvent event) { + LOGGER.debug(event, ev -> "processStopDrag -> " + ev); + setStartX(0); + setStartY(0); + setDragOffset(null); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java index 1500ce7d..cb2b0807 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java @@ -20,131 +20,131 @@ */ public class WindowResizeHandler implements EventHandler { - /** - * Install the resize handler. - * - * @param stage the stage. - * @param nodes the nodes. - */ - public static void install(@NotNull Stage stage, @NotNull Node... nodes) { - - var handler = new WindowResizeHandler(stage); - var scene = stage.getScene(); - scene.addEventHandler(MOUSE_MOVED, handler); - scene.addEventHandler(MOUSE_PRESSED, handler); - scene.addEventHandler(MOUSE_DRAGGED, handler); - scene.addEventHandler(MOUSE_EXITED, handler); - scene.addEventHandler(MOUSE_EXITED_TARGET, handler); - - addHandler(scene.getRoot(), handler); - - for (var node : nodes) { - addHandler(node, handler); - } - } - - private static void addHandler(@NotNull Node node, @NotNull EventHandler listener) { - node.addEventHandler(MOUSE_MOVED, listener); - node.addEventHandler(MOUSE_PRESSED, listener); - node.addEventHandler(MOUSE_DRAGGED, listener); - node.addEventHandler(MOUSE_EXITED, listener); - node.addEventHandler(MOUSE_EXITED_TARGET, listener); + /** + * Install the resize handler. + * + * @param stage the stage. + * @param nodes the nodes. + */ + public static void install(@NotNull Stage stage, @NotNull Node... nodes) { + + var handler = new WindowResizeHandler(stage); + var scene = stage.getScene(); + scene.addEventHandler(MOUSE_MOVED, handler); + scene.addEventHandler(MOUSE_PRESSED, handler); + scene.addEventHandler(MOUSE_DRAGGED, handler); + scene.addEventHandler(MOUSE_EXITED, handler); + scene.addEventHandler(MOUSE_EXITED_TARGET, handler); + + addHandler(scene.getRoot(), handler); + + for (var node : nodes) { + addHandler(node, handler); } - - @NotNull - private final Stage stage; - - @NotNull - private Cursor cursorEvent; - - private double startX; - private double startY; - - private int border; - - public WindowResizeHandler(@NotNull Stage stage) { - this.stage = stage; - this.border = 4; - this.startX = 0; - this.startY = 0; - this.cursorEvent = Cursor.DEFAULT; - } - - @Override - public void handle(@NotNull MouseEvent mouseEvent) { - - var mouseEventType = mouseEvent.getEventType(); - var scene = stage.getScene(); - - var mouseEventX = mouseEvent.getSceneX(); - var mouseEventY = mouseEvent.getSceneY(); - var sceneWidth = scene.getWidth(); - var sceneHeight = scene.getHeight(); - - if (MOUSE_MOVED.equals(mouseEventType)) { - - if (mouseEventX < border && mouseEventY < border) { - cursorEvent = Cursor.NW_RESIZE; - } else if (mouseEventX < border && mouseEventY > sceneHeight - border) { - cursorEvent = Cursor.SW_RESIZE; - } else if (mouseEventX > sceneWidth - border && mouseEventY < border) { - cursorEvent = Cursor.NE_RESIZE; - } else if (mouseEventX > sceneWidth - border && mouseEventY > sceneHeight - border) { - cursorEvent = Cursor.SE_RESIZE; - } else if (mouseEventX < border) { - cursorEvent = Cursor.W_RESIZE; - } else if (mouseEventX > sceneWidth - border) { - cursorEvent = Cursor.E_RESIZE; - } else if (mouseEventY < border) { - cursorEvent = Cursor.N_RESIZE; - } else if (mouseEventY > sceneHeight - border) { - cursorEvent = Cursor.S_RESIZE; - } else { - cursorEvent = Cursor.DEFAULT; - } - - scene.setCursor(cursorEvent); - - } else if (MOUSE_EXITED.equals(mouseEventType) || MOUSE_EXITED_TARGET.equals(mouseEventType)) { - scene.setCursor(Cursor.DEFAULT); - } else if (MOUSE_PRESSED.equals(mouseEventType)) { - startX = stage.getWidth() - mouseEventX; - startY = stage.getHeight() - mouseEventY; - } else if (MOUSE_DRAGGED.equals(mouseEventType)) { - - if (Cursor.DEFAULT.equals(cursorEvent)) { - return; - } - - if (!Cursor.W_RESIZE.equals(cursorEvent) && !Cursor.E_RESIZE.equals(cursorEvent)) { - double minHeight = stage.getMinHeight() > (border * 2) ? stage.getMinHeight() : (border * 2); - if (Cursor.NW_RESIZE.equals(cursorEvent) || Cursor.N_RESIZE.equals(cursorEvent) || - Cursor.NE_RESIZE.equals(cursorEvent)) { - if (stage.getHeight() > minHeight || mouseEventY < 0) { - stage.setHeight(stage.getY() - mouseEvent.getScreenY() + stage.getHeight()); - stage.setY(mouseEvent.getScreenY()); - } - } else { - if (stage.getHeight() > minHeight || mouseEventY + startY - stage.getHeight() > 0) { - stage.setHeight(mouseEventY + startY); - } - } - } - - if (!Cursor.N_RESIZE.equals(cursorEvent) && !Cursor.S_RESIZE.equals(cursorEvent)) { - double minWidth = stage.getMinWidth() > (border * 2) ? stage.getMinWidth() : (border * 2); - if (Cursor.NW_RESIZE.equals(cursorEvent) || Cursor.W_RESIZE.equals(cursorEvent) || - Cursor.SW_RESIZE.equals(cursorEvent)) { - if (stage.getWidth() > minWidth || mouseEventX < 0) { - stage.setWidth(stage.getX() - mouseEvent.getScreenX() + stage.getWidth()); - stage.setX(mouseEvent.getScreenX()); - } - } else { - if (stage.getWidth() > minWidth || mouseEventX + startX - stage.getWidth() > 0) { - stage.setWidth(mouseEventX + startX); - } - } - } + } + + private static void addHandler(@NotNull Node node, @NotNull EventHandler listener) { + node.addEventHandler(MOUSE_MOVED, listener); + node.addEventHandler(MOUSE_PRESSED, listener); + node.addEventHandler(MOUSE_DRAGGED, listener); + node.addEventHandler(MOUSE_EXITED, listener); + node.addEventHandler(MOUSE_EXITED_TARGET, listener); + } + + @NotNull + private final Stage stage; + + @NotNull + private Cursor cursorEvent; + + private double startX; + private double startY; + + private int border; + + public WindowResizeHandler(@NotNull Stage stage) { + this.stage = stage; + this.border = 4; + this.startX = 0; + this.startY = 0; + this.cursorEvent = Cursor.DEFAULT; + } + + @Override + public void handle(@NotNull MouseEvent mouseEvent) { + + var mouseEventType = mouseEvent.getEventType(); + var scene = stage.getScene(); + + var mouseEventX = mouseEvent.getSceneX(); + var mouseEventY = mouseEvent.getSceneY(); + var sceneWidth = scene.getWidth(); + var sceneHeight = scene.getHeight(); + + if (MOUSE_MOVED.equals(mouseEventType)) { + + if (mouseEventX < border && mouseEventY < border) { + cursorEvent = Cursor.NW_RESIZE; + } else if (mouseEventX < border && mouseEventY > sceneHeight - border) { + cursorEvent = Cursor.SW_RESIZE; + } else if (mouseEventX > sceneWidth - border && mouseEventY < border) { + cursorEvent = Cursor.NE_RESIZE; + } else if (mouseEventX > sceneWidth - border && mouseEventY > sceneHeight - border) { + cursorEvent = Cursor.SE_RESIZE; + } else if (mouseEventX < border) { + cursorEvent = Cursor.W_RESIZE; + } else if (mouseEventX > sceneWidth - border) { + cursorEvent = Cursor.E_RESIZE; + } else if (mouseEventY < border) { + cursorEvent = Cursor.N_RESIZE; + } else if (mouseEventY > sceneHeight - border) { + cursorEvent = Cursor.S_RESIZE; + } else { + cursorEvent = Cursor.DEFAULT; + } + + scene.setCursor(cursorEvent); + + } else if (MOUSE_EXITED.equals(mouseEventType) || MOUSE_EXITED_TARGET.equals(mouseEventType)) { + scene.setCursor(Cursor.DEFAULT); + } else if (MOUSE_PRESSED.equals(mouseEventType)) { + startX = stage.getWidth() - mouseEventX; + startY = stage.getHeight() - mouseEventY; + } else if (MOUSE_DRAGGED.equals(mouseEventType)) { + + if (Cursor.DEFAULT.equals(cursorEvent)) { + return; + } + + if (!Cursor.W_RESIZE.equals(cursorEvent) && !Cursor.E_RESIZE.equals(cursorEvent)) { + double minHeight = stage.getMinHeight() > (border * 2) ? stage.getMinHeight() : (border * 2); + if (Cursor.NW_RESIZE.equals(cursorEvent) || Cursor.N_RESIZE.equals(cursorEvent) || Cursor.NE_RESIZE.equals( + cursorEvent)) { + if (stage.getHeight() > minHeight || mouseEventY < 0) { + stage.setHeight(stage.getY() - mouseEvent.getScreenY() + stage.getHeight()); + stage.setY(mouseEvent.getScreenY()); + } + } else { + if (stage.getHeight() > minHeight || mouseEventY + startY - stage.getHeight() > 0) { + stage.setHeight(mouseEventY + startY); + } + } + } + + if (!Cursor.N_RESIZE.equals(cursorEvent) && !Cursor.S_RESIZE.equals(cursorEvent)) { + double minWidth = stage.getMinWidth() > (border * 2) ? stage.getMinWidth() : (border * 2); + if (Cursor.NW_RESIZE.equals(cursorEvent) || Cursor.W_RESIZE.equals(cursorEvent) || Cursor.SW_RESIZE.equals( + cursorEvent)) { + if (stage.getWidth() > minWidth || mouseEventX < 0) { + stage.setWidth(stage.getX() - mouseEvent.getScreenX() + stage.getWidth()); + stage.setX(mouseEvent.getScreenX()); + } + } else { + if (stage.getWidth() > minWidth || mouseEventX + startX - stage.getWidth() > 0) { + stage.setWidth(mouseEventX + startX); + } } + } } + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/impl/DraggablePanel.java b/rlib-fx/src/main/java/javasabr/rlib/fx/impl/DraggablePanel.java index f3ca1b0c..0be0269e 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/impl/DraggablePanel.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/impl/DraggablePanel.java @@ -13,124 +13,124 @@ */ public class DraggablePanel extends VBox { - /** - * The drag offset. - */ - @Nullable - private Point2D dragOffset; - - /** - * The start X coord. - */ - private double startX; - - /** - * The start Y coord. - */ - private double startY; - - public DraggablePanel() { - setOnMousePressed(this::processStartDrag); - setOnMouseDragged(this::processMove); - setOnMouseReleased(this::processStopDrag); + /** + * The drag offset. + */ + @Nullable + private Point2D dragOffset; + + /** + * The start X coord. + */ + private double startX; + + /** + * The start Y coord. + */ + private double startY; + + public DraggablePanel() { + setOnMousePressed(this::processStartDrag); + setOnMouseDragged(this::processMove); + setOnMouseReleased(this::processStopDrag); + } + + /** + * Get the drag offset. + * + * @return the drag offset. + */ + protected @Nullable Point2D getDragOffset() { + return dragOffset; + } + + /** + * Set the drag offset. + * + * @param dragOffset the drag offset. + */ + public void setDragOffset(@Nullable final Point2D dragOffset) { + this.dragOffset = dragOffset; + } + + /** + * Get the start X coord. + * + * @return the start X coord. + */ + protected double getStartX() { + return startX; + } + + /** + * Set the start X coord. + * + * @param startX the start X coord. + */ + public void setStartX(final double startX) { + this.startX = startX; + } + + /** + * Get the start Y coord. + * + * @return the start Y coord. + */ + protected double getStartY() { + return startY; + } + + /** + * Set the start Y coord. + * + * @param startY the start Y coord. + */ + public void setStartY(final double startY) { + this.startY = startY; + } + + /** + * Handle moving. + * + * @param event the mouse event. + */ + protected void processMove(@NotNull final MouseEvent event) { + + final Point2D dragOffset = getDragOffset(); + if (dragOffset == null) { + return; } - /** - * Get the drag offset. - * - * @return the drag offset. - */ - protected @Nullable Point2D getDragOffset() { - return dragOffset; - } - - /** - * Set the drag offset. - * - * @param dragOffset the drag offset. - */ - public void setDragOffset(@Nullable final Point2D dragOffset) { - this.dragOffset = dragOffset; - } - - /** - * Get the start X coord. - * - * @return the start X coord. - */ - protected double getStartX() { - return startX; - } - - /** - * Set the start X coord. - * - * @param startX the start X coord. - */ - public void setStartX(final double startX) { - this.startX = startX; - } - - /** - * Get the start Y coord. - * - * @return the start Y coord. - */ - protected double getStartY() { - return startY; - } - - /** - * Set the start Y coord. - * - * @param startY the start Y coord. - */ - public void setStartY(final double startY) { - this.startY = startY; - } - - /** - * Handle moving. - * - * @param event the mouse event. - */ - protected void processMove(@NotNull final MouseEvent event) { - - final Point2D dragOffset = getDragOffset(); - if (dragOffset == null) { - return; - } - - final double dragX = event.getSceneX() - dragOffset.getX(); - final double dragY = event.getSceneY() - getDragOffset().getY(); - - final double newXPosition = startX + dragX; - final double newYPosition = startY + dragY; - - setTranslateX(newXPosition); - setTranslateY(newYPosition); - } - - /** - * Handle starting of dragging. - * - * @param event the mouse event. - */ - protected void processStartDrag(@NotNull final MouseEvent event) { - setStartX(getTranslateX()); - setStartY(getTranslateY()); - setDragOffset(new Point2D(event.getSceneX(), event.getSceneY())); - toFront(); - } - - /** - * Handle finishing of dragging. - * - * @param event the mouse event. - */ - protected void processStopDrag(@NotNull final MouseEvent event) { - setStartX(0); - setStartY(0); - setDragOffset(null); - } + final double dragX = event.getSceneX() - dragOffset.getX(); + final double dragY = event.getSceneY() - getDragOffset().getY(); + + final double newXPosition = startX + dragX; + final double newYPosition = startY + dragY; + + setTranslateX(newXPosition); + setTranslateY(newYPosition); + } + + /** + * Handle starting of dragging. + * + * @param event the mouse event. + */ + protected void processStartDrag(@NotNull final MouseEvent event) { + setStartX(getTranslateX()); + setStartY(getTranslateY()); + setDragOffset(new Point2D(event.getSceneX(), event.getSceneY())); + toFront(); + } + + /** + * Handle finishing of dragging. + * + * @param event the mouse event. + */ + protected void processStopDrag(@NotNull final MouseEvent event) { + setStartX(0); + setStartY(0); + setDragOffset(null); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDraggableElement.java b/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDraggableElement.java index 686cd370..8ef26e4b 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDraggableElement.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDraggableElement.java @@ -14,44 +14,44 @@ */ public class SimpleDraggableElement extends VBox { - public SimpleDraggableElement() { - setOnDragDetected(this::processStartDragAndDrop); - setOnDragDone(this::processFinishDragAndDrop); - } + public SimpleDraggableElement() { + setOnDragDetected(this::processStartDragAndDrop); + setOnDragDone(this::processFinishDragAndDrop); + } - /** - * Get transfer modes. - * - * @return transfer modes. - */ - protected @NotNull TransferMode[] getTransferMode() { - return TransferMode.COPY_OR_MOVE; - } + /** + * Get transfer modes. + * + * @return transfer modes. + */ + protected @NotNull TransferMode[] getTransferMode() { + return TransferMode.COPY_OR_MOVE; + } - /** - * Prepare data to the dragboard. - * - * @param dragboard the dragboard. - */ - protected void prepareData(@NotNull final Dragboard dragboard) { - } + /** + * Prepare data to the dragboard. + * + * @param dragboard the dragboard. + */ + protected void prepareData(@NotNull final Dragboard dragboard) { + } - /** - * Handle finishing of dragging. - * - * @param event the mouse event. - */ - protected void processFinishDragAndDrop(@NotNull final DragEvent event) { - event.consume(); - } + /** + * Handle finishing of dragging. + * + * @param event the mouse event. + */ + protected void processFinishDragAndDrop(@NotNull final DragEvent event) { + event.consume(); + } - /** - * Handle starting of dragging. - * - * @param event the mouse event. - */ - protected void processStartDragAndDrop(@NotNull final MouseEvent event) { - prepareData(startDragAndDrop(getTransferMode())); - event.consume(); - } + /** + * Handle starting of dragging. + * + * @param event the mouse event. + */ + protected void processStartDragAndDrop(@NotNull final MouseEvent event) { + prepareData(startDragAndDrop(getTransferMode())); + event.consume(); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDroppedPanel.java b/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDroppedPanel.java index 71b65ac7..c3e583a6 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDroppedPanel.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/impl/SimpleDroppedPanel.java @@ -12,62 +12,62 @@ */ public class SimpleDroppedPanel extends Pane { - public SimpleDroppedPanel() { - setOnDragOver(this::processOnDragOver); - setOnDragEntered(this::processOnDragEntered); - setOnDragExited(this::processOnDragExited); - setOnDragDropped(this::processOnDragDropped); - } + public SimpleDroppedPanel() { + setOnDragOver(this::processOnDragOver); + setOnDragEntered(this::processOnDragEntered); + setOnDragExited(this::processOnDragExited); + setOnDragDropped(this::processOnDragDropped); + } - /** - * Accept a transfer mode. - * - * @param event the drag event. - */ - protected void acceptTransfersMode(@NotNull final DragEvent event) { - event.acceptTransferModes(TransferMode.COPY); - } + /** + * Accept a transfer mode. + * + * @param event the drag event. + */ + protected void acceptTransfersMode(@NotNull final DragEvent event) { + event.acceptTransferModes(TransferMode.COPY); + } - /** - * Handle finishing of dropping. - * - * @param event the drag event. - */ - protected void processOnDragDropped(@NotNull final DragEvent event) { - event.setDropCompleted(true); - event.consume(); - } + /** + * Handle finishing of dropping. + * + * @param event the drag event. + */ + protected void processOnDragDropped(@NotNull final DragEvent event) { + event.setDropCompleted(true); + event.consume(); + } - /** - * Handle entering to a drop area. - * - * @param event the drag event. - */ - protected void processOnDragEntered(@NotNull final DragEvent event) { - event.consume(); - } + /** + * Handle entering to a drop area. + * + * @param event the drag event. + */ + protected void processOnDragEntered(@NotNull final DragEvent event) { + event.consume(); + } - /** - * Handle exiting from a drop area. - * - * @param event the drag event. - */ - protected void processOnDragExited(@NotNull final DragEvent event) { - event.consume(); - } - - /** - * Handle dragging over element. - * - * @param event the drag event. - */ - protected void processOnDragOver(@NotNull final DragEvent event) { + /** + * Handle exiting from a drop area. + * + * @param event the drag event. + */ + protected void processOnDragExited(@NotNull final DragEvent event) { + event.consume(); + } - final Object source = event.getGestureSource(); - if (source != this) { - acceptTransfersMode(event); - } + /** + * Handle dragging over element. + * + * @param event the drag event. + */ + protected void processOnDragOver(@NotNull final DragEvent event) { - event.consume(); + final Object source = event.getGestureSource(); + if (source != this) { + acceptTransfersMode(event); } + + event.consume(); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/input/InternalContent.java b/rlib-fx/src/main/java/javasabr/rlib/fx/input/InternalContent.java index 10544515..2bb738b1 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/input/InternalContent.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/input/InternalContent.java @@ -14,83 +14,83 @@ */ public class InternalContent extends HashMap { - private static final long serialVersionUID = 2133513859087232216L; + private static final long serialVersionUID = 2133513859087232216L; - public static final DataFormat DATA_OBJECT = new DataFormat("internal/object"); - public static final DataFormat DATA_STRING = new DataFormat("internal/string"); - public static final DataFormat DATA_NUMBER = new DataFormat("internal/number"); - public static final DataFormat DATA_REFERENCE = new DataFormat("internal/reference"); + public static final DataFormat DATA_OBJECT = new DataFormat("internal/object"); + public static final DataFormat DATA_STRING = new DataFormat("internal/string"); + public static final DataFormat DATA_NUMBER = new DataFormat("internal/number"); + public static final DataFormat DATA_REFERENCE = new DataFormat("internal/reference"); - /** - * Gets a number. - * - * @return the number or null. - */ - public @Nullable Number getNumber() { - return (Number) get(DATA_NUMBER); - } + /** + * Gets a number. + * + * @return the number or null. + */ + public @Nullable Number getNumber() { + return (Number) get(DATA_NUMBER); + } - /** - * Gets an object. - * - * @param the object's type. - * @return the object or null. - */ - public @Nullable T getObject() { - return unsafeCast(get(DATA_OBJECT)); - } + /** + * Gets an object. + * + * @param the object's type. + * @return the object or null. + */ + public @Nullable T getObject() { + return unsafeCast(get(DATA_OBJECT)); + } - /** - * Gets a reference. - * - * @return the reference or null. - */ - public @Nullable Reference getReference() { - return (Reference) get(DATA_REFERENCE); - } + /** + * Gets a reference. + * + * @return the reference or null. + */ + public @Nullable Reference getReference() { + return (Reference) get(DATA_REFERENCE); + } - /** - * Gets a string. - * - * @return the string or null. - */ - public @Nullable String getString() { - return (String) get(DATA_STRING); - } + /** + * Gets a string. + * + * @return the string or null. + */ + public @Nullable String getString() { + return (String) get(DATA_STRING); + } - /** - * Puts a number. - * - * @param number the number or null. - */ - public void putNumber(@Nullable Number number) { - put(DATA_NUMBER, number); - } + /** + * Puts a number. + * + * @param number the number or null. + */ + public void putNumber(@Nullable Number number) { + put(DATA_NUMBER, number); + } - /** - * Puts an object. - * - * @param object the object or null. - */ - public void putObject(@Nullable Object object) { - put(DATA_OBJECT, object); - } + /** + * Puts an object. + * + * @param object the object or null. + */ + public void putObject(@Nullable Object object) { + put(DATA_OBJECT, object); + } - /** - * Puts a reference. - * - * @param reference the reference or null. - */ - public void putReference(@Nullable Reference reference) { - put(DATA_REFERENCE, reference); - } + /** + * Puts a reference. + * + * @param reference the reference or null. + */ + public void putReference(@Nullable Reference reference) { + put(DATA_REFERENCE, reference); + } - /** - * Puts a string. - * - * @param string the string or null. - */ - public void putString(@Nullable String string) { - put(DATA_STRING, string); - } + /** + * Puts a string. + * + * @param string the string or null. + */ + public void putString(@Nullable String string) { + put(DATA_STRING, string); + } } \ No newline at end of file diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FXUtils.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FXUtils.java index f558aac1..eac8f736 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FXUtils.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FXUtils.java @@ -21,456 +21,616 @@ @Deprecated public class FXUtils { - /** - * Add a css class to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param className the css class. - */ - public static void addClassTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final String className) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - } - - /** - * Add a css classes to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param classNames the css classes. - */ - public static void addClassesTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final String... classNames) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - } - - - /** - * Add a css class to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param className the css class. - */ - public static void addClassTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final String className) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - third.getStyleClass().add(className); - } - - /** - * Add a css classes to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param classNames the css classes. - */ - public static void addClassesTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final String... classNames) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - third.getStyleClass().addAll(classNames); - } - - /** - * Add a css class to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param fourth the fourth styleable. - * @param className the css class. - */ - public static void addClassTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final Styleable fourth, - @NotNull final String className) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - third.getStyleClass().add(className); - fourth.getStyleClass().add(className); - } - - /** - * Add a css classes to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param fourth the fourth styleable. - * @param classNames the css classes. - */ - public static void addClassesTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final Styleable fourth, - @NotNull final String... classNames) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - third.getStyleClass().addAll(classNames); - fourth.getStyleClass().addAll(classNames); - } - - /** - * Add a css class to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param fourth the fourth styleable. - * @param fifth the fifth styleable. - * @param className the css class. - */ - public static void addClassTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final Styleable fourth, - @NotNull final Styleable fifth, @NotNull final String className) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - third.getStyleClass().add(className); - fourth.getStyleClass().add(className); - fifth.getStyleClass().add(className); - } - - /** - * Add a css classes to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param fourth the fourth styleable. - * @param fifth the fifth styleable. - * @param classNames the css classes. - */ - public static void addClassesTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final Styleable fourth, - @NotNull final Styleable fifth, @NotNull final String... classNames) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - third.getStyleClass().addAll(classNames); - fourth.getStyleClass().addAll(classNames); - fifth.getStyleClass().addAll(classNames); - } - - /** - * Add a css class to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param fourth the fourth styleable. - * @param fifth the fifth styleable. - * @param sixth the sixth styleable. - * @param className the css class. - */ - public static void addClassTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final Styleable fourth, - @NotNull final Styleable fifth, @NotNull final Styleable sixth, - @NotNull final String className) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - third.getStyleClass().add(className); - fourth.getStyleClass().add(className); - fifth.getStyleClass().add(className); - sixth.getStyleClass().add(className); - } - - /** - * Add a css classes to nodes. - * - * @param first the first styleable. - * @param second the second styleable. - * @param third the third styleable. - * @param fourth the fourth styleable. - * @param fifth the fifth styleable. - * @param sixth the sixth styleable. - * @param classNames the css classes. - */ - public static void addClassesTo(@NotNull final Styleable first, @NotNull final Styleable second, - @NotNull final Styleable third, @NotNull final Styleable fourth, - @NotNull final Styleable fifth, @NotNull final Styleable sixth, - @NotNull final String... classNames) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - third.getStyleClass().addAll(classNames); - fourth.getStyleClass().addAll(classNames); - fifth.getStyleClass().addAll(classNames); - sixth.getStyleClass().addAll(classNames); - } - - /** - * Add a css class to a styleable. - * - * @param styleable the styleable. - * @param className the css class. - */ - public static void addClassTo(@NotNull final Styleable styleable, @NotNull final String className) { - styleable.getStyleClass().add(className); - } - - /** - * Add a css classes to a styleable. - * - * @param styleable the styleable. - * @param classNames the css classes. - */ - public static void addClassesTo(@NotNull final Styleable styleable, @NotNull final String... classNames) { - styleable.getStyleClass().addAll(classNames); - } - - /** - * Add css classes to a styleables. - * - * @param args the list of styleables and class names. - */ - public static void addClassesTo(@NotNull final Object... args) { - for (final Object object : args) { - - if (!(object instanceof Styleable)) { - continue; - } - - final ObservableList classes = ((Styleable) object).getStyleClass(); - - for (final Object arg : args) { - if (arg instanceof String) { - classes.add((String) arg); - } - } + /** + * Add a css class to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param className the css class. + */ + public static void addClassTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + } + + /** + * Add a css classes to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param classNames the css classes. + */ + public static void addClassesTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + } + + /** + * Add a css class to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param className the css class. + */ + public static void addClassTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + third + .getStyleClass() + .add(className); + } + + /** + * Add a css classes to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param classNames the css classes. + */ + public static void addClassesTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + third + .getStyleClass() + .addAll(classNames); + } + + /** + * Add a css class to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param fourth the fourth styleable. + * @param className the css class. + */ + public static void addClassTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final Styleable fourth, + @NotNull final String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + third + .getStyleClass() + .add(className); + fourth + .getStyleClass() + .add(className); + } + + /** + * Add a css classes to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param fourth the fourth styleable. + * @param classNames the css classes. + */ + public static void addClassesTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final Styleable fourth, + @NotNull final String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + third + .getStyleClass() + .addAll(classNames); + fourth + .getStyleClass() + .addAll(classNames); + } + + /** + * Add a css class to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param fourth the fourth styleable. + * @param fifth the fifth styleable. + * @param className the css class. + */ + public static void addClassTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final Styleable fourth, + @NotNull final Styleable fifth, + @NotNull final String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + third + .getStyleClass() + .add(className); + fourth + .getStyleClass() + .add(className); + fifth + .getStyleClass() + .add(className); + } + + /** + * Add a css classes to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param fourth the fourth styleable. + * @param fifth the fifth styleable. + * @param classNames the css classes. + */ + public static void addClassesTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final Styleable fourth, + @NotNull final Styleable fifth, + @NotNull final String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + third + .getStyleClass() + .addAll(classNames); + fourth + .getStyleClass() + .addAll(classNames); + fifth + .getStyleClass() + .addAll(classNames); + } + + /** + * Add a css class to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param fourth the fourth styleable. + * @param fifth the fifth styleable. + * @param sixth the sixth styleable. + * @param className the css class. + */ + public static void addClassTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final Styleable fourth, + @NotNull final Styleable fifth, + @NotNull final Styleable sixth, + @NotNull final String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + third + .getStyleClass() + .add(className); + fourth + .getStyleClass() + .add(className); + fifth + .getStyleClass() + .add(className); + sixth + .getStyleClass() + .add(className); + } + + /** + * Add a css classes to nodes. + * + * @param first the first styleable. + * @param second the second styleable. + * @param third the third styleable. + * @param fourth the fourth styleable. + * @param fifth the fifth styleable. + * @param sixth the sixth styleable. + * @param classNames the css classes. + */ + public static void addClassesTo( + @NotNull final Styleable first, + @NotNull final Styleable second, + @NotNull final Styleable third, + @NotNull final Styleable fourth, + @NotNull final Styleable fifth, + @NotNull final Styleable sixth, + @NotNull final String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + third + .getStyleClass() + .addAll(classNames); + fourth + .getStyleClass() + .addAll(classNames); + fifth + .getStyleClass() + .addAll(classNames); + sixth + .getStyleClass() + .addAll(classNames); + } + + /** + * Add a css class to a styleable. + * + * @param styleable the styleable. + * @param className the css class. + */ + public static void addClassTo(@NotNull final Styleable styleable, @NotNull final String className) { + styleable + .getStyleClass() + .add(className); + } + + /** + * Add a css classes to a styleable. + * + * @param styleable the styleable. + * @param classNames the css classes. + */ + public static void addClassesTo(@NotNull final Styleable styleable, @NotNull final String... classNames) { + styleable + .getStyleClass() + .addAll(classNames); + } + + /** + * Add css classes to a styleables. + * + * @param args the list of styleables and class names. + */ + public static void addClassesTo(@NotNull final Object... args) { + for (final Object object : args) { + + if (!(object instanceof Styleable)) { + continue; + } + + final ObservableList classes = ((Styleable) object).getStyleClass(); + + for (final Object arg : args) { + if (arg instanceof String) { + classes.add((String) arg); } + } } - - /** - * Add a random color to background. - * - * @param node the node. - */ - public static void addDebugBackgroundColor(@NotNull final Node node) { - - final Random random = new Random(); - final String color = - "rgb(" + random.nextInt(255) + "," + random.nextInt(255) + ", " + random.nextInt(255) + ")"; - - node.setStyle("-fx-background-color: " + color + ";"); - } - - /** - * Add a debug border to a node.. - * - * @param node the node. - */ - public static void addDebugBorderTo(@NotNull final Node node) { - node.setStyle("-fx-border-color: red; -fx-border-width: 3px;"); - } - - /** - * Add a node to a parent. - * - * @param node the node. - * @param parent the parent. - */ - public static void addToPane(@NotNull final Node node, @NotNull final Pane parent) { - final ObservableList children = parent.getChildren(); - children.add(node); - } - - /** - * Add nodes to a parent. - * - * @param first the first node. - * @param second the second node. - * @param parent the parent. - */ - public static void addToPane(@NotNull final Node first, @NotNull final Node second, @NotNull final Pane parent) { - final ObservableList children = parent.getChildren(); - children.add(first); - children.add(second); - } - - /** - * Add nodes to a parent. - * - * @param first the first node. - * @param second the second node. - * @param third the third node. - * @param parent the parent. - */ - public static void addToPane(@NotNull final Node first, @NotNull final Node second, @NotNull final Node third, - @NotNull final Pane parent) { - final ObservableList children = parent.getChildren(); - children.add(first); - children.add(second); - children.add(third); - } - - /** - * Add nodes to a parent. - * - * @param first the first node. - * @param second the second node. - * @param third the third node. - * @param fourth the fourth node. - * @param parent the parent. - */ - public static void addToPane(@NotNull final Node first, @NotNull final Node second, @NotNull final Node third, - @NotNull final Node fourth, @NotNull final Pane parent) { - final ObservableList children = parent.getChildren(); - children.add(first); - children.add(second); - children.add(third); - children.add(fourth); - } - - /** - * Bind fixed height of region to height property. - * - * @param region the region. - * @param heightProperty the height property. - */ - public static void bindFixedHeight(@NotNull final Region region, - @NotNull final ReadOnlyProperty heightProperty) { - region.minHeightProperty().bind(heightProperty); - region.maxHeightProperty().bind(heightProperty); - } - - - /** - * Bind fixed height of region to height value. - * - * @param region the region. - * @param height the height value. - */ - public static void bindFixedHeight(@NotNull final Region region, - @NotNull final ObservableValue height) { - region.minHeightProperty().bind(height); - region.maxHeightProperty().bind(height); - } - - /** - * Bind fixed size of region to a height and width properties. - * - * @param region the region. - * @param widthProperty the width property. - * @param heightProperty the height property. - */ - public static void bindFixedSize(@NotNull final Region region, - @NotNull final ReadOnlyProperty widthProperty, - @NotNull final ReadOnlyProperty heightProperty) { - region.minWidthProperty().bind(widthProperty); - region.maxWidthProperty().bind(widthProperty); - region.minHeightProperty().bind(heightProperty); - region.maxHeightProperty().bind(heightProperty); - } - - /** - * Bind fixed size of region to a height and width properties. - * - * @param region the region. - * @param width the width value. - * @param height the height value. - */ - public static void bindFixedSize(@NotNull final Region region, - @NotNull final ObservableValue width, - @NotNull final ObservableValue height) { - region.minWidthProperty().bind(width); - region.maxWidthProperty().bind(width); - region.minHeightProperty().bind(height); - region.maxHeightProperty().bind(height); - } - - /** - * Bind fixed height of region to width property. - * - * @param region the region. - * @param widthProperty the height property. - */ - public static void bindFixedWidth(@NotNull final Region region, - @NotNull final ReadOnlyProperty widthProperty) { - region.minWidthProperty().bind(widthProperty); - region.maxWidthProperty().bind(widthProperty); - } - - /** - * Bind fixed height of region to width value. - * - * @param region the region. - * @param width the height value. - */ - public static void bindFixedWidth(@NotNull final Region region, - @NotNull final ObservableValue width) { - region.minWidthProperty().bind(width); - region.maxWidthProperty().bind(width); - } - - /** - * Remove a node from a parent. - * - * @param node the node. - * @param parent the parent. - */ - public static void removeFromParent(@NotNull final Node node, @NotNull final Pane parent) { - final ObservableList children = parent.getChildren(); - children.remove(node); - } - - /** - * Set fixed height to a region. - * - * @param region the region. - * @param height the height. - */ - public static void setFixedHeight(@NotNull final Region region, final double height) { - region.setMaxHeight(height); - region.setMinHeight(height); - } - - /** - * Set fixed size to a region. - * - * @param region the region. - * @param width the width. - * @param height the height. - */ - public static void setFixedSize(@NotNull final Region region, final double width, final double height) { - region.setMaxHeight(height); - region.setMinHeight(height); - region.setMaxWidth(width); - region.setMinWidth(width); - } - - /** - * Set fixed size to a region. - * - * @param region the region. - * @param size the size. - */ - public static void setFixedSize(@NotNull final Region region, @NotNull final Point size) { - region.setMaxHeight(size.getY()); - region.setMinHeight(size.getY()); - region.setMaxWidth(size.getX()); - region.setMinWidth(size.getX()); - } - - /** - * Set fixed width to a region. - * - * @param region the region. - * @param width the width. - */ - public static void setFixedWidth(@NotNull final Region region, final double width) { - region.setMaxWidth(width); - region.setMinWidth(width); - } - - /** - * Apply the handler to each child of the node. - * - * @param node the node. - * @param handler the handler. - */ - public static void applyToChildren(@NotNull final Parent node, @NotNull final Consumer handler) { - node.getChildrenUnmodifiable().forEach(handler); - } + } + + /** + * Add a random color to background. + * + * @param node the node. + */ + public static void addDebugBackgroundColor(@NotNull final Node node) { + + final Random random = new Random(); + final String color = "rgb(" + random.nextInt(255) + "," + random.nextInt(255) + ", " + random.nextInt(255) + ")"; + + node.setStyle("-fx-background-color: " + color + ";"); + } + + /** + * Add a debug border to a node.. + * + * @param node the node. + */ + public static void addDebugBorderTo(@NotNull final Node node) { + node.setStyle("-fx-border-color: red; -fx-border-width: 3px;"); + } + + /** + * Add a node to a parent. + * + * @param node the node. + * @param parent the parent. + */ + public static void addToPane(@NotNull final Node node, @NotNull final Pane parent) { + final ObservableList children = parent.getChildren(); + children.add(node); + } + + /** + * Add nodes to a parent. + * + * @param first the first node. + * @param second the second node. + * @param parent the parent. + */ + public static void addToPane(@NotNull final Node first, @NotNull final Node second, @NotNull final Pane parent) { + final ObservableList children = parent.getChildren(); + children.add(first); + children.add(second); + } + + /** + * Add nodes to a parent. + * + * @param first the first node. + * @param second the second node. + * @param third the third node. + * @param parent the parent. + */ + public static void addToPane( + @NotNull final Node first, + @NotNull final Node second, + @NotNull final Node third, + @NotNull final Pane parent) { + final ObservableList children = parent.getChildren(); + children.add(first); + children.add(second); + children.add(third); + } + + /** + * Add nodes to a parent. + * + * @param first the first node. + * @param second the second node. + * @param third the third node. + * @param fourth the fourth node. + * @param parent the parent. + */ + public static void addToPane( + @NotNull final Node first, + @NotNull final Node second, + @NotNull final Node third, + @NotNull final Node fourth, + @NotNull final Pane parent) { + final ObservableList children = parent.getChildren(); + children.add(first); + children.add(second); + children.add(third); + children.add(fourth); + } + + /** + * Bind fixed height of region to height property. + * + * @param region the region. + * @param heightProperty the height property. + */ + public static void bindFixedHeight( + @NotNull final Region region, + @NotNull final ReadOnlyProperty heightProperty) { + region + .minHeightProperty() + .bind(heightProperty); + region + .maxHeightProperty() + .bind(heightProperty); + } + + /** + * Bind fixed height of region to height value. + * + * @param region the region. + * @param height the height value. + */ + public static void bindFixedHeight( + @NotNull final Region region, + @NotNull final ObservableValue height) { + region + .minHeightProperty() + .bind(height); + region + .maxHeightProperty() + .bind(height); + } + + /** + * Bind fixed size of region to a height and width properties. + * + * @param region the region. + * @param widthProperty the width property. + * @param heightProperty the height property. + */ + public static void bindFixedSize( + @NotNull final Region region, + @NotNull final ReadOnlyProperty widthProperty, + @NotNull final ReadOnlyProperty heightProperty) { + region + .minWidthProperty() + .bind(widthProperty); + region + .maxWidthProperty() + .bind(widthProperty); + region + .minHeightProperty() + .bind(heightProperty); + region + .maxHeightProperty() + .bind(heightProperty); + } + + /** + * Bind fixed size of region to a height and width properties. + * + * @param region the region. + * @param width the width value. + * @param height the height value. + */ + public static void bindFixedSize( + @NotNull final Region region, + @NotNull final ObservableValue width, + @NotNull final ObservableValue height) { + region + .minWidthProperty() + .bind(width); + region + .maxWidthProperty() + .bind(width); + region + .minHeightProperty() + .bind(height); + region + .maxHeightProperty() + .bind(height); + } + + /** + * Bind fixed height of region to width property. + * + * @param region the region. + * @param widthProperty the height property. + */ + public static void bindFixedWidth( + @NotNull final Region region, + @NotNull final ReadOnlyProperty widthProperty) { + region + .minWidthProperty() + .bind(widthProperty); + region + .maxWidthProperty() + .bind(widthProperty); + } + + /** + * Bind fixed height of region to width value. + * + * @param region the region. + * @param width the height value. + */ + public static void bindFixedWidth( + @NotNull final Region region, + @NotNull final ObservableValue width) { + region + .minWidthProperty() + .bind(width); + region + .maxWidthProperty() + .bind(width); + } + + /** + * Remove a node from a parent. + * + * @param node the node. + * @param parent the parent. + */ + public static void removeFromParent(@NotNull final Node node, @NotNull final Pane parent) { + final ObservableList children = parent.getChildren(); + children.remove(node); + } + + /** + * Set fixed height to a region. + * + * @param region the region. + * @param height the height. + */ + public static void setFixedHeight(@NotNull final Region region, final double height) { + region.setMaxHeight(height); + region.setMinHeight(height); + } + + /** + * Set fixed size to a region. + * + * @param region the region. + * @param width the width. + * @param height the height. + */ + public static void setFixedSize(@NotNull final Region region, final double width, final double height) { + region.setMaxHeight(height); + region.setMinHeight(height); + region.setMaxWidth(width); + region.setMinWidth(width); + } + + /** + * Set fixed size to a region. + * + * @param region the region. + * @param size the size. + */ + public static void setFixedSize(@NotNull final Region region, @NotNull final Point size) { + region.setMaxHeight(size.getY()); + region.setMinHeight(size.getY()); + region.setMaxWidth(size.getX()); + region.setMinWidth(size.getX()); + } + + /** + * Set fixed width to a region. + * + * @param region the region. + * @param width the width. + */ + public static void setFixedWidth(@NotNull final Region region, final double width) { + region.setMaxWidth(width); + region.setMinWidth(width); + } + + /** + * Apply the handler to each child of the node. + * + * @param node the node. + * @param handler the handler. + */ + public static void applyToChildren(@NotNull final Parent node, @NotNull final Consumer handler) { + node + .getChildrenUnmodifiable() + .forEach(handler); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java index 1b785fc4..0b5a58c6 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java @@ -27,277 +27,249 @@ */ public class FxControlUtils { - /** - * Add handler of text changes. - * - * @param control the text control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onTextChange( - @NotNull TextInputControl control, - @NotNull Runnable handler - ) { - return ObservableUtils.onChange(control.textProperty(), handler); - } + /** + * Add handler of text changes. + * + * @param control the text control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onTextChange(@NotNull TextInputControl control, @NotNull Runnable handler) { + return ObservableUtils.onChange(control.textProperty(), handler); + } - /** - * Add handler of text changes. - * - * @param control the text control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onTextChange( - @NotNull TextInputControl control, - @NotNull Consumer handler - ) { - return ObservableUtils.onChange(control.textProperty(), handler); - } + /** + * Add handler of text changes. + * + * @param control the text control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onTextChange( + @NotNull TextInputControl control, + @NotNull Consumer handler) { + return ObservableUtils.onChange(control.textProperty(), handler); + } - /** - * Add handler of selected changes. - * - * @param control the check box control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedChange( - @NotNull CheckBox control, - @NotNull Runnable handler - ) { - return ObservableUtils.onChange(control.selectedProperty(), handler); - } + /** + * Add handler of selected changes. + * + * @param control the check box control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedChange(@NotNull CheckBox control, @NotNull Runnable handler) { + return ObservableUtils.onChange(control.selectedProperty(), handler); + } - /** - * Add handler of selected changes. - * - * @param control the check box control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedChange( - @NotNull CheckBox control, - @NotNull Consumer handler - ) { - return ObservableUtils.onChange(control.selectedProperty(), handler); - } + /** + * Add handler of selected changes. + * + * @param control the check box control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedChange( + @NotNull CheckBox control, + @NotNull Consumer handler) { + return ObservableUtils.onChange(control.selectedProperty(), handler); + } - /** - * Add handler of selected changes. - * - * @param control the check box control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedChange( - @NotNull ToggleButton control, - @NotNull Runnable handler - ) { - return ObservableUtils.onChange(control.selectedProperty(), handler); - } + /** + * Add handler of selected changes. + * + * @param control the check box control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedChange( + @NotNull ToggleButton control, + @NotNull Runnable handler) { + return ObservableUtils.onChange(control.selectedProperty(), handler); + } - /** - * Add handler of selected changes. - * - * @param control the check box control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedChange( - @NotNull ToggleButton control, - @NotNull Consumer handler - ) { - return ObservableUtils.onChange(control.selectedProperty(), handler); - } + /** + * Add handler of selected changes. + * + * @param control the check box control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedChange( + @NotNull ToggleButton control, + @NotNull Consumer handler) { + return ObservableUtils.onChange(control.selectedProperty(), handler); + } - /** - * Add handler of color changes. - * - * @param control the color picker control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onColorChange( - @NotNull ColorPicker control, - @NotNull Consumer handler - ) { - return ObservableUtils.onChange(control.valueProperty(), handler); - } + /** + * Add handler of color changes. + * + * @param control the color picker control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onColorChange( + @NotNull ColorPicker control, + @NotNull Consumer handler) { + return ObservableUtils.onChange(control.valueProperty(), handler); + } - /** - * Add handler of color changes. - * - * @param control the color picker control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onColorChange( - @NotNull ColorPicker control, - @NotNull Runnable handler - ) { - return ObservableUtils.onChange(control.valueProperty(), handler); - } + /** + * Add handler of color changes. + * + * @param control the color picker control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onColorChange(@NotNull ColorPicker control, @NotNull Runnable handler) { + return ObservableUtils.onChange(control.valueProperty(), handler); + } - /** - * Add handler of value changes. - * - * @param control the typed text field control. - * @param handler the handler. - * @param the value's type. - * @return the change event appender. - */ - public static ChangeEventAppender onValueChange( - @NotNull TypedTextField control, - @NotNull Consumer handler - ) { - return ObservableUtils.onChange(control.valueProperty(), handler); - } + /** + * Add handler of value changes. + * + * @param control the typed text field control. + * @param handler the handler. + * @param the value's type. + * @return the change event appender. + */ + public static ChangeEventAppender onValueChange( + @NotNull TypedTextField control, + @NotNull Consumer handler) { + return ObservableUtils.onChange(control.valueProperty(), handler); + } - /** - * Add handler of value changes. - * - * @param control the typed text field control. - * @param handler the handler. - * @param the value's type. - * @return the change event appender. - */ - public static ChangeEventAppender onValueChange( - @NotNull TypedTextField control, - @NotNull Runnable handler - ) { - return ObservableUtils.onChange(control.valueProperty(), handler); - } + /** + * Add handler of value changes. + * + * @param control the typed text field control. + * @param handler the handler. + * @param the value's type. + * @return the change event appender. + */ + public static ChangeEventAppender onValueChange( + @NotNull TypedTextField control, + @NotNull Runnable handler) { + return ObservableUtils.onChange(control.valueProperty(), handler); + } - /** - * Add handler of focus state changes. - * - * @param control the any focusable control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onFocusChange( - @NotNull Node control, - @NotNull Consumer handler - ) { - return ObservableUtils.onChange(control.focusedProperty(), handler); - } + /** + * Add handler of focus state changes. + * + * @param control the any focusable control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onFocusChange(@NotNull Node control, @NotNull Consumer handler) { + return ObservableUtils.onChange(control.focusedProperty(), handler); + } - /** - * Add handler of selected item changes. - * - * @param control the combo box control. - * @param handler the handler. - * @param the value's type. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedItemChange( - @NotNull ComboBox control, - @NotNull Runnable handler - ) { - return ObservableUtils.onChange(control.valueProperty(), handler); - } + /** + * Add handler of selected item changes. + * + * @param control the combo box control. + * @param handler the handler. + * @param the value's type. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedItemChange( + @NotNull ComboBox control, + @NotNull Runnable handler) { + return ObservableUtils.onChange(control.valueProperty(), handler); + } - /** - * Add handler of selected item changes. - * - * @param control the combo box control. - * @param handler the handler. - * @param the value's type. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedItemChange( - @NotNull ComboBox control, - @NotNull Consumer handler - ) { - return ObservableUtils.onChange(control.valueProperty(), handler); - } + /** + * Add handler of selected item changes. + * + * @param control the combo box control. + * @param handler the handler. + * @param the value's type. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedItemChange( + @NotNull ComboBox control, + @NotNull Consumer handler) { + return ObservableUtils.onChange(control.valueProperty(), handler); + } - /** - * Add handler of selected item changes. - * - * @param control the list view control. - * @param handler the handler. - * @param the value's type. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedItemChange( - @NotNull ListView control, - @NotNull Consumer handler - ) { - var selectionModel = control.getSelectionModel(); - return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); - } + /** + * Add handler of selected item changes. + * + * @param control the list view control. + * @param handler the handler. + * @param the value's type. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedItemChange( + @NotNull ListView control, + @NotNull Consumer handler) { + var selectionModel = control.getSelectionModel(); + return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); + } - /** - * Add handler of selected item changes. - * - * @param control the tree view control. - * @param handler the handler. - * @param the value's type. - * @return the change event appender. - */ - public static ChangeEventAppender> onSelectedItemChange( - @NotNull TreeView control, - @NotNull Runnable handler - ) { - var selectionModel = control.getSelectionModel(); - return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); - } + /** + * Add handler of selected item changes. + * + * @param control the tree view control. + * @param handler the handler. + * @param the value's type. + * @return the change event appender. + */ + public static ChangeEventAppender> onSelectedItemChange( + @NotNull TreeView control, + @NotNull Runnable handler) { + var selectionModel = control.getSelectionModel(); + return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); + } - /** - * Add handler of selected item changes. - * - * @param control the tree view control. - * @param handler the handler. - * @param the value's type. - * @return the change event appender. - */ - public static ChangeEventAppender> onSelectedItemChange( - @NotNull TreeView control, - @NotNull Consumer> handler - ) { - var selectionModel = control.getSelectionModel(); - return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); - } + /** + * Add handler of selected item changes. + * + * @param control the tree view control. + * @param handler the handler. + * @param the value's type. + * @return the change event appender. + */ + public static ChangeEventAppender> onSelectedItemChange( + @NotNull TreeView control, + @NotNull Consumer> handler) { + var selectionModel = control.getSelectionModel(); + return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); + } - /** - * Add handler to handle action events. - * - * @param control the button control. - * @param handler the handler. - */ - public static void onAction(@NotNull ButtonBase control, @NotNull Runnable handler) { - control.addEventHandler(ActionEvent.ACTION, event -> handler.run()); - } + /** + * Add handler to handle action events. + * + * @param control the button control. + * @param handler the handler. + */ + public static void onAction(@NotNull ButtonBase control, @NotNull Runnable handler) { + control.addEventHandler(ActionEvent.ACTION, event -> handler.run()); + } - /** - * Add handler of selected tab changes. - * - * @param control the tab pane control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedTabChange( - @NotNull TabPane control, - @NotNull Consumer handler - ) { - var selectionModel = control.getSelectionModel(); - return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); - } + /** + * Add handler of selected tab changes. + * + * @param control the tab pane control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedTabChange(@NotNull TabPane control, @NotNull Consumer handler) { + var selectionModel = control.getSelectionModel(); + return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); + } - /** - * Add handler of selected tab changes. - * - * @param control the tab pane control. - * @param handler the handler. - * @return the change event appender. - */ - public static ChangeEventAppender onSelectedTabChange( - @NotNull TabPane control, - @NotNull BiConsumer handler - ) { - var selectionModel = control.getSelectionModel(); - return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); - } + /** + * Add handler of selected tab changes. + * + * @param control the tab pane control. + * @param handler the handler. + * @return the change event appender. + */ + public static ChangeEventAppender onSelectedTabChange( + @NotNull TabPane control, + @NotNull BiConsumer handler) { + var selectionModel = control.getSelectionModel(); + return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java index 2b207de5..97752ea9 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java @@ -18,216 +18,7 @@ */ public class FxUtils { - public static class CssClassAppender { - - /** - * Add the css class to the styleable object. - * - * @param styleable the styleable object. - * @param className the css class. - * @return the css class appender. - */ - public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String className) { - styleable.getStyleClass().add(className); - return this; - } - - /** - * Add the css class to the styleable objects. - * - * @param first the first styleable object. - * @param second the second styleable object. - * @param className the css class. - * @return the css class appender. - */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String className - ) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - return this; - } - - /** - * Add the css class to the styleable objects. - * - * @param first the first styleable object. - * @param second the second styleable object. - * @param third the third styleable object. - * @param className the css class. - * @return the css class appender. - */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String className - ) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - third.getStyleClass().add(className); - return this; - } - - /** - * Add css classes to the styleable object. - * - * @param styleable the styleable object. - * @param classNames the css classes. - * @return the css class appender. - */ - public @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String... classNames) { - styleable.getStyleClass().addAll(classNames); - return this; - } - - /** - * Add css classes to the styleable objects. - * - * @param first the first styleable object. - * @param second the second styleable object. - * @param classNames the css classes. - * @return the css class appender. - */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String... classNames - ) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - return this; - } - - /** - * Add css classes to the styleable objects. - * - * @param first the first styleable object. - * @param second the second styleable object. - * @param third the third styleable object. - * @param classNames the css classes. - * @return the css class appender. - */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String... classNames - ) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - third.getStyleClass().addAll(classNames); - return this; - } - } - - public static class ChildrenAppender { - - /** - * Add the node to the parent. - * - * @param parent the parent. - * @param node the node. - * @return the child appender. - */ - public @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node node) { - parent.getChildren().add(node); - return this; - } - - /** - * Add the node to the parent. - * - * @param parent the parent. - * @param node the node. - * @return the child appender. - */ - public @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node node) { - parent.getChildren().add(node); - return this; - } - - /** - * Add the nodes to the parent. - * - * @param parent the parent. - * @param nodes the nodes. - * @return the child appender. - */ - public @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node... nodes) { - parent.getChildren().addAll(nodes); - return this; - } - - /** - * Add the nodes to the parent. - * - * @param parent the parent. - * @param nodes the nodes. - * @return the child appender. - */ - public @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node... nodes) { - parent.getChildren().addAll(nodes); - return this; - } - } - - public static class ChildrenRemover { - - /** - * Remove the node from the parent. - * - * @param parent the parent. - * @param node the node. - * @return the child appender. - */ - public @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node node) { - parent.getChildren().remove(node); - return this; - } - - /** - * Remove the node from the parent. - * - * @param parent the parent. - * @param node the node. - * @return the child appender. - */ - public @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node node) { - parent.getChildren().remove(node); - return this; - } - - /** - * Remove the nodes from the parent. - * - * @param parent the parent. - * @param nodes the nodes. - * @return the child appender. - */ - public @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node... nodes) { - parent.getChildren().removeAll(nodes); - return this; - } - - /** - * Remove the nodes from the parent. - * - * @param parent the parent. - * @param nodes the nodes. - * @return the child appender. - */ - public @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node... nodes) { - parent.getChildren().removeAll(nodes); - return this; - } - } - - private static final CssClassAppender CLASS_APPENDER = new CssClassAppender(); - private static final ChildrenAppender CHILDREN_APPENDER = new ChildrenAppender(); - private static final ChildrenRemover CHILDREN_REMOVER = new ChildrenRemover(); + public static class CssClassAppender { /** * Add the css class to the styleable object. @@ -236,305 +27,588 @@ public static class ChildrenRemover { * @param className the css class. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String className) { - styleable.getStyleClass().add(className); - return CLASS_APPENDER; + public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String className) { + styleable + .getStyleClass() + .add(className); + return this; } /** * Add the css class to the styleable objects. * - * @param first the first styleable object. - * @param second the second styleable object. + * @param first the first styleable object. + * @param second the second styleable object. * @param className the css class. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String className - ) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - return CLASS_APPENDER; + public @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + return this; } /** * Add the css class to the styleable objects. * - * @param first the first styleable object. - * @param second the second styleable object. - * @param third the third styleable object. + * @param first the first styleable object. + * @param second the second styleable object. + * @param third the third styleable object. * @param className the css class. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String className - ) { - first.getStyleClass().add(className); - second.getStyleClass().add(className); - third.getStyleClass().add(className); - return CLASS_APPENDER; + public @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull Styleable third, + @NotNull String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + third + .getStyleClass() + .add(className); + return this; } /** * Add css classes to the styleable object. * - * @param styleable the styleable object. + * @param styleable the styleable object. * @param classNames the css classes. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String... classNames) { - styleable.getStyleClass().addAll(classNames); - return CLASS_APPENDER; + public @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String... classNames) { + styleable + .getStyleClass() + .addAll(classNames); + return this; } /** * Add css classes to the styleable objects. * - * @param first the first styleable object. - * @param second the second styleable object. + * @param first the first styleable object. + * @param second the second styleable object. * @param classNames the css classes. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String... classNames - ) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - return CLASS_APPENDER; + public @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + return this; } /** * Add css classes to the styleable objects. * - * @param first the first styleable object. - * @param second the second styleable object. - * @param third the third styleable object. + * @param first the first styleable object. + * @param second the second styleable object. + * @param third the third styleable object. * @param classNames the css classes. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String... classNames - ) { - first.getStyleClass().addAll(classNames); - second.getStyleClass().addAll(classNames); - third.getStyleClass().addAll(classNames); - return CLASS_APPENDER; + public @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull Styleable third, + @NotNull String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + third + .getStyleClass() + .addAll(classNames); + return this; } + } + public static class ChildrenAppender { /** * Add the node to the parent. * * @param parent the parent. - * @param node the node. + * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node node) { - parent.getChildren().add(node); - return CHILDREN_APPENDER; + public @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node node) { + parent + .getChildren() + .add(node); + return this; } /** * Add the node to the parent. * * @param parent the parent. - * @param node the node. + * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node node) { - parent.getChildren().add(node); - return CHILDREN_APPENDER; + public @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node node) { + parent + .getChildren() + .add(node); + return this; } /** * Add the nodes to the parent. * * @param parent the parent. - * @param nodes the nodes. + * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node... nodes) { - parent.getChildren().addAll(nodes); - return CHILDREN_APPENDER; + public @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node... nodes) { + parent + .getChildren() + .addAll(nodes); + return this; } /** * Add the nodes to the parent. * * @param parent the parent. - * @param nodes the nodes. + * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node... nodes) { - parent.getChildren().addAll(nodes); - return CHILDREN_APPENDER; + public @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node... nodes) { + parent + .getChildren() + .addAll(nodes); + return this; } + } + + public static class ChildrenRemover { /** * Remove the node from the parent. * * @param parent the parent. - * @param node the node. + * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node node) { - parent.getChildren().remove(node); - return CHILDREN_REMOVER; + public @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node node) { + parent + .getChildren() + .remove(node); + return this; } /** * Remove the node from the parent. * * @param parent the parent. - * @param node the node. + * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node node) { - parent.getChildren().remove(node); - return CHILDREN_REMOVER; + public @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node node) { + parent + .getChildren() + .remove(node); + return this; } /** * Remove the nodes from the parent. * * @param parent the parent. - * @param nodes the nodes. + * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node... nodes) { - parent.getChildren().removeAll(nodes); - return CHILDREN_REMOVER; + public @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node... nodes) { + parent + .getChildren() + .removeAll(nodes); + return this; } /** * Remove the nodes from the parent. * * @param parent the parent. - * @param nodes the nodes. + * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node... nodes) { - parent.getChildren().removeAll(nodes); - return CHILDREN_REMOVER; - } - - /** - * Reset pref width property for the region. - * - * @param region the region. - * @param the region's type. - * @return the region. - */ - public static T resetPrefWidth(@NotNull T region) { - region.prefWidthProperty().unbind(); - region.setPrefWidth(Region.USE_COMPUTED_SIZE); - return region; + public @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node... nodes) { + parent + .getChildren() + .removeAll(nodes); + return this; } - - /** - * Reset min/max width properties for the region. - * - * @param the region's type. - * @param region the region. - * @return the region. - */ - public static T resetMinMaxWidth(@NotNull T region) { - region.maxWidthProperty().unbind(); - region.setMaxWidth(Region.USE_COMPUTED_SIZE); - region.minWidthProperty().unbind(); - region.setMinWidth(Region.USE_COMPUTED_SIZE); - return region; + } + + private static final CssClassAppender CLASS_APPENDER = new CssClassAppender(); + private static final ChildrenAppender CHILDREN_APPENDER = new ChildrenAppender(); + private static final ChildrenRemover CHILDREN_REMOVER = new ChildrenRemover(); + + /** + * Add the css class to the styleable object. + * + * @param styleable the styleable object. + * @param className the css class. + * @return the css class appender. + */ + public static @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String className) { + styleable + .getStyleClass() + .add(className); + return CLASS_APPENDER; + } + + /** + * Add the css class to the styleable objects. + * + * @param first the first styleable object. + * @param second the second styleable object. + * @param className the css class. + * @return the css class appender. + */ + public static @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + return CLASS_APPENDER; + } + + /** + * Add the css class to the styleable objects. + * + * @param first the first styleable object. + * @param second the second styleable object. + * @param third the third styleable object. + * @param className the css class. + * @return the css class appender. + */ + public static @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull Styleable third, + @NotNull String className) { + first + .getStyleClass() + .add(className); + second + .getStyleClass() + .add(className); + third + .getStyleClass() + .add(className); + return CLASS_APPENDER; + } + + /** + * Add css classes to the styleable object. + * + * @param styleable the styleable object. + * @param classNames the css classes. + * @return the css class appender. + */ + public static @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String... classNames) { + styleable + .getStyleClass() + .addAll(classNames); + return CLASS_APPENDER; + } + + /** + * Add css classes to the styleable objects. + * + * @param first the first styleable object. + * @param second the second styleable object. + * @param classNames the css classes. + * @return the css class appender. + */ + public static @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + return CLASS_APPENDER; + } + + /** + * Add css classes to the styleable objects. + * + * @param first the first styleable object. + * @param second the second styleable object. + * @param third the third styleable object. + * @param classNames the css classes. + * @return the css class appender. + */ + public static @NotNull CssClassAppender addClass( + @NotNull Styleable first, + @NotNull Styleable second, + @NotNull Styleable third, + @NotNull String... classNames) { + first + .getStyleClass() + .addAll(classNames); + second + .getStyleClass() + .addAll(classNames); + third + .getStyleClass() + .addAll(classNames); + return CLASS_APPENDER; + } + + /** + * Add the node to the parent. + * + * @param parent the parent. + * @param node the node. + * @return the child appender. + */ + public static @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node node) { + parent + .getChildren() + .add(node); + return CHILDREN_APPENDER; + } + + /** + * Add the node to the parent. + * + * @param parent the parent. + * @param node the node. + * @return the child appender. + */ + public static @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node node) { + parent + .getChildren() + .add(node); + return CHILDREN_APPENDER; + } + + /** + * Add the nodes to the parent. + * + * @param parent the parent. + * @param nodes the nodes. + * @return the child appender. + */ + public static @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node... nodes) { + parent + .getChildren() + .addAll(nodes); + return CHILDREN_APPENDER; + } + + /** + * Add the nodes to the parent. + * + * @param parent the parent. + * @param nodes the nodes. + * @return the child appender. + */ + public static @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node... nodes) { + parent + .getChildren() + .addAll(nodes); + return CHILDREN_APPENDER; + } + + /** + * Remove the node from the parent. + * + * @param parent the parent. + * @param node the node. + * @return the child appender. + */ + public static @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node node) { + parent + .getChildren() + .remove(node); + return CHILDREN_REMOVER; + } + + /** + * Remove the node from the parent. + * + * @param parent the parent. + * @param node the node. + * @return the child appender. + */ + public static @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node node) { + parent + .getChildren() + .remove(node); + return CHILDREN_REMOVER; + } + + /** + * Remove the nodes from the parent. + * + * @param parent the parent. + * @param nodes the nodes. + * @return the child appender. + */ + public static @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node... nodes) { + parent + .getChildren() + .removeAll(nodes); + return CHILDREN_REMOVER; + } + + /** + * Remove the nodes from the parent. + * + * @param parent the parent. + * @param nodes the nodes. + * @return the child appender. + */ + public static @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node... nodes) { + parent + .getChildren() + .removeAll(nodes); + return CHILDREN_REMOVER; + } + + /** + * Reset pref width property for the region. + * + * @param region the region. + * @param the region's type. + * @return the region. + */ + public static T resetPrefWidth(@NotNull T region) { + region + .prefWidthProperty() + .unbind(); + region.setPrefWidth(Region.USE_COMPUTED_SIZE); + return region; + } + + /** + * Reset min/max width properties for the region. + * + * @param the region's type. + * @param region the region. + * @return the region. + */ + public static T resetMinMaxWidth(@NotNull T region) { + region + .maxWidthProperty() + .unbind(); + region.setMaxWidth(Region.USE_COMPUTED_SIZE); + region + .minWidthProperty() + .unbind(); + region.setMinWidth(Region.USE_COMPUTED_SIZE); + return region; + } + + /** + * Rebind pref width property of the region. + * + * @param region the region. + * @param value the value. + * @param the region's type. + * @return the region. + */ + public static T rebindPrefWidth( + @NotNull T region, + @NotNull ObservableValue value) { + + var width = region.prefWidthProperty(); + + if (width.isBound()) { + width.unbind(); } - /** - * Rebind pref width property of the region. - * - * @param region the region. - * @param value the value. - * @param the region's type. - * @return the region. - */ - public static T rebindPrefWidth( - @NotNull T region, - @NotNull ObservableValue value - ) { - - var width = region.prefWidthProperty(); - - if (width.isBound()) { - width.unbind(); - } - - width.bind(value); - - - return region; - } - - /** - * Add a random color to background. - * - * @param node the node. - */ - public static void addDebugBackgroundColor(@NotNull Node node) { - - var random = ThreadLocalRandom.current(); - var color = "rgb(" + random.nextInt(255) + "," + - random.nextInt(255) + ", " + random.nextInt(255) + ")"; - - node.setStyle("-fx-background-color: " + color + ";"); - } - - /** - * Add a debug border to a node.. - * - * @param node the node. - */ - public static void addDebugBorderTo(@NotNull Node node) { - node.setStyle("-fx-border-color: red; -fx-border-width: 3px;"); - } - - /** - * Set fixed size to a region. - * - * @param region the region. - * @param width the width. - * @param height the height. - */ - public static void setFixedSize(@NotNull Region region, double width, double height) { - region.setMaxHeight(height); - region.setMinHeight(height); - region.setMaxWidth(width); - region.setMinWidth(width); - } - - /** - * Set fixed size to a region. - * - * @param region the region. - * @param size the size. - */ - public static void setFixedSize(@NotNull Region region, @NotNull Point size) { - setFixedSize(region, size.getX(), size.getY()); - } - - /** - * Set fixed size to a region. - * - * @param region the region. - * @param size the size. - */ - public static void setFixedSize(@NotNull Region region, @NotNull Point2D size) { - setFixedSize(region, size.getX(), size.getY()); - } + width.bind(value); + + return region; + } + + /** + * Add a random color to background. + * + * @param node the node. + */ + public static void addDebugBackgroundColor(@NotNull Node node) { + + var random = ThreadLocalRandom.current(); + var color = "rgb(" + random.nextInt(255) + "," + random.nextInt(255) + ", " + random.nextInt(255) + ")"; + + node.setStyle("-fx-background-color: " + color + ";"); + } + + /** + * Add a debug border to a node.. + * + * @param node the node. + */ + public static void addDebugBorderTo(@NotNull Node node) { + node.setStyle("-fx-border-color: red; -fx-border-width: 3px;"); + } + + /** + * Set fixed size to a region. + * + * @param region the region. + * @param width the width. + * @param height the height. + */ + public static void setFixedSize(@NotNull Region region, double width, double height) { + region.setMaxHeight(height); + region.setMinHeight(height); + region.setMaxWidth(width); + region.setMinWidth(width); + } + + /** + * Set fixed size to a region. + * + * @param region the region. + * @param size the size. + */ + public static void setFixedSize(@NotNull Region region, @NotNull Point size) { + setFixedSize(region, size.getX(), size.getY()); + } + + /** + * Set fixed size to a region. + * + * @param region the region. + * @param size the size. + */ + public static void setFixedSize(@NotNull Region region, @NotNull Point2D size) { + setFixedSize(region, size.getX(), size.getY()); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java index c740e88e..72c6962f 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java @@ -16,249 +16,238 @@ */ public class ObservableUtils { - public static class ChangeEventAppender implements AutoCloseable { + public static class ChangeEventAppender implements AutoCloseable { - private ObservableValue value; + private ObservableValue value; - public void complete() { - value = null; - } - - /** - * Add on change event handler. - * - * @param action the action on changes. - * @return the change event appender. - */ - public ChangeEventAppender onChange(@NotNull Runnable action) { - value.addListener((observable, oldValue, newValue) -> action.run()); - return this; - } - - /** - * Add on change event handler. - * - * @param predicate the condition to use the consumer. - * @param action the action on changes. - * @return the change event appender. - */ - public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNull Runnable action) { - - value.addListener((observable, oldValue, newValue) -> { - if (predicate.test(newValue)) { - action.run(); - } - }); - - return this; - } - - /** - * Add on change event handler. - * - * @param consumer the consumer to handle new values. - * @return the change event appender. - */ - public ChangeEventAppender onChange(@NotNull Consumer consumer) { - value.addListener((observable, oldValue, newValue) -> consumer.accept(newValue)); - return this; - } - - /** - * Add on change event handler. - * - * @param predicate the condition to use the consumer. - * @param consumer the consumer to handle new values. - * @return the change event appender. - */ - public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNull Consumer consumer) { - - value.addListener((observable, oldValue, newValue) -> { - if (predicate.test(newValue)) { - consumer.accept(newValue); - } - }); - - return this; - } - - /** - * Add on change event handler. - * - * @param consumer the consumer to handle new values. - * @return the change event appender. - */ - public ChangeEventAppender onChange(@NotNull BiConsumer consumer) { - value.addListener((observable, oldValue, newValue) -> consumer.accept(oldValue, newValue)); - return this; - } - - /** - * Add on change event handler. - * - * @param predicate the condition to use the consumer. - * @param consumer the consumer to handle new values. - * @return the change event appender. - */ - public ChangeEventAppender onChangeIf( - @NotNull BiPredicate predicate, - @NotNull BiConsumer consumer - ) { - - value.addListener((observable, oldValue, newValue) -> { - if (predicate.test(oldValue, newValue)) { - consumer.accept(oldValue, newValue); - } - }); - - return this; - } - - @Override - public void close() throws Exception { - value = null; - } - } - - private static final ThreadLocal CHANGE_EVENT_APPENDER = - ThreadLocal.withInitial(ChangeEventAppender::new); - - private static @NotNull ChangeEventAppender getAppender(@NotNull ObservableValue value) { - - ChangeEventAppender appender = unsafeCast(CHANGE_EVENT_APPENDER.get()); - appender.value = value; - - return appender; + public void complete() { + value = null; } /** * Add on change event handler. * - * @param value the observable value. * @param action the action on changes. - * @param the value type. * @return the change event appender. */ - public static @NotNull ChangeEventAppender onChange( - @NotNull ObservableValue value, - @NotNull Runnable action - ) { - value.addListener((observable, oldValue, newValue) -> action.run()); - return getAppender(value); + public ChangeEventAppender onChange(@NotNull Runnable action) { + value.addListener((observable, oldValue, newValue) -> action.run()); + return this; } /** * Add on change event handler. * - * @param value the observable value. * @param predicate the condition to use the consumer. - * @param action the action on changes. - * @param the value type. + * @param action the action on changes. * @return the change event appender. */ - public static ChangeEventAppender onChangeIf( - @NotNull ObservableValue value, - @NotNull Predicate predicate, - @NotNull Runnable action - ) { - - value.addListener((observable, oldValue, newValue) -> { - if (predicate.test(newValue)) { - action.run(); - } - }); - - return getAppender(value); + public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNull Runnable action) { + + value.addListener((observable, oldValue, newValue) -> { + if (predicate.test(newValue)) { + action.run(); + } + }); + + return this; } /** * Add on change event handler. * - * @param value the observable value. * @param consumer the consumer to handle new values. - * @param the value type. * @return the change event appender. */ - public static ChangeEventAppender onChange( - @NotNull ObservableValue value, - @NotNull Consumer consumer - ) { - value.addListener((observable, oldValue, newValue) -> consumer.accept(newValue)); - return getAppender(value); + public ChangeEventAppender onChange(@NotNull Consumer consumer) { + value.addListener((observable, oldValue, newValue) -> consumer.accept(newValue)); + return this; } /** * Add on change event handler. * - * @param value the observable value. * @param predicate the condition to use the consumer. - * @param consumer the consumer to handle new values. - * @param the value type. + * @param consumer the consumer to handle new values. * @return the change event appender. */ - public static ChangeEventAppender onChangeIf( - @NotNull ObservableValue value, - @NotNull Predicate predicate, - @NotNull Consumer consumer - ) { - - value.addListener((observable, oldValue, newValue) -> { - if (predicate.test(newValue)) { - consumer.accept(newValue); - } - }); - - return getAppender(value); - } + public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNull Consumer consumer) { - /** - * Start building change handlers. - * - * @param value the observable value. - * @param the value type. - * @return the change event appender. - */ - public static ChangeEventAppender onChanges(@NotNull ObservableValue value) { - return getAppender(value); + value.addListener((observable, oldValue, newValue) -> { + if (predicate.test(newValue)) { + consumer.accept(newValue); + } + }); + + return this; } /** * Add on change event handler. * - * @param value the observable value. * @param consumer the consumer to handle new values. - * @param the value type. * @return the change event appender. */ - public static ChangeEventAppender onChange( - @NotNull ObservableValue value, - @NotNull BiConsumer consumer - ) { - value.addListener((observable, oldValue, newValue) -> consumer.accept(oldValue, newValue)); - return getAppender(value); + public ChangeEventAppender onChange(@NotNull BiConsumer consumer) { + value.addListener((observable, oldValue, newValue) -> consumer.accept(oldValue, newValue)); + return this; } /** * Add on change event handler. * - * @param value the observable value. * @param predicate the condition to use the consumer. - * @param consumer the consumer to handle new values. - * @param the value type. + * @param consumer the consumer to handle new values. * @return the change event appender. */ - public static ChangeEventAppender onChangeIf( - @NotNull ObservableValue value, - @NotNull BiPredicate predicate, - @NotNull BiConsumer consumer - ) { - - value.addListener((observable, oldValue, newValue) -> { - if (predicate.test(oldValue, newValue)) { - consumer.accept(oldValue, newValue); - } - }); - - return getAppender(value); + public ChangeEventAppender onChangeIf(@NotNull BiPredicate predicate, @NotNull BiConsumer consumer) { + + value.addListener((observable, oldValue, newValue) -> { + if (predicate.test(oldValue, newValue)) { + consumer.accept(oldValue, newValue); + } + }); + + return this; + } + + @Override + public void close() throws Exception { + value = null; } + } + + private static final ThreadLocal CHANGE_EVENT_APPENDER = ThreadLocal.withInitial( + ChangeEventAppender::new); + + private static @NotNull ChangeEventAppender getAppender(@NotNull ObservableValue value) { + + ChangeEventAppender appender = unsafeCast(CHANGE_EVENT_APPENDER.get()); + appender.value = value; + + return appender; + } + + /** + * Add on change event handler. + * + * @param value the observable value. + * @param action the action on changes. + * @param the value type. + * @return the change event appender. + */ + public static @NotNull ChangeEventAppender onChange( + @NotNull ObservableValue value, + @NotNull Runnable action) { + value.addListener((observable, oldValue, newValue) -> action.run()); + return getAppender(value); + } + + /** + * Add on change event handler. + * + * @param value the observable value. + * @param predicate the condition to use the consumer. + * @param action the action on changes. + * @param the value type. + * @return the change event appender. + */ + public static ChangeEventAppender onChangeIf( + @NotNull ObservableValue value, + @NotNull Predicate predicate, + @NotNull Runnable action) { + + value.addListener((observable, oldValue, newValue) -> { + if (predicate.test(newValue)) { + action.run(); + } + }); + + return getAppender(value); + } + + /** + * Add on change event handler. + * + * @param value the observable value. + * @param consumer the consumer to handle new values. + * @param the value type. + * @return the change event appender. + */ + public static ChangeEventAppender onChange(@NotNull ObservableValue value, @NotNull Consumer consumer) { + value.addListener((observable, oldValue, newValue) -> consumer.accept(newValue)); + return getAppender(value); + } + + /** + * Add on change event handler. + * + * @param value the observable value. + * @param predicate the condition to use the consumer. + * @param consumer the consumer to handle new values. + * @param the value type. + * @return the change event appender. + */ + public static ChangeEventAppender onChangeIf( + @NotNull ObservableValue value, + @NotNull Predicate predicate, + @NotNull Consumer consumer) { + + value.addListener((observable, oldValue, newValue) -> { + if (predicate.test(newValue)) { + consumer.accept(newValue); + } + }); + + return getAppender(value); + } + + /** + * Start building change handlers. + * + * @param value the observable value. + * @param the value type. + * @return the change event appender. + */ + public static ChangeEventAppender onChanges(@NotNull ObservableValue value) { + return getAppender(value); + } + + /** + * Add on change event handler. + * + * @param value the observable value. + * @param consumer the consumer to handle new values. + * @param the value type. + * @return the change event appender. + */ + public static ChangeEventAppender onChange( + @NotNull ObservableValue value, + @NotNull BiConsumer consumer) { + value.addListener((observable, oldValue, newValue) -> consumer.accept(oldValue, newValue)); + return getAppender(value); + } + + /** + * Add on change event handler. + * + * @param value the observable value. + * @param predicate the condition to use the consumer. + * @param consumer the consumer to handle new values. + * @param the value type. + * @return the change event appender. + */ + public static ChangeEventAppender onChangeIf( + @NotNull ObservableValue value, + @NotNull BiPredicate predicate, + @NotNull BiConsumer consumer) { + + value.addListener((observable, oldValue, newValue) -> { + if (predicate.test(oldValue, newValue)) { + consumer.accept(oldValue, newValue); + } + }); + + return getAppender(value); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java index 3f98edb0..16600baf 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java @@ -12,32 +12,32 @@ */ public class FloatArrayStringConverter extends StringConverter { - @Override - public float[] fromString(@Nullable String string) { + @Override + public float[] fromString(@Nullable String string) { - float[] newValue = null; + float[] newValue = null; - if (!StringUtils.isEmpty(string)) { + if (!StringUtils.isEmpty(string)) { - var splitter = string.contains(" ") ? " " : ","; - var split = string.split(splitter); + var splitter = string.contains(" ") ? " " : ","; + var split = string.split(splitter); - newValue = new float[split.length]; + newValue = new float[split.length]; - for (var i = 0; i < split.length; i++) { - newValue[i] = Float.parseFloat(split[i]); - } - } - - return newValue; + for (var i = 0; i < split.length; i++) { + newValue[i] = Float.parseFloat(split[i]); + } } - @Override - public @Nullable String toString(@Nullable float[] value) { - if (ArrayUtils.isEmpty(value)) { - return StringUtils.EMPTY; - } else { - return ArrayUtils.toString(value, " ", false, false); - } + return newValue; + } + + @Override + public @Nullable String toString(@Nullable float[] value) { + if (ArrayUtils.isEmpty(value)) { + return StringUtils.EMPTY; + } else { + return ArrayUtils.toString(value, " ", false, false); } + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java index 7f7dba70..76f9fbfb 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java @@ -12,32 +12,32 @@ */ public class IntegerArrayStringConverter extends StringConverter { - @Override - public int[] fromString(@Nullable String string) { + @Override + public int[] fromString(@Nullable String string) { - int[] newValue = null; + int[] newValue = null; - if (!StringUtils.isEmpty(string)) { + if (!StringUtils.isEmpty(string)) { - var splitter = string.contains(" ") ? " " : ","; - var split = string.split(splitter); + var splitter = string.contains(" ") ? " " : ","; + var split = string.split(splitter); - newValue = new int[split.length]; + newValue = new int[split.length]; - for (var i = 0; i < split.length; i++) { - newValue[i] = Integer.parseInt(split[i]); - } - } - - return newValue; + for (var i = 0; i < split.length; i++) { + newValue[i] = Integer.parseInt(split[i]); + } } - @Override - public @Nullable String toString(@Nullable int[] value) { - if (ArrayUtils.isEmpty(value)) { - return StringUtils.EMPTY; - } else { - return ArrayUtils.toString(value, " ", false, false); - } + return newValue; + } + + @Override + public @Nullable String toString(@Nullable int[] value) { + if (ArrayUtils.isEmpty(value)) { + return StringUtils.EMPTY; + } else { + return ArrayUtils.toString(value, " ", false, false); } + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java index eda7666a..c6807222 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java @@ -10,23 +10,23 @@ */ public class LimitedFloatStringConverter extends LimitedNumberStringConverter { - @Override - public @Nullable Float fromString(@Nullable String value) { + @Override + public @Nullable Float fromString(@Nullable String value) { - if (StringUtils.isEmpty(value)) { - return null; - } - - var result = Float.valueOf(value); - var minValue = getMinValue(); - var maxValue = getMaxValue(); + if (StringUtils.isEmpty(value)) { + return null; + } - if (minValue != null && result < minValue) { - throw new IllegalArgumentException(); - } else if (maxValue != null && result > maxValue) { - throw new IllegalArgumentException(); - } + var result = Float.valueOf(value); + var minValue = getMinValue(); + var maxValue = getMaxValue(); - return result; + if (minValue != null && result < minValue) { + throw new IllegalArgumentException(); + } else if (maxValue != null && result > maxValue) { + throw new IllegalArgumentException(); } + + return result; + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java index 1743166c..34e8081c 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java @@ -10,33 +10,33 @@ */ public class LimitedIntegerStringConverter extends LimitedNumberStringConverter { - @Override - public @Nullable Integer fromString(@Nullable String value) { + @Override + public @Nullable Integer fromString(@Nullable String value) { - if (StringUtils.isEmpty(value)) { - return null; - } - - var result = Integer.valueOf(value); - var minValue = getMinValue(); - var maxValue = getMaxValue(); + if (StringUtils.isEmpty(value)) { + return null; + } - if (minValue != null && result < minValue) { - throw new IllegalArgumentException(); - } else if (maxValue != null && result > getMaxValue()) { - throw new IllegalArgumentException(); - } + var result = Integer.valueOf(value); + var minValue = getMinValue(); + var maxValue = getMaxValue(); - return result; + if (minValue != null && result < minValue) { + throw new IllegalArgumentException(); + } else if (maxValue != null && result > getMaxValue()) { + throw new IllegalArgumentException(); } - @Override - public @Nullable String toString(@Nullable Integer value) { + return result; + } - if (value == null) { - return StringUtils.EMPTY; - } + @Override + public @Nullable String toString(@Nullable Integer value) { - return Integer.toString(value); + if (value == null) { + return StringUtils.EMPTY; } + + return Integer.toString(value); + } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java index 1df95f16..79458c71 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java @@ -12,70 +12,70 @@ */ public abstract class LimitedNumberStringConverter extends StringConverter { - /** - * The min value. - */ - @Nullable - private T minValue; + /** + * The min value. + */ + @Nullable + private T minValue; - /** - * The max value. - */ - @Nullable - private T maxValue; + /** + * The max value. + */ + @Nullable + private T maxValue; - public LimitedNumberStringConverter() { - this.maxValue = null; - this.minValue = null; - } + public LimitedNumberStringConverter() { + this.maxValue = null; + this.minValue = null; + } - public LimitedNumberStringConverter(@NotNull T minValue, @NotNull T maxValue) { - this.maxValue = minValue; - this.minValue = maxValue; - } + public LimitedNumberStringConverter(@NotNull T minValue, @NotNull T maxValue) { + this.maxValue = minValue; + this.minValue = maxValue; + } - /** - * Get the max value. - * - * @return the max value. - */ - public @Nullable T getMaxValue() { - return maxValue; - } + /** + * Get the max value. + * + * @return the max value. + */ + public @Nullable T getMaxValue() { + return maxValue; + } - /** - * Set the max value. - * - * @param maxValue the max value. - */ - public void setMaxValue(@Nullable T maxValue) { - this.maxValue = maxValue; - } + /** + * Set the max value. + * + * @param maxValue the max value. + */ + public void setMaxValue(@Nullable T maxValue) { + this.maxValue = maxValue; + } - /** - * Get the min value. - * - * @return the min value. - */ - public @Nullable T getMinValue() { - return minValue; - } + /** + * Get the min value. + * + * @return the min value. + */ + public @Nullable T getMinValue() { + return minValue; + } - /** - * Set the min value. - * - * @param minValue the min value. - */ - public void setMinValue(@Nullable T minValue) { - this.minValue = minValue; - } + /** + * Set the min value. + * + * @param minValue the min value. + */ + public void setMinValue(@Nullable T minValue) { + this.minValue = minValue; + } - @Override - public @Nullable String toString(@Nullable T value) { - if (value == null) { - return StringUtils.EMPTY; - } else { - return String.valueOf(value); - } + @Override + public @Nullable String toString(@Nullable T value) { + if (value == null) { + return StringUtils.EMPTY; + } else { + return String.valueOf(value); } + } } diff --git a/rlib-fx/src/main/resources/com/ss/rlib/fx/css/classes.css b/rlib-fx/src/main/resources/com/ss/rlib/fx/css/classes.css index 92273084..42e624b0 100644 --- a/rlib-fx/src/main/resources/com/ss/rlib/fx/css/classes.css +++ b/rlib-fx/src/main/resources/com/ss/rlib/fx/css/classes.css @@ -85,6 +85,7 @@ -fx-border-width: 0px; -fx-text-fill: white; } + .control-dialog > .dialog-actions > .button-action:pressed { -fx-background-color: black; -fx-background-radius: 0px; diff --git a/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java b/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java index 788ee27c..42a2328d 100644 --- a/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java +++ b/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java @@ -17,74 +17,78 @@ public class SimpleControlDialogTest extends Application { - private static class TestDialog extends DefaultControlDialog { + private static class TestDialog extends DefaultControlDialog { - @Override - protected void fillContent(@NotNull GridPane content) { - super.fillContent(content); - - var textArea = new TextArea("This is a text area."); - textArea.prefWidthProperty() - .bind(content.widthProperty()); - textArea.prefHeightProperty() - .bind(content.heightProperty()); - - content.add(textArea, 0, 0); - } + @Override + protected void fillContent(@NotNull GridPane content) { + super.fillContent(content); + + var textArea = new TextArea("This is a text area."); + textArea + .prefWidthProperty() + .bind(content.widthProperty()); + textArea + .prefHeightProperty() + .bind(content.heightProperty()); + + content.add(textArea, 0, 0); + } - @Override - protected void fillActions(@NotNull GridPane actions) { - super.fillActions(actions); + @Override + protected void fillActions(@NotNull GridPane actions) { + super.fillActions(actions); - var okButton = new Button("Ok"); - var cancelButton = new Button("Cancel"); + var okButton = new Button("Ok"); + var cancelButton = new Button("Cancel"); - actions.add(okButton, 0, 0); - actions.add(cancelButton, 1, 0); + actions.add(okButton, 0, 0); + actions.add(cancelButton, 1, 0); - FxUtils.addClass(okButton, CssClasses.BUTTON_ACTION) - .addClass(cancelButton, CssClasses.BUTTON_ACTION); - } + FxUtils + .addClass(okButton, CssClasses.BUTTON_ACTION) + .addClass(cancelButton, CssClasses.BUTTON_ACTION); } + } - @Override - public void start(@NotNull Stage stage) { + @Override + public void start(@NotNull Stage stage) { - var root = new VBox(); - root.setAlignment(Pos.CENTER); + var root = new VBox(); + root.setAlignment(Pos.CENTER); - var scene = new Scene(root); - scene.getStylesheets() - .add(CssClasses.CSS_FILE); + var scene = new Scene(root); + scene + .getStylesheets() + .add(CssClasses.CSS_FILE); - var button = new Button("Create a dialog in scene's center"); - button.setOnAction(event -> openInCenterDialog(scene)); + var button = new Button("Create a dialog in scene's center"); + button.setOnAction(event -> openInCenterDialog(scene)); - var button2 = new Button("Create a dialog over this button"); - button2.setOnAction(event -> openOverNode(button2)); + var button2 = new Button("Create a dialog over this button"); + button2.setOnAction(event -> openOverNode(button2)); - var emptyPane = new Pane(); - emptyPane.setMinHeight(300); + var emptyPane = new Pane(); + emptyPane.setMinHeight(300); - FxUtils.addChild(root, button, emptyPane, button2); + FxUtils.addChild(root, button, emptyPane, button2); - ControlDialogSupport.addSupport(scene); + ControlDialogSupport.addSupport(scene); - stage.setScene(scene); - stage.setWidth(1024); - stage.setHeight(768); - stage.show(); - } + stage.setScene(scene); + stage.setWidth(1024); + stage.setHeight(768); + stage.show(); + } - private void openInCenterDialog(@NotNull Scene scene) { - var dialog = new TestDialog(); - dialog.applySize(200, 200); - dialog.show(scene); - } + private void openInCenterDialog(@NotNull Scene scene) { + var dialog = new TestDialog(); + dialog.applySize(200, 200); + dialog.show(scene); + } - private void openOverNode(@NotNull Node node) { - var dialog = new TestDialog(); - dialog.applySize(200, 200); - dialog.show(node); - } + private void openOverNode(@NotNull Node node) { + var dialog = new TestDialog(); + dialog.applySize(200, 200); + dialog.show(node); + } } diff --git a/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java b/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java index 0f1f0b4d..482645ac 100644 --- a/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java +++ b/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java @@ -11,27 +11,28 @@ public class SimplePopupDialogTest extends Application { - @Override - public void start(@NotNull Stage stage) throws Exception { - - var root = new StackPane(); - var scene = new Scene(root); - scene.getStylesheets() - .add(CssClasses.CSS_FILE); - - var button = new Button("Create a dialog"); - button.setOnAction(event -> openDialog(stage)); - - FxUtils.addChild(root, button); - - stage.setScene(scene); - stage.setWidth(1024); - stage.setHeight(768); - stage.show(); - } - - private void openDialog(@NotNull Stage window) { - SimplePopupDialog dialog = new SimplePopupDialog(); - dialog.show(window); - } + @Override + public void start(@NotNull Stage stage) throws Exception { + + var root = new StackPane(); + var scene = new Scene(root); + scene + .getStylesheets() + .add(CssClasses.CSS_FILE); + + var button = new Button("Create a dialog"); + button.setOnAction(event -> openDialog(stage)); + + FxUtils.addChild(root, button); + + stage.setScene(scene); + stage.setWidth(1024); + stage.setHeight(768); + stage.show(); + } + + private void openDialog(@NotNull Stage window) { + SimplePopupDialog dialog = new SimplePopupDialog(); + dialog.show(window); + } } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java index 230abc4b..070ec2a6 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java @@ -10,468 +10,435 @@ */ public interface Logger { - @FunctionalInterface - interface Factory { - - @NotNull String make(); - } - - @FunctionalInterface - interface SinFactory { - - @NotNull String make(@NotNull F first); - } - - @FunctionalInterface - interface IntSinFactory { - - @NotNull String make(int val); - } - - @FunctionalInterface - interface BiFactory { - - @NotNull String make(@NotNull F first, @NotNull S second); - } - - @FunctionalInterface - interface NullableBiFactory { - - @NotNull String make(@Nullable F first, @Nullable S second); - } - - @FunctionalInterface - interface ObjIntFactory { - - @NotNull String make(@NotNull F first, int second); - } - - @FunctionalInterface - interface IntBiFactory { - - @NotNull String make(int first, int second); - } - - @FunctionalInterface - interface TriFactory { - - @NotNull String make(@NotNull F first, @NotNull S second, @NotNull T third); - } - - /** - * Print the debug message. - * - * @param message the message. - */ - default void debug(@NotNull String message) { - print(LoggerLevel.DEBUG, message); - } - - /** - * Print a build debug message. - * - * @param arg the arg for the message factory. - * @param messageFactory the message factory. - */ - default void debug(int arg, @NotNull Logger.IntSinFactory messageFactory) { - print(LoggerLevel.DEBUG, arg, messageFactory); - } - - /** - * Print a build debug message. - * - * @param arg the arg for the message factory. - * @param messageFactory the message factory. - * @param the argument's type. - */ - default void debug(@NotNull T arg, @NotNull Logger.SinFactory messageFactory) { - print(LoggerLevel.DEBUG, arg, messageFactory); - } - - /** - * Print a build debug message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - */ - default void debug( - @NotNull F first, - @NotNull S second, - @NotNull Logger.BiFactory messageFactory - ) { - print(LoggerLevel.DEBUG, first, second, messageFactory); - } - - /** - * Print a build debug message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - */ - default void debugNullable( - @Nullable F first, - @Nullable S second, - @NotNull Logger.NullableBiFactory messageFactory - ) { - print(LoggerLevel.DEBUG, first, second, messageFactory); - } - - /** - * Print a build debug message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - */ - default void debug( - @NotNull F first, - int second, - @NotNull Logger.ObjIntFactory messageFactory - ) { - print(LoggerLevel.DEBUG, first, second, messageFactory); - } - - /** - * Print a build debug message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - */ - default void debug(int first, int second, @NotNull Logger.IntBiFactory messageFactory) { - print(LoggerLevel.DEBUG, first, second, messageFactory); - } - - /** - * Print a build debug message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param third the third arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - * @param the third argument's type. - */ - default void debug( - @NotNull F first, - @NotNull S second, - @NotNull T third, - @NotNull Logger.TriFactory messageFactory - ) { - print(LoggerLevel.DEBUG, first, second, third, messageFactory); - } - - /** - * Print a build error message. - * - * @param message the message. - */ - default void error(@NotNull String message) { - print(LoggerLevel.ERROR, message); - } - - /** - * Print a build error message. - * - * @param exception the exception. - */ - default void error(@NotNull Throwable exception) { - print(LoggerLevel.ERROR, exception); - } - - /** - * Print a build information message. - * - * @param message the message. - */ - default void info(@NotNull String message) { - print(LoggerLevel.INFO, message); - } - - /** - * Print a build information message. - * - * @param arg the arg for the message factory. - * @param messageFactory the message factory. - * @param the argument's type. - */ - default void info(@NotNull T arg, @NotNull Logger.SinFactory messageFactory) { - print(LoggerLevel.INFO, arg, messageFactory); - } - - /** - * Print a build information message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - */ - default void info( - @NotNull F first, - @NotNull S second, - @NotNull Logger.BiFactory messageFactory - ) { - print(LoggerLevel.INFO, first, second, messageFactory); - } - - - /** - * Print a build information message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param third the third arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - * @param the third argument's type. - */ - default void info( - @NotNull F first, - @NotNull S second, - @NotNull T third, - @NotNull Logger.TriFactory messageFactory - ) { - print(LoggerLevel.INFO, first, second, third, messageFactory); - } - - /** - * Check of enabling the logger level. - * - * @param level the logger level. - * @return true if the level is enabled. - */ - default boolean isEnabled(@NotNull LoggerLevel level) { - return level.isEnabled(); - } - - /** - * Override the enabling status of the logger level. - * - * @param level the logger level. - * @param enabled true if need to be enabled. - * @return true if the status was changed. - */ - default boolean setEnabled(@NotNull LoggerLevel level, boolean enabled) { - return false; - } - - /** - * Remove overriding of enabling status if the logger level. - * - * @param level the logger level. - * @return true if the status was changed. - */ - default boolean applyDefault(@NotNull LoggerLevel level) { - return false; - } - - /** - * Print the warning message. - * - * @param message the message. - */ - default void warning(@NotNull String message) { - print(LoggerLevel.WARNING, message); - } - - /** - * Print the warning message. - * - * @param exception the exception. - */ - default void warning(@NotNull Throwable exception) { - print(LoggerLevel.WARNING, exception); - } - - /** - * Print a warning debug message. - * - * @param arg the arg for the message factory. - * @param messageFactory the message factory. - * @param the argument's type. - */ - default void warning(@NotNull A arg, @NotNull Logger.SinFactory messageFactory) { - print(LoggerLevel.WARNING, arg, messageFactory); - } - - /** - * Print a warning debug message. - * - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - */ - default void warning( - @NotNull F first, - @NotNull S second, - @NotNull Logger.BiFactory messageFactory - ) { - print(LoggerLevel.WARNING, first, second, messageFactory); - } - - /** - * Print the message. - * - * @param level the level of the message. - * @param message the message. - */ - void print(@NotNull LoggerLevel level, @NotNull String message); - - /** - * Print the message. - * - * @param level the level of the message. - * @param exception the exception. - */ - void print(@NotNull LoggerLevel level, @NotNull Throwable exception); - - /** - * Print a build message. - * - * @param level the level of the message. - * @param arg the arg for the message factory. - * @param messageFactory the message factory. - * @param the argument's type. - */ - default void print( - @NotNull LoggerLevel level, - @NotNull T arg, - @NotNull Logger.SinFactory messageFactory - ) { - if (isEnabled(level)) { - print(level, messageFactory.make(arg)); - } - } - - /** - * Print a build message. - * - * @param level the level of the message. - * @param arg the arg for the message factory. - * @param messageFactory the message factory. - */ - default void print(@NotNull LoggerLevel level, int arg, @NotNull Logger.IntSinFactory messageFactory) { - if (isEnabled(level)) { - print(level, messageFactory.make(arg)); - } - } - - /** - * Print a build message. - * - * @param level the level of the message. - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - */ - default void print( - @NotNull LoggerLevel level, - @NotNull F first, - @NotNull S second, - @NotNull Logger.BiFactory messageFactory - ) { - if (isEnabled(level)) { - print(level, messageFactory.make(first, second)); - } - } - - /** - * Print a build message. - * - * @param level the level of the message. - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - */ - default void print( - @NotNull LoggerLevel level, - @Nullable F first, - @Nullable S second, - @NotNull Logger.NullableBiFactory messageFactory - ) { - if (isEnabled(level)) { - print(level, messageFactory.make(first, second)); - } - } - - /** - * Print a build message. - * - * @param level the level of the message. - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - */ - default void print( - @NotNull LoggerLevel level, - @NotNull F first, - int second, - @NotNull Logger.ObjIntFactory messageFactory - ) { - if (isEnabled(level)) { - print(level, messageFactory.make(first, second)); - } - } - - /** - * Print a build message. - * - * @param level the level of the message. - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param messageFactory the message factory. - */ - default void print( - @NotNull LoggerLevel level, - int first, - int second, - @NotNull Logger.IntBiFactory messageFactory - ) { - if (isEnabled(level)) { - print(level, messageFactory.make(first, second)); - } - } - - /** - * Print a build message. - * - * @param level the level of the message. - * @param first the first arg for the message factory. - * @param second the second arg for the message factory. - * @param third the third arg for the message factory. - * @param messageFactory the message factory. - * @param the first argument's type. - * @param the second argument's type. - * @param the third argument's type. - */ - default void print( - @NotNull LoggerLevel level, - @NotNull F first, - @NotNull S second, - @NotNull T third, - @NotNull Logger.TriFactory messageFactory - ) { - - if (isEnabled(level)) { - print(level, messageFactory.make(first, second, third)); - } - } + @FunctionalInterface + interface Factory { + + @NotNull String make(); + } + + @FunctionalInterface + interface SinFactory { + + @NotNull String make(@NotNull F first); + } + + @FunctionalInterface + interface IntSinFactory { + + @NotNull String make(int val); + } + + @FunctionalInterface + interface BiFactory { + + @NotNull String make(@NotNull F first, @NotNull S second); + } + + @FunctionalInterface + interface NullableBiFactory { + + @NotNull String make(@Nullable F first, @Nullable S second); + } + + @FunctionalInterface + interface ObjIntFactory { + + @NotNull String make(@NotNull F first, int second); + } + + @FunctionalInterface + interface IntBiFactory { + + @NotNull String make(int first, int second); + } + + @FunctionalInterface + interface TriFactory { + + @NotNull String make(@NotNull F first, @NotNull S second, @NotNull T third); + } + + /** + * Print the debug message. + * + * @param message the message. + */ + default void debug(@NotNull String message) { + print(LoggerLevel.DEBUG, message); + } + + /** + * Print a build debug message. + * + * @param arg the arg for the message factory. + * @param messageFactory the message factory. + */ + default void debug(int arg, @NotNull Logger.IntSinFactory messageFactory) { + print(LoggerLevel.DEBUG, arg, messageFactory); + } + + /** + * Print a build debug message. + * + * @param arg the arg for the message factory. + * @param messageFactory the message factory. + * @param the argument's type. + */ + default void debug(@NotNull T arg, @NotNull Logger.SinFactory messageFactory) { + print(LoggerLevel.DEBUG, arg, messageFactory); + } + + /** + * Print a build debug message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + */ + default void debug(@NotNull F first, @NotNull S second, @NotNull Logger.BiFactory messageFactory) { + print(LoggerLevel.DEBUG, first, second, messageFactory); + } + + /** + * Print a build debug message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + */ + default void debugNullable( + @Nullable F first, + @Nullable S second, + @NotNull Logger.NullableBiFactory messageFactory) { + print(LoggerLevel.DEBUG, first, second, messageFactory); + } + + /** + * Print a build debug message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + */ + default void debug(@NotNull F first, int second, @NotNull Logger.ObjIntFactory messageFactory) { + print(LoggerLevel.DEBUG, first, second, messageFactory); + } + + /** + * Print a build debug message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + */ + default void debug(int first, int second, @NotNull Logger.IntBiFactory messageFactory) { + print(LoggerLevel.DEBUG, first, second, messageFactory); + } + + /** + * Print a build debug message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param third the third arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + * @param the third argument's type. + */ + default void debug( + @NotNull F first, + @NotNull S second, + @NotNull T third, + @NotNull Logger.TriFactory messageFactory) { + print(LoggerLevel.DEBUG, first, second, third, messageFactory); + } + + /** + * Print a build error message. + * + * @param message the message. + */ + default void error(@NotNull String message) { + print(LoggerLevel.ERROR, message); + } + + /** + * Print a build error message. + * + * @param exception the exception. + */ + default void error(@NotNull Throwable exception) { + print(LoggerLevel.ERROR, exception); + } + + /** + * Print a build information message. + * + * @param message the message. + */ + default void info(@NotNull String message) { + print(LoggerLevel.INFO, message); + } + + /** + * Print a build information message. + * + * @param arg the arg for the message factory. + * @param messageFactory the message factory. + * @param the argument's type. + */ + default void info(@NotNull T arg, @NotNull Logger.SinFactory messageFactory) { + print(LoggerLevel.INFO, arg, messageFactory); + } + + /** + * Print a build information message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + */ + default void info(@NotNull F first, @NotNull S second, @NotNull Logger.BiFactory messageFactory) { + print(LoggerLevel.INFO, first, second, messageFactory); + } + + /** + * Print a build information message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param third the third arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + * @param the third argument's type. + */ + default void info( + @NotNull F first, + @NotNull S second, + @NotNull T third, + @NotNull Logger.TriFactory messageFactory) { + print(LoggerLevel.INFO, first, second, third, messageFactory); + } + + /** + * Check of enabling the logger level. + * + * @param level the logger level. + * @return true if the level is enabled. + */ + default boolean isEnabled(@NotNull LoggerLevel level) { + return level.isEnabled(); + } + + /** + * Override the enabling status of the logger level. + * + * @param level the logger level. + * @param enabled true if need to be enabled. + * @return true if the status was changed. + */ + default boolean setEnabled(@NotNull LoggerLevel level, boolean enabled) { + return false; + } + + /** + * Remove overriding of enabling status if the logger level. + * + * @param level the logger level. + * @return true if the status was changed. + */ + default boolean applyDefault(@NotNull LoggerLevel level) { + return false; + } + + /** + * Print the warning message. + * + * @param message the message. + */ + default void warning(@NotNull String message) { + print(LoggerLevel.WARNING, message); + } + + /** + * Print the warning message. + * + * @param exception the exception. + */ + default void warning(@NotNull Throwable exception) { + print(LoggerLevel.WARNING, exception); + } + + /** + * Print a warning debug message. + * + * @param arg the arg for the message factory. + * @param messageFactory the message factory. + * @param the argument's type. + */ + default void warning(@NotNull A arg, @NotNull Logger.SinFactory messageFactory) { + print(LoggerLevel.WARNING, arg, messageFactory); + } + + /** + * Print a warning debug message. + * + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + */ + default void warning(@NotNull F first, @NotNull S second, @NotNull Logger.BiFactory messageFactory) { + print(LoggerLevel.WARNING, first, second, messageFactory); + } + + /** + * Print the message. + * + * @param level the level of the message. + * @param message the message. + */ + void print(@NotNull LoggerLevel level, @NotNull String message); + + /** + * Print the message. + * + * @param level the level of the message. + * @param exception the exception. + */ + void print(@NotNull LoggerLevel level, @NotNull Throwable exception); + + /** + * Print a build message. + * + * @param level the level of the message. + * @param arg the arg for the message factory. + * @param messageFactory the message factory. + * @param the argument's type. + */ + default void print(@NotNull LoggerLevel level, @NotNull T arg, @NotNull Logger.SinFactory messageFactory) { + if (isEnabled(level)) { + print(level, messageFactory.make(arg)); + } + } + + /** + * Print a build message. + * + * @param level the level of the message. + * @param arg the arg for the message factory. + * @param messageFactory the message factory. + */ + default void print(@NotNull LoggerLevel level, int arg, @NotNull Logger.IntSinFactory messageFactory) { + if (isEnabled(level)) { + print(level, messageFactory.make(arg)); + } + } + + /** + * Print a build message. + * + * @param level the level of the message. + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + */ + default void print( + @NotNull LoggerLevel level, + @NotNull F first, + @NotNull S second, + @NotNull Logger.BiFactory messageFactory) { + if (isEnabled(level)) { + print(level, messageFactory.make(first, second)); + } + } + + /** + * Print a build message. + * + * @param level the level of the message. + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + */ + default void print( + @NotNull LoggerLevel level, + @Nullable F first, + @Nullable S second, + @NotNull Logger.NullableBiFactory messageFactory) { + if (isEnabled(level)) { + print(level, messageFactory.make(first, second)); + } + } + + /** + * Print a build message. + * + * @param level the level of the message. + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + */ + default void print( + @NotNull LoggerLevel level, + @NotNull F first, + int second, + @NotNull Logger.ObjIntFactory messageFactory) { + if (isEnabled(level)) { + print(level, messageFactory.make(first, second)); + } + } + + /** + * Print a build message. + * + * @param level the level of the message. + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param messageFactory the message factory. + */ + default void print(@NotNull LoggerLevel level, int first, int second, @NotNull Logger.IntBiFactory messageFactory) { + if (isEnabled(level)) { + print(level, messageFactory.make(first, second)); + } + } + + /** + * Print a build message. + * + * @param level the level of the message. + * @param first the first arg for the message factory. + * @param second the second arg for the message factory. + * @param third the third arg for the message factory. + * @param messageFactory the message factory. + * @param the first argument's type. + * @param the second argument's type. + * @param the third argument's type. + */ + default void print( + @NotNull LoggerLevel level, + @NotNull F first, + @NotNull S second, + @NotNull T third, + @NotNull Logger.TriFactory messageFactory) { + + if (isEnabled(level)) { + print(level, messageFactory.make(first, second, third)); + } + } } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java index 074308d4..8e357ac8 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java @@ -5,55 +5,54 @@ public interface LoggerFactory { - /** - * Make a new logger with the name. - * - * @param name the logger's name. - * @return the new logger. - */ - @NotNull Logger make(@NotNull String name); - - /** - * Make a new logger for the type. - * - * @param type the logger's type. - * @return the new logger. - */ - @NotNull Logger make(@NotNull Class type); - - /** - * Get a default logger. - * - * @return he default logger. - */ - @NotNull Logger getDefault(); - - /** - * Add the new listener. - * - * @param listener the new listener. - */ - void addListener(@NotNull LoggerListener listener); - - /** - * Add the new writer. - * - * @param writer the new writer. - */ - void addWriter(@NotNull Writer writer); - - - /** - * Remove the listener. - * - * @param listener the listener. - */ - void removeListener(@NotNull LoggerListener listener); - - /** - * Remove the writer. - * - * @param writer the writer. - */ - void removeWriter(@NotNull Writer writer); + /** + * Make a new logger with the name. + * + * @param name the logger's name. + * @return the new logger. + */ + @NotNull Logger make(@NotNull String name); + + /** + * Make a new logger for the type. + * + * @param type the logger's type. + * @return the new logger. + */ + @NotNull Logger make(@NotNull Class type); + + /** + * Get a default logger. + * + * @return he default logger. + */ + @NotNull Logger getDefault(); + + /** + * Add the new listener. + * + * @param listener the new listener. + */ + void addListener(@NotNull LoggerListener listener); + + /** + * Add the new writer. + * + * @param writer the new writer. + */ + void addWriter(@NotNull Writer writer); + + /** + * Remove the listener. + * + * @param listener the listener. + */ + void removeListener(@NotNull LoggerListener listener); + + /** + * Remove the writer. + * + * @param writer the writer. + */ + void removeWriter(@NotNull Writer writer); } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java index b9e4bac3..47fbb84e 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java @@ -11,51 +11,51 @@ */ @Getter public enum LoggerLevel { - /** - * Info logger level. - */ - INFO("INFO", false, true), - /** - * Debug logger level. - */ - DEBUG("DEBUG", false, false), - /** - * Warning logger level. - */ - WARNING("WARNING", true, true), - /** - * Error logger level. - */ - ERROR("ERROR", true, true); - - public static final int LENGTH = values().length; - - /** - * The level title. - */ - @Setter - @NotNull - private String title; - - /** - * The flag of activity. - */ - @Setter - private boolean enabled; - - /** - * The flag of force flushing. - */ - private boolean forceFlush; - - LoggerLevel(@NotNull String title, boolean forceFlush, boolean enabled) { - this.title = title; - this.forceFlush = forceFlush; - this.enabled = enabled; - } - - @Override - public String toString() { - return title; - } + /** + * Info logger level. + */ + INFO("INFO", false, true), + /** + * Debug logger level. + */ + DEBUG("DEBUG", false, false), + /** + * Warning logger level. + */ + WARNING("WARNING", true, true), + /** + * Error logger level. + */ + ERROR("ERROR", true, true); + + public static final int LENGTH = values().length; + + /** + * The level title. + */ + @Setter + @NotNull + private String title; + + /** + * The flag of activity. + */ + @Setter + private boolean enabled; + + /** + * The flag of force flushing. + */ + private boolean forceFlush; + + LoggerLevel(@NotNull String title, boolean forceFlush, boolean enabled) { + this.title = title; + this.forceFlush = forceFlush; + this.enabled = enabled; + } + + @Override + public String toString() { + return title; + } } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java index cb88ae3f..576eacf6 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java @@ -9,16 +9,16 @@ */ public interface LoggerListener { - /** - * Print the result logger message. - * - * @param text the text. - */ - void println(@NotNull String text); + /** + * Print the result logger message. + * + * @param text the text. + */ + void println(@NotNull String text); - /** - * Flush last data. - */ - default void flush() { - } + /** + * Flush last data. + */ + default void flush() { + } } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java index fccec09d..d4371f79 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java @@ -13,126 +13,131 @@ */ public class LoggerManager { - private static final LoggerFactory LOGGER_FACTORY; - - static { - - String className = System.getProperty("com.ss.rlib.logger.factory", ""); - - Class implementation = null; - - if (!className.isEmpty()) { - try { - implementation = (Class) Class.forName(className); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - if (implementation == null) { - - var impls = ServiceLoader.load(LoggerFactory.class) - .iterator(); - - if (impls.hasNext()) { - implementation = impls.next().getClass(); - } - } - - if (implementation == null) { - System.err.println("ERROR: No any exist implementation of Rlib Logger Factory, will use null logger"); - LOGGER_FACTORY = new NullLoggerFactory(); - } else { - try { - LOGGER_FACTORY = implementation.getDeclaredConstructor().newInstance(); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new RuntimeException(e); - } - } - } - - /** - * Add the new listener. - * - * @param listener the new listener. - */ - public static void addListener(@NotNull LoggerListener listener) { - LOGGER_FACTORY.addListener(listener); - } + private static final LoggerFactory LOGGER_FACTORY; - /** - * Add the new writer. - * - * @param writer the new writer. - */ - public static void addWriter(@NotNull Writer writer) { - LOGGER_FACTORY.addWriter(writer); - } + static { - /** - * Get the main logger. - * - * @return the main logger. - */ - public static @NotNull Logger getDefaultLogger() { - return LOGGER_FACTORY.getDefault(); - } + String className = System.getProperty("com.ss.rlib.logger.factory", ""); - /** - * Get or create a logger for the class. - * - * @param cs the class. - * @return the logger for the class. - */ - public static @NotNull Logger getLogger(@NotNull Class cs) { - return LOGGER_FACTORY.make(cs); - } + Class implementation = null; - /** - * Get or create a logger for the id. - * - * @param id the id. - * @return the logger for the class. - */ - public static @NotNull Logger getLogger(@NotNull String id) { - return LOGGER_FACTORY.make(id); + if (!className.isEmpty()) { + try { + implementation = (Class) Class.forName(className); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } } - /** - * Remove the listener. - * - * @param listener the listener. - */ - public static void removeListener(@NotNull LoggerListener listener) { - LOGGER_FACTORY.removeListener(listener); - } + if (implementation == null) { - /** - * Remove the writer. - * - * @param writer the writer. - */ - public static void removeWriter(@NotNull Writer writer) { - LOGGER_FACTORY.removeWriter(writer); - } + var impls = ServiceLoader + .load(LoggerFactory.class) + .iterator(); - /** - * Enable passed logger level for some logger. - * - * @param cs the class which use its own logger. - * @param level the logger level to enable. - */ - public static void enable(@NotNull Class cs, @NotNull LoggerLevel level) { - getLogger(cs).setEnabled(level, true); + if (impls.hasNext()) { + implementation = impls + .next() + .getClass(); + } } - /** - * Disable passed logger level for some logger. - * - * @param cs the class which use its own logger. - * @param level the logger level to disable. - */ - public static void disable(@NotNull Class cs, @NotNull LoggerLevel level) { - getLogger(cs).setEnabled(level, false); + if (implementation == null) { + System.err.println("ERROR: No any exist implementation of Rlib Logger Factory, will use null logger"); + LOGGER_FACTORY = new NullLoggerFactory(); + } else { + try { + LOGGER_FACTORY = implementation + .getDeclaredConstructor() + .newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new RuntimeException(e); + } } + } + + /** + * Add the new listener. + * + * @param listener the new listener. + */ + public static void addListener(@NotNull LoggerListener listener) { + LOGGER_FACTORY.addListener(listener); + } + + /** + * Add the new writer. + * + * @param writer the new writer. + */ + public static void addWriter(@NotNull Writer writer) { + LOGGER_FACTORY.addWriter(writer); + } + + /** + * Get the main logger. + * + * @return the main logger. + */ + public static @NotNull Logger getDefaultLogger() { + return LOGGER_FACTORY.getDefault(); + } + + /** + * Get or create a logger for the class. + * + * @param cs the class. + * @return the logger for the class. + */ + public static @NotNull Logger getLogger(@NotNull Class cs) { + return LOGGER_FACTORY.make(cs); + } + + /** + * Get or create a logger for the id. + * + * @param id the id. + * @return the logger for the class. + */ + public static @NotNull Logger getLogger(@NotNull String id) { + return LOGGER_FACTORY.make(id); + } + + /** + * Remove the listener. + * + * @param listener the listener. + */ + public static void removeListener(@NotNull LoggerListener listener) { + LOGGER_FACTORY.removeListener(listener); + } + + /** + * Remove the writer. + * + * @param writer the writer. + */ + public static void removeWriter(@NotNull Writer writer) { + LOGGER_FACTORY.removeWriter(writer); + } + + /** + * Enable passed logger level for some logger. + * + * @param cs the class which use its own logger. + * @param level the logger level to enable. + */ + public static void enable(@NotNull Class cs, @NotNull LoggerLevel level) { + getLogger(cs).setEnabled(level, true); + } + + /** + * Disable passed logger level for some logger. + * + * @param cs the class which use its own logger. + * @param level the logger level to disable. + */ + public static void disable(@NotNull Class cs, @NotNull LoggerLevel level) { + getLogger(cs).setEnabled(level, false); + } } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java index 6563706e..504eac73 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java @@ -6,13 +6,13 @@ public final class NullLogger implements Logger { - @Override - public void print(@NotNull LoggerLevel level, @NotNull String message) { + @Override + public void print(@NotNull LoggerLevel level, @NotNull String message) { - } + } - @Override - public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { + @Override + public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { - } + } } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java index dc454021..b3e8cd64 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java @@ -8,36 +8,36 @@ public class NullLoggerFactory implements LoggerFactory { - private static final NullLogger NULL_LOGGER = new NullLogger(); - - @Override - public @NotNull Logger make(@NotNull String name) { - return NULL_LOGGER; - } - - @Override - public @NotNull Logger make(@NotNull Class type) { - return NULL_LOGGER; - } - - @Override - public @NotNull Logger getDefault() { - return NULL_LOGGER; - } - - @Override - public void addListener(@NotNull LoggerListener listener) { - } - - @Override - public void addWriter(@NotNull Writer writer) { - } - - @Override - public void removeListener(@NotNull LoggerListener listener) { - } - - @Override - public void removeWriter(@NotNull Writer writer) { - } + private static final NullLogger NULL_LOGGER = new NullLogger(); + + @Override + public @NotNull Logger make(@NotNull String name) { + return NULL_LOGGER; + } + + @Override + public @NotNull Logger make(@NotNull Class type) { + return NULL_LOGGER; + } + + @Override + public @NotNull Logger getDefault() { + return NULL_LOGGER; + } + + @Override + public void addListener(@NotNull LoggerListener listener) { + } + + @Override + public void addWriter(@NotNull Writer writer) { + } + + @Override + public void removeListener(@NotNull LoggerListener listener) { + } + + @Override + public void removeWriter(@NotNull Writer writer) { + } } diff --git a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java index beca5fba..a17be515 100644 --- a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java +++ b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java @@ -13,58 +13,58 @@ */ public final class DefaultLogger implements Logger { - private static final LoggerLevel[] VALUES = LoggerLevel.values(); + private static final LoggerLevel[] VALUES = LoggerLevel.values(); - /** - * The table of override enabled statuses. - */ - private final Boolean[] override; + /** + * The table of override enabled statuses. + */ + private final Boolean[] override; - /** - * The logger name. - */ - private final String name; + /** + * The logger name. + */ + private final String name; - /** - * The default logger factory. - */ - private final DefaultLoggerFactory loggerFactory; + /** + * The default logger factory. + */ + private final DefaultLoggerFactory loggerFactory; - public DefaultLogger(@NotNull String name, @NotNull DefaultLoggerFactory loggerFactory) { - this.name = name; - this.loggerFactory = loggerFactory; - this.override = new Boolean[VALUES.length]; - } + public DefaultLogger(@NotNull String name, @NotNull DefaultLoggerFactory loggerFactory) { + this.name = name; + this.loggerFactory = loggerFactory; + this.override = new Boolean[VALUES.length]; + } - @Override - public boolean isEnabled(@NotNull LoggerLevel level) { - var value = override[level.ordinal()]; - return Objects.requireNonNullElse(value, level.isEnabled()); - } + @Override + public boolean isEnabled(@NotNull LoggerLevel level) { + var value = override[level.ordinal()]; + return Objects.requireNonNullElse(value, level.isEnabled()); + } - @Override - public boolean setEnabled(@NotNull LoggerLevel level, boolean enabled) { - override[level.ordinal()] = enabled; - return true; - } + @Override + public boolean setEnabled(@NotNull LoggerLevel level, boolean enabled) { + override[level.ordinal()] = enabled; + return true; + } - @Override - public boolean applyDefault(@NotNull LoggerLevel level) { - override[level.ordinal()] = null; - return true; - } + @Override + public boolean applyDefault(@NotNull LoggerLevel level) { + override[level.ordinal()] = null; + return true; + } - @Override - public void print(@NotNull LoggerLevel level, @NotNull String message) { - if (isEnabled(level)) { - loggerFactory.write(level, name, message); - } + @Override + public void print(@NotNull LoggerLevel level, @NotNull String message) { + if (isEnabled(level)) { + loggerFactory.write(level, name, message); } + } - @Override - public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { - if (isEnabled(level)) { - loggerFactory.write(level, name, StringUtils.toString(exception)); - } + @Override + public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { + if (isEnabled(level)) { + loggerFactory.write(level, name, StringUtils.toString(exception)); } + } } diff --git a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java index 5773f9c4..e693d2a6 100644 --- a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java +++ b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java @@ -23,124 +23,124 @@ */ public class DefaultLoggerFactory implements LoggerFactory { - /** - * The dictionary of all created loggers. - */ - private final @NotNull ConcurrentMap loggers; - - /** - * The main logger. - */ - private final @NotNull Logger logger; - - /** - * The list of listeners. - */ - private final @NotNull ConcurrentArray listeners; - - /** - * The list of writers. - */ - private final @NotNull ConcurrentArray writers; - - /** - * The date time formatter. - */ - private final @NotNull DateTimeFormatter timeFormatter; - - public DefaultLoggerFactory() { - this.loggers = new ConcurrentHashMap<>(); - this.logger = new DefaultLogger("", this); - this.timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss:SSS"); - this.listeners = ConcurrentArray.ofType(LoggerListener.class); - this.writers = ConcurrentArray.ofType(Writer.class); + /** + * The dictionary of all created loggers. + */ + private final @NotNull ConcurrentMap loggers; + + /** + * The main logger. + */ + private final @NotNull Logger logger; + + /** + * The list of listeners. + */ + private final @NotNull ConcurrentArray listeners; + + /** + * The list of writers. + */ + private final @NotNull ConcurrentArray writers; + + /** + * The date time formatter. + */ + private final @NotNull DateTimeFormatter timeFormatter; + + public DefaultLoggerFactory() { + this.loggers = new ConcurrentHashMap<>(); + this.logger = new DefaultLogger("", this); + this.timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss:SSS"); + this.listeners = ConcurrentArray.ofType(LoggerListener.class); + this.writers = ConcurrentArray.ofType(Writer.class); + } + + @Override + public void addListener(@NotNull LoggerListener listener) { + listeners.runInWriteLock(listener, Array::add); + } + + @Override + public void addWriter(@NotNull Writer writer) { + writers.runInWriteLock(writer, Array::add); + } + + @Override + public @NotNull Logger getDefault() { + return logger; + } + + @Override + public @NotNull Logger make(@NotNull Class type) { + return notNull(loggers.computeIfAbsent(type.getSimpleName(), name -> new DefaultLogger(name, this))); + } + + @Override + public @NotNull Logger make(@NotNull String name) { + return notNull(loggers.computeIfAbsent(name, str -> new DefaultLogger(str, this))); + } + + @Override + public void removeListener(@NotNull LoggerListener listener) { + listeners.runInWriteLock(listener, Array::remove); + } + + @Override + public void removeWriter(@NotNull Writer writer) { + writers.runInWriteLock(writer, Array::remove); + } + + /** + * Process of writing message to a console and writers. + * + * @param level the level of the message. + * @param name the name of owner. + * @param message the message. + */ + void write(@NotNull LoggerLevel level, @NotNull String name, @NotNull String message) { + + var timeStump = timeFormatter.format(LocalTime.now()); + var result = level.getTitle() + ' ' + timeStump + ' ' + name + ": " + message; + + write(level, result); + } + + /** + * Process of writing the result message. + * + * @param level the level of the result message. + * @param resultMessage the result message. + */ + private void write(@NotNull LoggerLevel level, @NotNull String resultMessage) { + + listeners.forEachInReadLockR(resultMessage, LoggerListener::println); + writers.forEachInReadLockR(resultMessage, DefaultLoggerFactory::append); + + System.err.println(resultMessage); + + if (!level.isForceFlush()) { + return; } - @Override - public void addListener(@NotNull LoggerListener listener) { - listeners.runInWriteLock(listener, Array::add); - } - - @Override - public void addWriter(@NotNull Writer writer) { - writers.runInWriteLock(writer, Array::add); - } - - @Override - public @NotNull Logger getDefault() { - return logger; - } - - @Override - public @NotNull Logger make(@NotNull Class type) { - return notNull(loggers.computeIfAbsent(type.getSimpleName(), name -> new DefaultLogger(name, this))); - } - - @Override - public @NotNull Logger make(@NotNull String name) { - return notNull(loggers.computeIfAbsent(name, str -> new DefaultLogger(str, this))); - } - - @Override - public void removeListener(@NotNull LoggerListener listener) { - listeners.runInWriteLock(listener, Array::remove); - } - - @Override - public void removeWriter(@NotNull Writer writer) { - writers.runInWriteLock(writer, Array::remove); - } - - /** - * Process of writing message to a console and writers. - * - * @param level the level of the message. - * @param name the name of owner. - * @param message the message. - */ - void write(@NotNull LoggerLevel level, @NotNull String name, @NotNull String message) { - - var timeStump = timeFormatter.format(LocalTime.now()); - var result = level.getTitle() + ' ' + timeStump + ' ' + name + ": " + message; - - write(level, result); - } - - /** - * Process of writing the result message. - * - * @param level the level of the result message. - * @param resultMessage the result message. - */ - private void write(@NotNull LoggerLevel level, @NotNull String resultMessage) { - - listeners.forEachInReadLockR(resultMessage, LoggerListener::println); - writers.forEachInReadLockR(resultMessage, DefaultLoggerFactory::append); - - System.err.println(resultMessage); - - if (!level.isForceFlush()) { - return; - } - - listeners.forEachInReadLock(LoggerListener::flush); - writers.forEachInReadLock(DefaultLoggerFactory::flush); - } + listeners.forEachInReadLock(LoggerListener::flush); + writers.forEachInReadLock(DefaultLoggerFactory::flush); + } - private static void append(@NotNull Writer writer, @NotNull String toWrite) { - try { - writer.append(toWrite); - writer.append('\n'); - } catch (IOException e) { - e.printStackTrace(); - } + private static void append(@NotNull Writer writer, @NotNull String toWrite) { + try { + writer.append(toWrite); + writer.append('\n'); + } catch (IOException e) { + e.printStackTrace(); } + } - private static void flush(@NotNull Writer writer) { - try { - writer.flush(); - } catch (IOException e) { - e.printStackTrace(); - } + private static void flush(@NotNull Writer writer) { + try { + writer.flush(); + } catch (IOException e) { + e.printStackTrace(); } + } } diff --git a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java index bcf6f38a..626290dd 100644 --- a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java +++ b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java @@ -18,65 +18,65 @@ */ public class FolderFileListener implements LoggerListener { - private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyy-MM-dd_HH-mm-ss"); + private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyy-MM-dd_HH-mm-ss"); - /** - * The folder with log files. - */ - @NotNull - private final Path folder; + /** + * The folder with log files. + */ + @NotNull + private final Path folder; - /** - * The current writer. - */ - private Writer writer; + /** + * The current writer. + */ + private Writer writer; - public FolderFileListener(@NotNull Path folder) { + public FolderFileListener(@NotNull Path folder) { - if (!Files.isDirectory(folder)) { - throw new IllegalArgumentException("file is not directory."); - } - - if (!Files.exists(folder)) { - try { - Files.createDirectories(folder); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - this.folder = folder; + if (!Files.isDirectory(folder)) { + throw new IllegalArgumentException("file is not directory."); + } + if (!Files.exists(folder)) { + try { + Files.createDirectories(folder); + } catch (IOException e) { + throw new UncheckedIOException(e); + } } - /** - * Get or create a writer. - * - * @return the writer. - * @throws IOException the io exception - */ - public @NotNull Writer getWriter() throws IOException { + this.folder = folder; + + } - if (writer == null) { + /** + * Get or create a writer. + * + * @return the writer. + * @throws IOException the io exception + */ + public @NotNull Writer getWriter() throws IOException { - var dateTime = LocalDateTime.now(); - var filename = TIME_FORMATTER.format(dateTime) + ".log"; + if (writer == null) { - writer = Files.newBufferedWriter(folder.resolve(filename), Charset.forName("UTF-8")); - } + var dateTime = LocalDateTime.now(); + var filename = TIME_FORMATTER.format(dateTime) + ".log"; - return writer; + writer = Files.newBufferedWriter(folder.resolve(filename), Charset.forName("UTF-8")); } - @Override - public void println(@NotNull String text) { - try { - var writer = getWriter(); - writer.append(text); - writer.append('\n'); - writer.flush(); - } catch (IOException e) { - e.printStackTrace(); - } + return writer; + } + + @Override + public void println(@NotNull String text) { + try { + var writer = getWriter(); + writer.append(text); + writer.append('\n'); + writer.flush(); + } catch (IOException e) { + e.printStackTrace(); } + } } diff --git a/rlib-logger-impl/src/test/java/javasabr/rlib/logger/impl/DefaultLoggerTest.java b/rlib-logger-impl/src/test/java/javasabr/rlib/logger/impl/DefaultLoggerTest.java index e77285de..a05a1cb4 100644 --- a/rlib-logger-impl/src/test/java/javasabr/rlib/logger/impl/DefaultLoggerTest.java +++ b/rlib-logger-impl/src/test/java/javasabr/rlib/logger/impl/DefaultLoggerTest.java @@ -13,44 +13,43 @@ public class DefaultLoggerTest { - private static final ConcurrentArray WROTE_DATA = ConcurrentArray.ofType(String.class); + private static final ConcurrentArray WROTE_DATA = ConcurrentArray.ofType(String.class); - private static final LoggerListener LOGGER_LISTENER = - text -> WROTE_DATA.runInWriteLock(strings -> strings.add(text)); + private static final LoggerListener LOGGER_LISTENER = text -> WROTE_DATA.runInWriteLock(strings -> strings.add(text)); - @BeforeAll - static void registerListener() { - LoggerManager.addListener(LOGGER_LISTENER); - } + @BeforeAll + static void registerListener() { + LoggerManager.addListener(LOGGER_LISTENER); + } - @AfterAll - static void unregisterListener() { - LoggerManager.addListener(LOGGER_LISTENER); - } + @AfterAll + static void unregisterListener() { + LoggerManager.addListener(LOGGER_LISTENER); + } - @BeforeEach - void clearWroteData() { - WROTE_DATA.runInWriteLock(Collection::clear); - } + @BeforeEach + void clearWroteData() { + WROTE_DATA.runInWriteLock(Collection::clear); + } - @Test - void shouldCreateDefaultLoggerImplementation() { + @Test + void shouldCreateDefaultLoggerImplementation() { - var logger = LoggerManager.getLogger(DefaultLoggerTest.class); + var logger = LoggerManager.getLogger(DefaultLoggerTest.class); - Assertions.assertTrue(logger instanceof DefaultLogger); - } + Assertions.assertTrue(logger instanceof DefaultLogger); + } - @Test - void shouldWriteDataToDefaultLoggerImplementation() { + @Test + void shouldWriteDataToDefaultLoggerImplementation() { - var logger = LoggerManager.getLogger(DefaultLoggerTest.class); - logger.print(LoggerLevel.ERROR, "test data"); + var logger = LoggerManager.getLogger(DefaultLoggerTest.class); + logger.print(LoggerLevel.ERROR, "test data"); - Assertions.assertEquals(1, WROTE_DATA.size()); + Assertions.assertEquals(1, WROTE_DATA.size()); - logger.print(LoggerLevel.ERROR, "test data 2"); + logger.print(LoggerLevel.ERROR, "test data 2"); - Assertions.assertEquals(2, WROTE_DATA.size()); - } + Assertions.assertEquals(2, WROTE_DATA.size()); + } } diff --git a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java index a9630ab4..79239bba 100644 --- a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java +++ b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java @@ -8,58 +8,58 @@ @RequiredArgsConstructor public class Slf4jLogger implements Logger { - private final org.slf4j.Logger logger; + private final org.slf4j.Logger logger; - @Override - public boolean isEnabled(@NotNull LoggerLevel level) { + @Override + public boolean isEnabled(@NotNull LoggerLevel level) { - switch (level) { - case INFO: - return logger.isInfoEnabled(); - case DEBUG: - return logger.isDebugEnabled(); - case ERROR: - return logger.isErrorEnabled(); - case WARNING: - return logger.isWarnEnabled(); - } - - return false; + switch (level) { + case INFO: + return logger.isInfoEnabled(); + case DEBUG: + return logger.isDebugEnabled(); + case ERROR: + return logger.isErrorEnabled(); + case WARNING: + return logger.isWarnEnabled(); } - @Override - public void print(@NotNull LoggerLevel level, @NotNull String message) { + return false; + } + + @Override + public void print(@NotNull LoggerLevel level, @NotNull String message) { - switch (level) { - case INFO: - logger.info(message); - return; - case DEBUG: - logger.debug(message); - return; - case ERROR: - logger.error(message); - return; - case WARNING: - logger.warn(message); - } + switch (level) { + case INFO: + logger.info(message); + return; + case DEBUG: + logger.debug(message); + return; + case ERROR: + logger.error(message); + return; + case WARNING: + logger.warn(message); } + } - @Override - public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { + @Override + public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { - switch (level) { - case INFO: - logger.info(exception.getMessage(), exception); - return; - case DEBUG: - logger.debug(exception.getMessage(), exception); - return; - case ERROR: - logger.error(exception.getMessage(), exception); - return; - case WARNING: - logger.warn(exception.getMessage(), exception); - } + switch (level) { + case INFO: + logger.info(exception.getMessage(), exception); + return; + case DEBUG: + logger.debug(exception.getMessage(), exception); + return; + case ERROR: + logger.error(exception.getMessage(), exception); + return; + case WARNING: + logger.warn(exception.getMessage(), exception); } + } } diff --git a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java index 3b713e9d..68e35384 100644 --- a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java +++ b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java @@ -8,44 +8,44 @@ public class Slf4jLoggerFactory implements LoggerFactory { - private final Logger logger; - - public Slf4jLoggerFactory() { - this.logger = new Slf4jLogger(org.slf4j.LoggerFactory.getLogger("")); - } - - @Override - public @NotNull Logger make(@NotNull String name) { - return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(name)); - } - - @Override - public @NotNull Logger make(@NotNull Class type) { - return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(type)); - } - - @Override - public @NotNull Logger getDefault() { - return logger; - } - - @Override - public void addListener(@NotNull LoggerListener listener) { - throw new UnsupportedOperationException(); - } - - @Override - public void addWriter(@NotNull Writer writer) { - throw new UnsupportedOperationException(); - } - - @Override - public void removeListener(@NotNull LoggerListener listener) { - throw new UnsupportedOperationException(); - } - - @Override - public void removeWriter(@NotNull Writer writer) { - throw new UnsupportedOperationException(); - } + private final Logger logger; + + public Slf4jLoggerFactory() { + this.logger = new Slf4jLogger(org.slf4j.LoggerFactory.getLogger("")); + } + + @Override + public @NotNull Logger make(@NotNull String name) { + return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(name)); + } + + @Override + public @NotNull Logger make(@NotNull Class type) { + return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(type)); + } + + @Override + public @NotNull Logger getDefault() { + return logger; + } + + @Override + public void addListener(@NotNull LoggerListener listener) { + throw new UnsupportedOperationException(); + } + + @Override + public void addWriter(@NotNull Writer writer) { + throw new UnsupportedOperationException(); + } + + @Override + public void removeListener(@NotNull LoggerListener listener) { + throw new UnsupportedOperationException(); + } + + @Override + public void removeWriter(@NotNull Writer writer) { + throw new UnsupportedOperationException(); + } } diff --git a/rlib-logger-slf4j/src/test/java/javasabr/rlib/logger/slf4j/Slf4jLoggerTest.java b/rlib-logger-slf4j/src/test/java/javasabr/rlib/logger/slf4j/Slf4jLoggerTest.java index 002d7338..ba430afa 100644 --- a/rlib-logger-slf4j/src/test/java/javasabr/rlib/logger/slf4j/Slf4jLoggerTest.java +++ b/rlib-logger-slf4j/src/test/java/javasabr/rlib/logger/slf4j/Slf4jLoggerTest.java @@ -6,11 +6,11 @@ public class Slf4jLoggerTest { - @Test - void shouldCreateDefaultLoggerImplementation() { + @Test + void shouldCreateDefaultLoggerImplementation() { - var logger = LoggerManager.getLogger(Slf4jLoggerTest.class); + var logger = LoggerManager.getLogger(Slf4jLoggerTest.class); - Assertions.assertTrue(logger instanceof Slf4jLogger); - } + Assertions.assertTrue(logger instanceof Slf4jLogger); + } } diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java index 99e05868..8e61d6ef 100644 --- a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java @@ -7,24 +7,24 @@ public interface MailSender { - /** - * Send a new email with the subject to the email address. - * - * @param email the target email. - * @param subject the subject. - * @param content the email's content. - * @throws UncheckedMessagingException if something was wrong. - */ - void send(@NotNull String email, @NotNull String subject, @NotNull String content); + /** + * Send a new email with the subject to the email address. + * + * @param email the target email. + * @param subject the subject. + * @param content the email's content. + * @throws UncheckedMessagingException if something was wrong. + */ + void send(@NotNull String email, @NotNull String subject, @NotNull String content); - /** - * Send a new email with the subject to the email address. - * - * @param email the target email. - * @param subject the subject. - * @param content the email's content. - * @return the async result of sending process. - * @throws CompletionException -> UncheckedMessagingException if something was wrong. - */ - @NotNull CompletableFuture sendAsync(@NotNull String email, @NotNull String subject, @NotNull String content); + /** + * Send a new email with the subject to the email address. + * + * @param email the target email. + * @param subject the subject. + * @param content the email's content. + * @return the async result of sending process. + * @throws CompletionException -> UncheckedMessagingException if something was wrong. + */ + @NotNull CompletableFuture sendAsync(@NotNull String email, @NotNull String subject, @NotNull String content); } diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSenderConfig.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSenderConfig.java index 2918bae6..79135665 100644 --- a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSenderConfig.java +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSenderConfig.java @@ -7,14 +7,14 @@ @Builder public class MailSenderConfig { - private String host; - private int port; + private String host; + private int port; - private String sslHost; - private String username; - private String password; - private String from; + private String sslHost; + private String username; + private String password; + private String from; - private boolean useAuth; - private boolean enableTtls; + private boolean useAuth; + private boolean enableTtls; } diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java index f969c911..467d6d96 100644 --- a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java @@ -5,7 +5,7 @@ public class UncheckedMessagingException extends RuntimeException { - public UncheckedMessagingException(@NotNull MessagingException cause) { - super(cause); - } + public UncheckedMessagingException(@NotNull MessagingException cause) { + super(cause); + } } diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java index e3498d4f..e52a31a5 100644 --- a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java @@ -31,114 +31,116 @@ public class JavaxMailSender implements MailSender { - private static final Logger LOGGER = LoggerManager.getLogger(JavaxMailSender.class); + private static final Logger LOGGER = LoggerManager.getLogger(JavaxMailSender.class); - @Getter - @Builder - public static class JavaxMailSenderConfig { + @Getter + @Builder + public static class JavaxMailSenderConfig { - private int executorMinThreads; - private int executorMaxThreads; - private int executorKeepAlive; + private int executorMinThreads; + private int executorMaxThreads; + private int executorKeepAlive; - private Executor executor; - } + private Executor executor; + } - private final Executor executor; - private final Session session; - private final InternetAddress from; + private final Executor executor; + private final Session session; + private final InternetAddress from; - public JavaxMailSender(@NotNull MailSenderConfig config) { - this(config, JavaxMailSenderConfig.builder() + public JavaxMailSender(@NotNull MailSenderConfig config) { + this( + config, + JavaxMailSenderConfig + .builder() .executorKeepAlive(60) .executorMinThreads(1) .executorMaxThreads(2) - .build() - ); - } - public JavaxMailSender(@NotNull MailSenderConfig config, @NotNull JavaxMailSenderConfig javaxConfig) { + .build()); + } + + public JavaxMailSender(@NotNull MailSenderConfig config, @NotNull JavaxMailSenderConfig javaxConfig) { - var prop = new Properties(); - prop.put("mail.smtp.auth", String.valueOf(config.isUseAuth())); - prop.put("mail.smtp.host", config.getHost()); - prop.put("mail.smtp.port", String.valueOf(config.getPort())); + var prop = new Properties(); + prop.put("mail.smtp.auth", String.valueOf(config.isUseAuth())); + prop.put("mail.smtp.host", config.getHost()); + prop.put("mail.smtp.port", String.valueOf(config.getPort())); - if (config.isEnableTtls()) { - prop.put("mail.smtp.socketFactory.port", String.valueOf(config.getPort())); - prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); - prop.put("mail.smtp.starttls.enable", "true"); - prop.put("mail.smtp.ssl.trust", config.getSslHost()); - } + if (config.isEnableTtls()) { + prop.put("mail.smtp.socketFactory.port", String.valueOf(config.getPort())); + prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); + prop.put("mail.smtp.starttls.enable", "true"); + prop.put("mail.smtp.ssl.trust", config.getSslHost()); + } - var username = config.getUsername(); - var password = config.getPassword(); + var username = config.getUsername(); + var password = config.getPassword(); - this.session = Session.getInstance(prop, new Authenticator() { + this.session = Session.getInstance( + prop, new Authenticator() { - @Override - protected @NotNull PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } + @Override + protected @NotNull PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } }); - try { - this.from = new InternetAddress(config.getFrom()); - } catch (AddressException e) { - throw new RuntimeException(e); - } - - LOGGER.info("Initialized javax mail sender with settings:"); - LOGGER.info("User : " + username); - LOGGER.info("From : " + config.getFrom()); - LOGGER.info("Server : " + config.getHost() + ":" + config.getPort()); - LOGGER.info("Using SSL : " + config.isEnableTtls()); - - if (javaxConfig.getExecutor() != null) { - this.executor = javaxConfig.getExecutor(); - } else { - this.executor = new ThreadPoolExecutor( - javaxConfig.getExecutorMinThreads(), - javaxConfig.getExecutorMaxThreads(), - javaxConfig.getExecutorKeepAlive(), - TimeUnit.SECONDS, - new SynchronousQueue<>(), - Executors.defaultThreadFactory(), - new ThreadPoolExecutor.CallerRunsPolicy() - ); - } + try { + this.from = new InternetAddress(config.getFrom()); + } catch (AddressException e) { + throw new RuntimeException(e); } - @Override - public void send(@NotNull String email, @NotNull String subject, @NotNull String content) { + LOGGER.info("Initialized javax mail sender with settings:"); + LOGGER.info("User : " + username); + LOGGER.info("From : " + config.getFrom()); + LOGGER.info("Server : " + config.getHost() + ":" + config.getPort()); + LOGGER.info("Using SSL : " + config.isEnableTtls()); + + if (javaxConfig.getExecutor() != null) { + this.executor = javaxConfig.getExecutor(); + } else { + this.executor = new ThreadPoolExecutor( + javaxConfig.getExecutorMinThreads(), + javaxConfig.getExecutorMaxThreads(), + javaxConfig.getExecutorKeepAlive(), + TimeUnit.SECONDS, + new SynchronousQueue<>(), + Executors.defaultThreadFactory(), + new ThreadPoolExecutor.CallerRunsPolicy()); + } + } - try { + @Override + public void send(@NotNull String email, @NotNull String subject, @NotNull String content) { - var message = new MimeMessage(session); - message.setFrom(from); - message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(email)); - message.setSubject(subject, StandardCharsets.UTF_8.name()); + try { - var mimeBodyPart = new MimeBodyPart(); - mimeBodyPart.setContent(content, "text/html; charset=UTF-8"); + var message = new MimeMessage(session); + message.setFrom(from); + message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(email)); + message.setSubject(subject, StandardCharsets.UTF_8.name()); - var multipart = new MimeMultipart(); - multipart.addBodyPart(mimeBodyPart); + var mimeBodyPart = new MimeBodyPart(); + mimeBodyPart.setContent(content, "text/html; charset=UTF-8"); - message.setContent(multipart); + var multipart = new MimeMultipart(); + multipart.addBodyPart(mimeBodyPart); - Transport.send(message); + message.setContent(multipart); - } catch (MessagingException e) { - throw new UncheckedMessagingException(e); - } - } + Transport.send(message); - @Override - public @NotNull CompletableFuture sendAsync( - @NotNull String email, - @NotNull String subject, - @NotNull String content - ) { - return runAsync(() -> send(email, subject, content), executor); + } catch (MessagingException e) { + throw new UncheckedMessagingException(e); } + } + + @Override + public @NotNull CompletableFuture sendAsync( + @NotNull String email, + @NotNull String subject, + @NotNull String content) { + return runAsync(() -> send(email, subject, content), executor); + } } diff --git a/rlib-mail/src/test/java/javasabr/rlib/mail/BaseMailTest.java b/rlib-mail/src/test/java/javasabr/rlib/mail/BaseMailTest.java index fbf77ab9..f7d7b29f 100644 --- a/rlib-mail/src/test/java/javasabr/rlib/mail/BaseMailTest.java +++ b/rlib-mail/src/test/java/javasabr/rlib/mail/BaseMailTest.java @@ -6,16 +6,16 @@ public abstract class BaseMailTest { - protected static final FakeSMTPTestContainer FAKE_SMTP_TEST_CONTAINER = new FakeSMTPTestContainer(); + protected static final FakeSMTPTestContainer FAKE_SMTP_TEST_CONTAINER = new FakeSMTPTestContainer(); - @BeforeAll - static void runContainers() { - FAKE_SMTP_TEST_CONTAINER.start(); - FAKE_SMTP_TEST_CONTAINER.waitForReadyState(); - } + @BeforeAll + static void runContainers() { + FAKE_SMTP_TEST_CONTAINER.start(); + FAKE_SMTP_TEST_CONTAINER.waitForReadyState(); + } - @AfterAll - static void stopContainers() { - FAKE_SMTP_TEST_CONTAINER.stop(); - } + @AfterAll + static void stopContainers() { + FAKE_SMTP_TEST_CONTAINER.stop(); + } } diff --git a/rlib-mail/src/test/java/javasabr/rlib/mail/sender/JavaxMailSenderTest.java b/rlib-mail/src/test/java/javasabr/rlib/mail/sender/JavaxMailSenderTest.java index 75b18a5c..89873f55 100644 --- a/rlib-mail/src/test/java/javasabr/rlib/mail/sender/JavaxMailSenderTest.java +++ b/rlib-mail/src/test/java/javasabr/rlib/mail/sender/JavaxMailSenderTest.java @@ -7,30 +7,31 @@ public class JavaxMailSenderTest extends BaseMailTest { - @Test - void shouldSendEmailSuccessfully() { + @Test + void shouldSendEmailSuccessfully() { - var smtpServer = FAKE_SMTP_TEST_CONTAINER; - var smtpPort = smtpServer.getSmtpPort(); - var smtpUser = smtpServer.getSmtpUser(); - var smtpPassword = smtpServer.getSmtpPassword(); + var smtpServer = FAKE_SMTP_TEST_CONTAINER; + var smtpPort = smtpServer.getSmtpPort(); + var smtpUser = smtpServer.getSmtpUser(); + var smtpPassword = smtpServer.getSmtpPassword(); - var config = MailSenderConfig.builder() - .from("from@test.com") - .host("localhost") - .port(smtpPort) - .password(smtpPassword) - .username(smtpUser) - .useAuth(true) - .build(); + var config = MailSenderConfig + .builder() + .from("from@test.com") + .host("localhost") + .port(smtpPort) + .password(smtpPassword) + .username(smtpUser) + .useAuth(true) + .build(); - var sender = new JavaxMailSender(config); - sender.send("to@test.com", "Test Subject", "Content"); + var sender = new JavaxMailSender(config); + sender.send("to@test.com", "Test Subject", "Content"); - Assertions.assertEquals(1, smtpServer.getEmailCountFrom("from@test.com")); + Assertions.assertEquals(1, smtpServer.getEmailCountFrom("from@test.com")); - sender.send("to@test.com", "Test Subject 2", "Content 2"); + sender.send("to@test.com", "Test Subject 2", "Content 2"); - Assertions.assertEquals(2, smtpServer.getEmailCountFrom("from@test.com")); - } + Assertions.assertEquals(2, smtpServer.getEmailCountFrom("from@test.com")); + } } 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 fd24d107..769c9303 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java @@ -10,65 +10,65 @@ */ public interface BufferAllocator { - /** - * Get a new read buffer to use. - * - * @return the new buffer. - */ - @NotNull ByteBuffer takeReadBuffer(); + /** + * Get a new read buffer to use. + * + * @return the new buffer. + */ + @NotNull ByteBuffer takeReadBuffer(); - /** - * Get a new pending buffer to use. - * - * @return the new pending buffer. - */ - @NotNull ByteBuffer takePendingBuffer(); + /** + * Get a new pending buffer to use. + * + * @return the new pending buffer. + */ + @NotNull ByteBuffer takePendingBuffer(); - /** - * Get a new write buffer to use. - * - * @return the new buffer. - */ - @NotNull ByteBuffer takeWriteBuffer(); + /** + * Get a new write buffer to use. + * + * @return the new buffer. + */ + @NotNull ByteBuffer takeWriteBuffer(); - /** - * Get a new buffer with requested capacity. - * - * @param bufferSize the size of new buffer. - * @return the new buffer. - */ - @NotNull ByteBuffer takeBuffer(int bufferSize); + /** + * Get a new buffer with requested capacity. + * + * @param bufferSize the size of new buffer. + * @return the new buffer. + */ + @NotNull ByteBuffer takeBuffer(int bufferSize); - /** - * Store an old read buffer if need. - * - * @param buffer the old read buffer. - * @return this allocator. - */ - @NotNull BufferAllocator putReadBuffer(@NotNull ByteBuffer buffer); + /** + * Store an old read buffer if need. + * + * @param buffer the old read buffer. + * @return this allocator. + */ + @NotNull BufferAllocator putReadBuffer(@NotNull ByteBuffer buffer); - /** - * Store an old pending buffer if need. - * - * @param buffer the old pending buffer. - * @return this allocator. - */ - @NotNull BufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer); + /** + * Store an old pending buffer if need. + * + * @param buffer the old pending buffer. + * @return this allocator. + */ + @NotNull BufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer); - /** - * Store an old write buffer if need. - * - * @param buffer the old write buffer. - * @return this allocator. - */ - @NotNull BufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer); + /** + * Store an old write buffer if need. + * + * @param buffer the old write buffer. + * @return this allocator. + */ + @NotNull BufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer); - /** - * Store an old byte buffer if need. - * - * @param buffer the old byte buffer. - * @return this allocator. - */ + /** + * Store an old byte buffer if need. + * + * @param buffer the old byte buffer. + * @return this allocator. + */ - @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer); + @NotNull BufferAllocator putBuffer(@NotNull 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 4ebff115..18dee5c2 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/Connection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/Connection.java @@ -15,72 +15,74 @@ */ public interface Connection { - @AllArgsConstructor - class ReceivedPacketEvent, R extends ReadablePacket> { - @NotNull public final C connection; - @NotNull public final R packet; - } + @AllArgsConstructor + class ReceivedPacketEvent, R extends ReadablePacket> { + @NotNull + public final C connection; + @NotNull + public final R packet; + } - /** - * Get a remote address of this connection. - * - * @return the remote address. - */ - @NotNull String getRemoteAddress(); + /** + * Get a remote address of this connection. + * + * @return the remote address. + */ + @NotNull String getRemoteAddress(); - /** - * Get a timestamp of last write/read activity. - * - * @return the timestamp of last write/read activity. - */ - long getLastActivity(); + /** + * Get a timestamp of last write/read activity. + * + * @return the timestamp of last write/read activity. + */ + long getLastActivity(); - /** - * Close this connection if this connection is still opened. - */ - void close(); + /** + * Close this connection if this connection is still opened. + */ + void close(); - /** - * Check a closed state of this connection. - * - * @return true if this connection is already closed. - */ - boolean isClosed(); + /** + * Check a closed state of this connection. + * + * @return true if this connection is already closed. + */ + boolean isClosed(); - /** - * Send a packet to connection's owner. - * - * @param packet the writable packet. - */ - void send(@NotNull W packet); + /** + * Send a packet to connection's owner. + * + * @param packet the writable packet. + */ + void send(@NotNull W packet); - /** - * Send a packet to connection's owner with async feedback of this sending. - * - * @param packet the writable packet. - * @return the async result with true if the packet was sent or false if sending was failed. - * @since 9.5.0 - */ - @NotNull CompletableFuture sendWithFeedback(@NotNull W packet); + /** + * Send a packet to connection's owner with async feedback of this sending. + * + * @param packet the writable packet. + * @return the async result with true if the packet was sent or false if sending was failed. + * @since 9.5.0 + */ + @NotNull CompletableFuture sendWithFeedback(@NotNull W packet); - /** - * Register a consumer to handle received packets. - * - * @param consumer the consumer. - */ - void onReceive(@NotNull NotNullBiConsumer, ? super R> consumer); + /** + * Register a consumer to handle received packets. + * + * @param consumer the consumer. + */ + void onReceive(@NotNull NotNullBiConsumer, ? super R> consumer); - /** - * Get a stream of received packet events. - * - * @return the stream of received packet events. - */ - @NotNull Flux, ? extends R>> receivedEvents(); + /** + * Get a stream of received packet events. + * + * @return the stream of received packet events. + */ + @NotNull Flux, ? extends R>> receivedEvents(); - /** - * Get a stream of received packets. - * - * @return the stream of received packets. - */ - @NotNull Flux receivedPackets(); + /** + * Get a stream of received packets. + * + * @return the stream of received packets. + */ + @NotNull Flux receivedPackets(); } 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 55b08726..1778af27 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/Network.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/Network.java @@ -7,8 +7,8 @@ */ public interface Network> { - /** - * Shutdown this network. - */ - void shutdown(); + /** + * Shutdown this network. + */ + 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 b55f70bc..cb0f6973 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java @@ -12,73 +12,73 @@ */ public interface NetworkConfig { - @Builder - @Getter - class SimpleNetworkConfig implements NetworkConfig { + @Builder + @Getter + class SimpleNetworkConfig implements NetworkConfig { - @Builder.Default - private String groupName = "NetworkThread"; - @Builder.Default - private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; + @Builder.Default + private String groupName = "NetworkThread"; + @Builder.Default + private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; - @Builder.Default - private int readBufferSize = 2048; - @Builder.Default - private int pendingBufferSize = 4096; - @Builder.Default - private int writeBufferSize = 2048; - } - - @NotNull NetworkConfig DEFAULT_CLIENT = new NetworkConfig() { + @Builder.Default + private int readBufferSize = 2048; + @Builder.Default + private int pendingBufferSize = 4096; + @Builder.Default + private int writeBufferSize = 2048; + } - @Override - public @NotNull String getThreadGroupName() { - return "ClientNetworkThread"; - } - }; + @NotNull NetworkConfig DEFAULT_CLIENT = new NetworkConfig() { - /** - * Get a group name of network threads. - * - * @return the group name. - */ - default @NotNull String getThreadGroupName() { - return "NetworkThread"; + @Override + public @NotNull String getThreadGroupName() { + return "ClientNetworkThread"; } + }; - /** - * Get size of buffer with used to collect received data from network. - * - * @return the read buffer's size. - */ - default int getReadBufferSize() { - return 2048; - } + /** + * Get a group name of network threads. + * + * @return the group name. + */ + default @NotNull String getThreadGroupName() { + return "NetworkThread"; + } - /** - * Get size of buffer with pending data. Pending buffer allows to construct a packet with - * bigger data than {@link #getReadBufferSize()}. It should be at least 2x of {@link #getReadBufferSize()} - * - * @return the pending buffer's size. - */ - default int getPendingBufferSize() { - return getReadBufferSize() * 2; - } + /** + * Get size of buffer with used to collect received data from network. + * + * @return the read buffer's size. + */ + default int getReadBufferSize() { + return 2048; + } - /** - * Get size of buffer which used to serialize packets to bytes. - * - * @return the write buffer's size. - */ - default int getWriteBufferSize() { - return 2048; - } + /** + * Get size of buffer with pending data. Pending buffer allows to construct a packet with bigger data than + * {@link #getReadBufferSize()}. It should be at least 2x of {@link #getReadBufferSize()} + * + * @return the pending buffer's size. + */ + default int getPendingBufferSize() { + return getReadBufferSize() * 2; + } - default @NotNull ByteOrder getByteOrder() { - return ByteOrder.BIG_ENDIAN; - } + /** + * Get size of buffer which used to serialize packets to bytes. + * + * @return the write buffer's size. + */ + default int getWriteBufferSize() { + return 2048; + } - default boolean isDirectByteBuffer() { - return false; - } + default @NotNull ByteOrder getByteOrder() { + return ByteOrder.BIG_ENDIAN; + } + + default boolean isDirectByteBuffer() { + 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 71d28ce8..8d85968c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java @@ -11,39 +11,39 @@ */ public interface NetworkCryptor { - /** - * Default NULL implementation of the network crypt. - */ - @NotNull NetworkCryptor NULL = new NetworkCryptor() { + /** + * Default NULL implementation of the network crypt. + */ + @NotNull NetworkCryptor NULL = new NetworkCryptor() { - @Override - public @Nullable ByteBuffer decrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore) { - return null; - } + @Override + public @Nullable ByteBuffer decrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore) { + return null; + } - @Override - public @Nullable ByteBuffer encrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore) { - return null; - } - }; + @Override + public @Nullable ByteBuffer encrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore) { + return null; + } + }; - /** - * Decrypt data. - * - * @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. - */ - @Nullable ByteBuffer decrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore); + /** + * Decrypt data. + * + * @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. + */ + @Nullable ByteBuffer decrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore); - /** - * Encrypt data. - * - * @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. - */ - @Nullable ByteBuffer encrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore); + /** + * Encrypt data. + * + * @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. + */ + @Nullable ByteBuffer encrypt(@NotNull ByteBuffer data, int length, @NotNull 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 b773a720..8df7b8fa 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java @@ -22,221 +22,185 @@ */ public final class NetworkFactory { - public static > @NotNull ClientNetwork newClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection - ) { - return new DefaultClientNetwork<>(networkConfig, channelToConnection); - } - - public static > @NotNull ServerNetwork newServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection - ) { - return new DefaultServerNetwork<>(networkConfig, channelToConnection); - } - - /** - * Create a string packet based asynchronous client network. - * - * @return the client network. - */ - public static @NotNull ClientNetwork newStringDataClientNetwork() { - return newStringDataClientNetwork(NetworkConfig.DEFAULT_CLIENT); - } - - /** - * Create a string packet based asynchronous client network. - * - * @param networkConfig the network config. - * @return the client network. - */ - public static @NotNull ClientNetwork newStringDataClientNetwork( - @NotNull NetworkConfig networkConfig - ) { - return newStringDataClientNetwork( - networkConfig, - new DefaultBufferAllocator(networkConfig) - ); - } - - /** - * Create a string packet based asynchronous client network. - * - * @param networkConfig the network config. - * @param bufferAllocator the buffer allocator. - * @return the client network. - */ - public static @NotNull ClientNetwork newStringDataClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator - ) { - return newClientNetwork( - networkConfig, - (network, channel) -> new StringDataConnection(network, channel, bufferAllocator) - ); - } - - /** - * Create id based packet default asynchronous client network. - * - * @param packetRegistry the readable packet registry. - * @return the server network. - */ - public static @NotNull ClientNetwork newDefaultClientNetwork( - @NotNull ReadablePacketRegistry packetRegistry - ) { - return newDefaultClientNetwork( - NetworkConfig.DEFAULT_CLIENT, - new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), - packetRegistry - ); - } - - /** - * Create id based packet default asynchronous client network. - * - * @param networkConfig the network config. - * @param bufferAllocator the buffer allocator. - * @param packetRegistry the readable packet registry. - * @return the server network. - */ - public static @NotNull ClientNetwork newDefaultClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry - ) { - return newClientNetwork( - networkConfig, - (network, channel) -> new DefaultConnection( - network, - channel, - bufferAllocator, - packetRegistry - ) - ); - } - - /** - * Create string packet based asynchronous secure client network. - * - * @param networkConfig the network config. - * @param bufferAllocator the buffer allocator. - * @param sslContext the ssl context. - * @return the client network. - */ - public static @NotNull ClientNetwork newStringDataSSLClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext - ) { - return newClientNetwork( - networkConfig, - (network, channel) -> new StringDataSSLConnection(network, channel, bufferAllocator, sslContext, true) - ); - } - - /** - * Create string packet based asynchronous server network. - * - * @return the server network. - */ - public static @NotNull ServerNetwork newStringDataServerNetwork() { - return newStringDataServerNetwork(ServerNetworkConfig.DEFAULT_SERVER); - } - - /** - * Create string packet based asynchronous server network. - * - * @param networkConfig the network config. - * @return the server network. - */ - public static @NotNull ServerNetwork newStringDataServerNetwork( - @NotNull ServerNetworkConfig networkConfig - ) { - return newStringDataServerNetwork( - networkConfig, - new DefaultBufferAllocator(networkConfig) - ); - } - - /** - * Create string packet based asynchronous server network. - * - * @param networkConfig the network config. - * @param bufferAllocator the buffer allocator. - * @return the server network. - */ - public static @NotNull ServerNetwork newStringDataServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator - ) { - return newServerNetwork( - networkConfig, - (network, channel) -> new StringDataConnection(network, channel, bufferAllocator) - ); - } - - /** - * Create string packet based asynchronous secure server network. - * - * @param networkConfig the network config. - * @param bufferAllocator the buffer allocator. - * @param sslContext the ssl context. - * @return the server network. - */ - public static @NotNull ServerNetwork newStringDataSSLServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext - ) { - return newServerNetwork( - networkConfig, - (network, channel) -> new StringDataSSLConnection(network, channel, bufferAllocator, sslContext, false) - ); - } - - /** - * Create id based packet default asynchronous server network. - * - * @param packetRegistry the readable packet registry. - * @return the server network. - */ - public static @NotNull ServerNetwork newDefaultServerNetwork( - @NotNull ReadablePacketRegistry packetRegistry - ) { - return newDefaultServerNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), - packetRegistry - ); - } - - /** - * Create id based packet default asynchronous server network. - * - * @param networkConfig the network config. - * @param bufferAllocator the buffer allocator. - * @param packetRegistry the readable packet registry. - * @return the server network. - */ - public static @NotNull ServerNetwork newDefaultServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry - ) { - return newServerNetwork( - networkConfig, - (network, channel) -> new DefaultConnection( - network, - channel, - bufferAllocator, - packetRegistry - ) - ); - } - - private NetworkFactory() throws Exception { - throw new Exception("no permission"); - } + public static > @NotNull ClientNetwork newClientNetwork( + @NotNull NetworkConfig networkConfig, + @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + return new DefaultClientNetwork<>(networkConfig, channelToConnection); + } + + public static > @NotNull ServerNetwork newServerNetwork( + @NotNull ServerNetworkConfig networkConfig, + @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + return new DefaultServerNetwork<>(networkConfig, channelToConnection); + } + + /** + * Create a string packet based asynchronous client network. + * + * @return the client network. + */ + public static @NotNull ClientNetwork newStringDataClientNetwork() { + return newStringDataClientNetwork(NetworkConfig.DEFAULT_CLIENT); + } + + /** + * Create a string packet based asynchronous client network. + * + * @param networkConfig the network config. + * @return the client network. + */ + public static @NotNull ClientNetwork newStringDataClientNetwork( + @NotNull NetworkConfig networkConfig) { + return newStringDataClientNetwork(networkConfig, new DefaultBufferAllocator(networkConfig)); + } + + /** + * Create a string packet based asynchronous client network. + * + * @param networkConfig the network config. + * @param bufferAllocator the buffer allocator. + * @return the client network. + */ + public static @NotNull ClientNetwork newStringDataClientNetwork( + @NotNull NetworkConfig networkConfig, + @NotNull BufferAllocator bufferAllocator) { + return newClientNetwork( + networkConfig, + (network, channel) -> new StringDataConnection(network, channel, bufferAllocator)); + } + + /** + * Create id based packet default asynchronous client network. + * + * @param packetRegistry the readable packet registry. + * @return the server network. + */ + public static @NotNull ClientNetwork newDefaultClientNetwork( + @NotNull ReadablePacketRegistry packetRegistry) { + return newDefaultClientNetwork( + NetworkConfig.DEFAULT_CLIENT, + new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), + packetRegistry); + } + + /** + * Create id based packet default asynchronous client network. + * + * @param networkConfig the network config. + * @param bufferAllocator the buffer allocator. + * @param packetRegistry the readable packet registry. + * @return the server network. + */ + public static @NotNull ClientNetwork newDefaultClientNetwork( + @NotNull NetworkConfig networkConfig, + @NotNull BufferAllocator bufferAllocator, + @NotNull ReadablePacketRegistry packetRegistry) { + return newClientNetwork( + networkConfig, + (network, channel) -> new DefaultConnection(network, channel, bufferAllocator, packetRegistry)); + } + + /** + * Create string packet based asynchronous secure client network. + * + * @param networkConfig the network config. + * @param bufferAllocator the buffer allocator. + * @param sslContext the ssl context. + * @return the client network. + */ + public static @NotNull ClientNetwork newStringDataSSLClientNetwork( + @NotNull NetworkConfig networkConfig, + @NotNull BufferAllocator bufferAllocator, + @NotNull SSLContext sslContext) { + return newClientNetwork( + networkConfig, + (network, channel) -> new StringDataSSLConnection(network, channel, bufferAllocator, sslContext, true)); + } + + /** + * Create string packet based asynchronous server network. + * + * @return the server network. + */ + public static @NotNull ServerNetwork newStringDataServerNetwork() { + return newStringDataServerNetwork(ServerNetworkConfig.DEFAULT_SERVER); + } + + /** + * Create string packet based asynchronous server network. + * + * @param networkConfig the network config. + * @return the server network. + */ + public static @NotNull ServerNetwork newStringDataServerNetwork( + @NotNull ServerNetworkConfig networkConfig) { + return newStringDataServerNetwork(networkConfig, new DefaultBufferAllocator(networkConfig)); + } + + /** + * Create string packet based asynchronous server network. + * + * @param networkConfig the network config. + * @param bufferAllocator the buffer allocator. + * @return the server network. + */ + public static @NotNull ServerNetwork newStringDataServerNetwork( + @NotNull ServerNetworkConfig networkConfig, + @NotNull BufferAllocator bufferAllocator) { + return newServerNetwork( + networkConfig, + (network, channel) -> new StringDataConnection(network, channel, bufferAllocator)); + } + + /** + * Create string packet based asynchronous secure server network. + * + * @param networkConfig the network config. + * @param bufferAllocator the buffer allocator. + * @param sslContext the ssl context. + * @return the server network. + */ + public static @NotNull ServerNetwork newStringDataSSLServerNetwork( + @NotNull ServerNetworkConfig networkConfig, + @NotNull BufferAllocator bufferAllocator, + @NotNull SSLContext sslContext) { + return newServerNetwork( + networkConfig, + (network, channel) -> new StringDataSSLConnection(network, channel, bufferAllocator, sslContext, false)); + } + + /** + * Create id based packet default asynchronous server network. + * + * @param packetRegistry the readable packet registry. + * @return the server network. + */ + public static @NotNull ServerNetwork newDefaultServerNetwork( + @NotNull ReadablePacketRegistry packetRegistry) { + return newDefaultServerNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), + packetRegistry); + } + + /** + * Create id based packet default asynchronous server network. + * + * @param networkConfig the network config. + * @param bufferAllocator the buffer allocator. + * @param packetRegistry the readable packet registry. + * @return the server network. + */ + public static @NotNull ServerNetwork newDefaultServerNetwork( + @NotNull ServerNetworkConfig networkConfig, + @NotNull BufferAllocator bufferAllocator, + @NotNull ReadablePacketRegistry packetRegistry) { + return newServerNetwork( + networkConfig, + (network, channel) -> new DefaultConnection(network, channel, bufferAllocator, packetRegistry)); + } + + private NetworkFactory() throws Exception { + throw new Exception("no permission"); + } } 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 cc3630d3..bb405284 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java @@ -13,75 +13,75 @@ */ public interface ServerNetworkConfig extends NetworkConfig { - @Builder - @Getter - class SimpleServerNetworkConfig implements ServerNetworkConfig { + @Builder + @Getter + class SimpleServerNetworkConfig implements ServerNetworkConfig { - @Builder.Default - private String threadGroupName = "ServerNetworkThread"; - @Builder.Default - private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; - @Builder.Default - private GroupThreadFactory.ThreadConstructor threadConstructor = Thread::new; + @Builder.Default + private String threadGroupName = "ServerNetworkThread"; + @Builder.Default + private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; + @Builder.Default + private GroupThreadFactory.ThreadConstructor threadConstructor = Thread::new; - @Builder.Default - private int readBufferSize = 2048; - @Builder.Default - private int pendingBufferSize = 4096; - @Builder.Default - private int writeBufferSize = 2048; - @Builder.Default - private int threadGroupSize = 1; - @Builder.Default - private int threadPriority = Thread.NORM_PRIORITY; - } - - @NotNull ServerNetworkConfig DEFAULT_SERVER = new ServerNetworkConfig() { + @Builder.Default + private int readBufferSize = 2048; + @Builder.Default + private int pendingBufferSize = 4096; + @Builder.Default + private int writeBufferSize = 2048; + @Builder.Default + private int threadGroupSize = 1; + @Builder.Default + private int threadPriority = Thread.NORM_PRIORITY; + } - @Override - public int getThreadGroupMinSize() { - return 1; - } + @NotNull ServerNetworkConfig DEFAULT_SERVER = new ServerNetworkConfig() { - @Override - public @NotNull String getThreadGroupName() { - return "ServerNetworkThread"; - } - }; - - /** - * Get a minimal size of network thread executor. - * - * @return the minimal executor size. - */ - default int getThreadGroupMinSize() { - return 1; + @Override + public int getThreadGroupMinSize() { + return 1; } - /** - * Get a maximum size of network thread executor. - * - * @return the maximum executor size. - */ - default int getThreadGroupMaxSize() { - return getThreadGroupMinSize(); + @Override + public @NotNull String getThreadGroupName() { + return "ServerNetworkThread"; } + }; - /** - * Get a thread constructor which should be used to create network threads. - * - * @return the thread constructor. - */ - default @NotNull GroupThreadFactory.ThreadConstructor getThreadConstructor() { - return Thread::new; - } + /** + * Get a minimal size of network thread executor. + * + * @return the minimal executor size. + */ + default int getThreadGroupMinSize() { + return 1; + } - /** - * Get a priority of network threads. - * - * @return the priority of network threads. - */ - default int getThreadPriority() { - return Thread.NORM_PRIORITY; - } + /** + * Get a maximum size of network thread executor. + * + * @return the maximum executor size. + */ + default int getThreadGroupMaxSize() { + return getThreadGroupMinSize(); + } + + /** + * Get a thread constructor which should be used to create network threads. + * + * @return the thread constructor. + */ + default @NotNull GroupThreadFactory.ThreadConstructor getThreadConstructor() { + return Thread::new; + } + + /** + * Get a priority of network threads. + * + * @return the priority of network threads. + */ + default int getThreadPriority() { + return Thread.NORM_PRIORITY; + } } 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 e7d8a2f7..3ab99e2b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/UnsafeConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/UnsafeConnection.java @@ -5,6 +5,6 @@ public interface UnsafeConnection extends Connection { - void onConnected(); + void onConnected(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/annotation/PacketDescription.java b/rlib-network/src/main/java/javasabr/rlib/network/annotation/PacketDescription.java index a2ca1e56..48a8a37f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/annotation/PacketDescription.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/annotation/PacketDescription.java @@ -16,5 +16,5 @@ @Target({ElementType.TYPE}) public @interface PacketDescription { - int id(); + 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 08f81f51..d9316e77 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 @@ -15,27 +15,26 @@ */ public interface ClientNetwork> extends Network { - /** - * Connect to a server by the address. - * - * @param serverAddress the sever address. - * @return the future with result connection. - */ - @NotNull CompletableFuture connect(@NotNull InetSocketAddress serverAddress); + /** + * Connect to a server by the address. + * + * @param serverAddress the sever address. + * @return the future with result connection. + */ + @NotNull CompletableFuture connect(@NotNull InetSocketAddress serverAddress); - /** - * Connect to a server by the address. - * - * @param serverAddress the sever address. - * @return the future with result connection. - */ - @NotNull Mono connected(@NotNull InetSocketAddress serverAddress); + /** + * Connect to a server by the address. + * + * @param serverAddress the sever address. + * @return the future with result connection. + */ + @NotNull Mono connected(@NotNull InetSocketAddress serverAddress); - - /** - * Get a current connection to a server or null. - * - * @return the current connection or null. - */ - @Nullable C getCurrentConnection(); + /** + * Get a current connection to a server or null. + * + * @return the current connection or null. + */ + @Nullable C getCurrentConnection(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java index e53398de..30f255d6 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java @@ -32,93 +32,92 @@ */ public class DefaultClientNetwork> extends AbstractNetwork implements ClientNetwork { - protected static final Logger LOGGER = LoggerManager.getLogger(DefaultClientNetwork.class); - - protected final @NotNull AtomicBoolean connecting; - - protected volatile @Nullable CompletableFuture pendingConnection; - protected volatile @Getter @Nullable C currentConnection; - - public DefaultClientNetwork( - @NotNull NetworkConfig config, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection - ) { - super(config, channelToConnection); - this.connecting = new AtomicBoolean(false); - - LOGGER.info(config, conf -> "Client network configuration: {\n" + - " groupName: \"" + conf.getThreadGroupName() + "\",\n" + - " readBufferSize: " + conf.getReadBufferSize() + ",\n" + - " pendingBufferSize: " + conf.getPendingBufferSize() + ",\n" + - " writeBufferSize: " + conf.getWriteBufferSize() + "\n" + - "}"); - } + protected static final Logger LOGGER = LoggerManager.getLogger(DefaultClientNetwork.class); - @Override - public @NotNull CompletableFuture connect(@NotNull InetSocketAddress serverAddress) { + protected final @NotNull AtomicBoolean connecting; - C currentConnection = getCurrentConnection(); + protected volatile @Nullable CompletableFuture pendingConnection; + protected volatile @Getter + @Nullable C currentConnection; - if (currentConnection != null) { - unchecked(currentConnection, C::close); - } + public DefaultClientNetwork( + @NotNull NetworkConfig config, + @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + super(config, channelToConnection); + this.connecting = new AtomicBoolean(false); - // if we are trying connection now - if (!connecting.compareAndSet(false, true)) { + LOGGER.info( + config, + conf -> "Client network configuration: {\n" + " groupName: \"" + conf.getThreadGroupName() + "\",\n" + + " readBufferSize: " + conf.getReadBufferSize() + ",\n" + " pendingBufferSize: " + + conf.getPendingBufferSize() + ",\n" + " writeBufferSize: " + conf.getWriteBufferSize() + "\n" + "}"); + } - var asyncResult = this.pendingConnection; + @Override + public @NotNull CompletableFuture connect(@NotNull InetSocketAddress serverAddress) { - if (asyncResult != null) { - return asyncResult; - } + C currentConnection = getCurrentConnection(); - ThreadUtils.sleep(100); + if (currentConnection != null) { + unchecked(currentConnection, C::close); + } - return connect(serverAddress); - } + // if we are trying connection now + if (!connecting.compareAndSet(false, true)) { - var asyncResult = new CompletableFuture(); + var asyncResult = this.pendingConnection; - var channel = uncheckedGet(AsynchronousSocketChannel::open); - channel.connect(serverAddress, null, new CompletionHandler() { + if (asyncResult != null) { + return asyncResult; + } - @Override - public void completed(@Nullable Void result, @Nullable Void attachment) { - LOGGER.info(channel, ch -> "Connected to server: " + NetworkUtils.getRemoteAddress(ch)); - asyncResult.complete(channelToConnection.apply(DefaultClientNetwork.this, channel)); - } + ThreadUtils.sleep(100); - @Override - public void failed(@NotNull Throwable exc, @Nullable Void attachment) { - asyncResult.completeExceptionally(exc); - } - }); + return connect(serverAddress); + } - pendingConnection = asyncResult; + var asyncResult = new CompletableFuture(); - return asyncResult.handle((connection, throwable) -> { - this.currentConnection = connection; - this.connecting.set(false); - return AsyncUtils.continueCompletableStage(connection, throwable); - }); - } + var channel = uncheckedGet(AsynchronousSocketChannel::open); + channel.connect( + serverAddress, null, new CompletionHandler() { - @Override - public @NotNull Mono connected(@NotNull InetSocketAddress serverAddress) { - return Mono.create(monoSink -> connect(serverAddress) - .whenComplete((connection, ex) -> { - if(ex != null) { - monoSink.error(ex); - } else { - monoSink.success(connection); - } - })); - } + @Override + public void completed(@Nullable Void result, @Nullable Void attachment) { + LOGGER.info(channel, ch -> "Connected to server: " + NetworkUtils.getRemoteAddress(ch)); + asyncResult.complete(channelToConnection.apply(DefaultClientNetwork.this, channel)); + } - @Override - public void shutdown() { - Optional - .ofNullable(getCurrentConnection()) - .ifPresent(connection -> unchecked(connection, C::close)); - } + @Override + public void failed(@NotNull Throwable exc, @Nullable Void attachment) { + asyncResult.completeExceptionally(exc); + } + }); + + pendingConnection = asyncResult; + + return asyncResult.handle((connection, throwable) -> { + this.currentConnection = connection; + this.connecting.set(false); + return AsyncUtils.continueCompletableStage(connection, throwable); + }); + } + + @Override + public @NotNull Mono connected(@NotNull InetSocketAddress serverAddress) { + return Mono.create(monoSink -> connect(serverAddress).whenComplete((connection, ex) -> { + if (ex != null) { + monoSink.error(ex); + } else { + monoSink.success(connection); + } + })); + } + + @Override + public void shutdown() { + Optional + .ofNullable(getCurrentConnection()) + .ifPresent(connection -> unchecked(connection, C::close)); + } } 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 b18666b6..c744f6d6 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 @@ -39,217 +39,220 @@ public abstract class AbstractConnection implements UnsafeConnection { - private static final Logger LOGGER = LoggerManager.getLogger(AbstractConnection.class); + private static final Logger LOGGER = LoggerManager.getLogger(AbstractConnection.class); - private static class WritablePacketWithFeedback extends - WritablePacketWrapper, W> { + private static class WritablePacketWithFeedback extends + WritablePacketWrapper, W> { - public WritablePacketWithFeedback(@NotNull CompletableFuture attachment, @NotNull W packet) { - super(attachment, packet); - } + public WritablePacketWithFeedback(@NotNull CompletableFuture attachment, @NotNull W packet) { + super(attachment, packet); } - - protected final @Getter @NotNull String remoteAddress; - - protected final @NotNull Network> network; - protected final @NotNull BufferAllocator bufferAllocator; - protected final @NotNull AsynchronousSocketChannel channel; - protected final @NotNull LinkedList pendingPackets; - protected final @NotNull StampedLock lock; - - protected final @NotNull AtomicBoolean isWriting; - protected final @NotNull AtomicBoolean closed; - - protected final @NotNull Array, ? super R>> subscribers; - - protected final int maxPacketsByRead; - - protected volatile @Getter long lastActivity; - - public AbstractConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - int maxPacketsByRead - ) { - this.bufferAllocator = bufferAllocator; - this.maxPacketsByRead = maxPacketsByRead; - this.lock = new StampedLock(); - this.channel = channel; - this.pendingPackets = LinkedListFactory.newLinkedList(WritablePacket.class); - this.network = network; - this.isWriting = new AtomicBoolean(false); - this.closed = new AtomicBoolean(false); - this.subscribers = ArrayFactory.newCopyOnModifyArray(NotNullBiConsumer.class); - this.remoteAddress = String.valueOf(NetworkUtils.getRemoteAddress(channel)); - } - - @Override - public void onConnected() {} - - protected abstract @NotNull PacketReader getPacketReader(); - - protected abstract @NotNull PacketWriter getPacketWriter(); - - protected void handleReceivedPacket(@NotNull R packet) { - LOGGER.debug( - channel, - packet, - (ch, pck) -> "Handle received packet: " + pck + " from: " + NetworkUtils.getRemoteAddress(ch) - ); - subscribers.forEachR(this, packet, BiConsumer::accept); - } - - @Override - public void onReceive(@NotNull NotNullBiConsumer, ? super R> consumer) { - subscribers.add(consumer); - getPacketReader().startRead(); - } - - @Override - public @NotNull Flux, ? extends R>> receivedEvents() { - return Flux.create(this::registerFluxOnReceivedEvents); + } + + protected final @Getter + @NotNull String remoteAddress; + + protected final @NotNull Network> network; + protected final @NotNull BufferAllocator bufferAllocator; + protected final @NotNull AsynchronousSocketChannel channel; + protected final @NotNull LinkedList pendingPackets; + protected final @NotNull StampedLock lock; + + protected final @NotNull AtomicBoolean isWriting; + protected final @NotNull AtomicBoolean closed; + + protected final @NotNull Array, ? super R>> subscribers; + + protected final int maxPacketsByRead; + + protected volatile @Getter long lastActivity; + + public AbstractConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + int maxPacketsByRead) { + this.bufferAllocator = bufferAllocator; + this.maxPacketsByRead = maxPacketsByRead; + this.lock = new StampedLock(); + this.channel = channel; + this.pendingPackets = LinkedListFactory.newLinkedList(WritablePacket.class); + this.network = network; + this.isWriting = new AtomicBoolean(false); + this.closed = new AtomicBoolean(false); + this.subscribers = ArrayFactory.newCopyOnModifyArray(NotNullBiConsumer.class); + this.remoteAddress = String.valueOf(NetworkUtils.getRemoteAddress(channel)); + } + + @Override + public void onConnected() { + } + + protected abstract @NotNull PacketReader getPacketReader(); + + protected abstract @NotNull PacketWriter getPacketWriter(); + + protected void handleReceivedPacket(@NotNull R packet) { + LOGGER.debug( + channel, + packet, + (ch, pck) -> "Handle received packet: " + pck + " from: " + NetworkUtils.getRemoteAddress(ch)); + subscribers.forEachR(this, packet, BiConsumer::accept); + } + + @Override + public void onReceive(@NotNull NotNullBiConsumer, ? super R> consumer) { + subscribers.add(consumer); + getPacketReader().startRead(); + } + + @Override + public @NotNull Flux, ? extends R>> receivedEvents() { + return Flux.create(this::registerFluxOnReceivedEvents); + } + + @Override + public @NotNull Flux receivedPackets() { + return Flux.create(this::registerFluxOnReceivedPackets); + } + + protected void registerFluxOnReceivedEvents( + @NotNull FluxSink, ? extends R>> sink) { + + NotNullBiConsumer, R> listener = + (connection, packet) -> sink.next(new ReceivedPacketEvent<>(connection, + packet)); + + onReceive(listener); + + sink.onDispose(() -> subscribers.remove(listener)); + } + + protected void registerFluxOnReceivedPackets(@NotNull FluxSink sink) { + + NotNullBiConsumer, R> listener = (connection, packet) -> sink.next(packet); + + onReceive(listener); + + sink.onDispose(() -> subscribers.remove(listener)); + } + + protected @Nullable WritablePacket nextPacketToWrite() { + long stamp = lock.writeLock(); + try { + return pendingPackets.poll(); + } finally { + lock.unlockWrite(stamp); } + } - @Override - public @NotNull Flux receivedPackets() { - return Flux.create(this::registerFluxOnReceivedPackets); + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + doClose(); } + } - protected void registerFluxOnReceivedEvents( - @NotNull FluxSink, ? extends R>> sink - ) { - - NotNullBiConsumer, R> listener = - (connection, packet) -> sink.next(new ReceivedPacketEvent<>(connection, packet)); + /** + * Does the process of closing this connection. + */ + protected void doClose() { - onReceive(listener); - - sink.onDispose(() -> subscribers.remove(listener)); + if (channel.isOpen()) { + unchecked(channel, AsynchronousChannel::close); } - protected void registerFluxOnReceivedPackets(@NotNull FluxSink sink) { + clearWaitPackets(); - NotNullBiConsumer, R> listener = (connection, packet) -> sink.next(packet); + getPacketReader().close(); + getPacketWriter().close(); + } - onReceive(listener); + /** + * Update the time of last activity. + */ + protected void updateLastActivity() { + this.lastActivity = System.currentTimeMillis(); + } - sink.onDispose(() -> subscribers.remove(listener)); - } + @Override + public boolean isClosed() { + return closed.get(); + } - protected @Nullable WritablePacket nextPacketToWrite() { - long stamp = lock.writeLock(); - try { - return pendingPackets.poll(); - } finally { - lock.unlockWrite(stamp); - } - } + protected void onWrittenPacket(@NotNull WritablePacket packet) { + } - @Override - public void close() { - if (closed.compareAndSet(false, true)) { - doClose(); - } + protected void onSentPacket(@NotNull WritablePacket packet, @NotNull Boolean result) { + if (packet instanceof WritablePacketWithFeedback) { + ((WritablePacketWithFeedback) packet) + .getAttachment() + .complete(result); } + } - /** - * Does the process of closing this connection. - */ - protected void doClose() { + @Override + public final void send(@NotNull W packet) { + sendImpl(packet); + } - if (channel.isOpen()) { - unchecked(channel, AsynchronousChannel::close); - } + protected void sendImpl(@NotNull WritablePacket packet) { - clearWaitPackets(); - - getPacketReader().close(); - getPacketWriter().close(); - } - - /** - * Update the time of last activity. - */ - protected void updateLastActivity() { - this.lastActivity = System.currentTimeMillis(); + if (isClosed()) { + return; } - @Override - public boolean isClosed() { - return closed.get(); + long stamp = lock.writeLock(); + try { + pendingPackets.add(packet); + } finally { + lock.unlockWrite(stamp); } - protected void onWrittenPacket(@NotNull WritablePacket packet) { } + getPacketWriter().writeNextPacket(); + } - protected void onSentPacket(@NotNull WritablePacket packet, @NotNull Boolean result) { - if (packet instanceof WritablePacketWithFeedback) { - ((WritablePacketWithFeedback) packet).getAttachment().complete(result); - } + protected void queueAtFirst(@NotNull WritablePacket packet) { + long stamp = lock.writeLock(); + try { + pendingPackets.addFirst(packet); + } finally { + lock.unlockWrite(stamp); } + } - @Override - public final void send(@NotNull W packet) { - sendImpl(packet); - } + @Override + public @NotNull CompletableFuture sendWithFeedback(@NotNull W packet) { - protected void sendImpl(@NotNull WritablePacket packet) { + var asyncResult = new CompletableFuture(); - if (isClosed()) { - return; - } + sendImpl(new WritablePacketWithFeedback<>(asyncResult, packet)); - long stamp = lock.writeLock(); - try { - pendingPackets.add(packet); - } finally { - lock.unlockWrite(stamp); - } - - getPacketWriter().writeNextPacket(); + if (isClosed()) { + return CompletableFuture.completedFuture(Boolean.FALSE); } - protected void queueAtFirst(@NotNull WritablePacket packet) { - long stamp = lock.writeLock(); - try { - pendingPackets.addFirst(packet); - } finally { - lock.unlockWrite(stamp); - } + return asyncResult; + } + + /** + * Clear waited packets. + */ + protected void clearWaitPackets() { + long stamp = lock.writeLock(); + try { + doClearWaitPackets(); + } finally { + lock.unlockWrite(stamp); } + } - @Override - public @NotNull CompletableFuture sendWithFeedback(@NotNull W packet) { - - var asyncResult = new CompletableFuture(); - - sendImpl(new WritablePacketWithFeedback<>(asyncResult, packet)); + protected void doClearWaitPackets() { - if (isClosed()) { - return CompletableFuture.completedFuture(Boolean.FALSE); - } - - return asyncResult; - } - - /** - * Clear waited packets. - */ - protected void clearWaitPackets() { - long stamp = lock.writeLock(); - try { - doClearWaitPackets(); - } finally { - lock.unlockWrite(stamp); - } + for (var pendingPacket : pendingPackets) { + onSentPacket(pendingPacket, Boolean.FALSE); } - protected void doClearWaitPackets() { - - for (var pendingPacket : pendingPackets) { - onSentPacket(pendingPacket, Boolean.FALSE); - } - - pendingPackets.clear(); - } + pendingPackets.clear(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java index f7508957..9b7cb91f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java @@ -16,16 +16,15 @@ */ public abstract class AbstractNetwork> implements Network { - protected static final Logger LOGGER = LoggerManager.getLogger(AbstractNetwork.class); + protected static final Logger LOGGER = LoggerManager.getLogger(AbstractNetwork.class); - protected final @NotNull NetworkConfig config; - protected final @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection; + protected final @NotNull NetworkConfig config; + protected final @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection; - protected AbstractNetwork( - @NotNull NetworkConfig config, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection - ) { - this.config = config; - this.channelToConnection = channelToConnection; - } + protected AbstractNetwork( + @NotNull NetworkConfig config, + @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + this.config = config; + this.channelToConnection = channelToConnection; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java index af6f71b4..b870ff79 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java @@ -14,29 +14,28 @@ public abstract class AbstractSSLConnection extends AbstractConnection { - protected final @NotNull SSLEngine sslEngine; + protected final @NotNull SSLEngine sslEngine; - public AbstractSSLConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext, - int maxPacketsByRead, - boolean clientMode - ) { - super(network, channel, bufferAllocator, maxPacketsByRead); - this.sslEngine = sslContext.createSSLEngine(); - this.sslEngine.setUseClientMode(clientMode); - try { - this.sslEngine.beginHandshake(); - } catch (SSLException e) { - throw new RuntimeException(e); - } + public AbstractSSLConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull SSLContext sslContext, + int maxPacketsByRead, + boolean clientMode) { + super(network, channel, bufferAllocator, maxPacketsByRead); + this.sslEngine = sslContext.createSSLEngine(); + this.sslEngine.setUseClientMode(clientMode); + try { + this.sslEngine.beginHandshake(); + } catch (SSLException e) { + throw new RuntimeException(e); } + } - @Override - protected void sendImpl(@NotNull WritablePacket packet) { - super.sendImpl(packet); - getPacketReader().startRead(); - } + @Override + protected void sendImpl(@NotNull WritablePacket packet) { + super.sendImpl(packet); + getPacketReader().startRead(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java index bc3011bf..9d139e8f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java @@ -18,77 +18,89 @@ @ToString public class DefaultBufferAllocator implements BufferAllocator { - private static final Logger LOGGER = LoggerManager.getLogger(DefaultBufferAllocator.class); + private static final Logger LOGGER = LoggerManager.getLogger(DefaultBufferAllocator.class); - protected final @NotNull Pool readBufferPool; - protected final @NotNull Pool pendingBufferPool; - protected final @NotNull Pool writeBufferPool; + protected final @NotNull Pool readBufferPool; + protected final @NotNull Pool pendingBufferPool; + protected final @NotNull Pool writeBufferPool; - protected final @NotNull NetworkConfig config; + protected final @NotNull NetworkConfig config; - public DefaultBufferAllocator(@NotNull NetworkConfig config) { - this.config = config; - this.readBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); - this.pendingBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); - this.writeBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); - } + public DefaultBufferAllocator(@NotNull NetworkConfig config) { + this.config = config; + this.readBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); + this.pendingBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); + this.writeBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); + } - @Override - public @NotNull ByteBuffer takeReadBuffer() { - var bufferSize = config.getReadBufferSize(); - LOGGER.debug(bufferSize, size -> "Allocate a new read buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - } + @Override + public @NotNull ByteBuffer takeReadBuffer() { + var bufferSize = config.getReadBufferSize(); + LOGGER.debug(bufferSize, size -> "Allocate a new read buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + } - @Override - public @NotNull ByteBuffer takePendingBuffer() { - var bufferSize = config.getPendingBufferSize(); - LOGGER.debug(bufferSize, size -> "Allocate a new pending buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - } + @Override + public @NotNull ByteBuffer takePendingBuffer() { + var bufferSize = config.getPendingBufferSize(); + LOGGER.debug(bufferSize, size -> "Allocate a new pending buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + } - @Override - public @NotNull ByteBuffer takeWriteBuffer() { - var bufferSize = config.getWriteBufferSize(); - LOGGER.debug(bufferSize, size -> "Allocate a new write buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - } + @Override + public @NotNull ByteBuffer takeWriteBuffer() { + var bufferSize = config.getWriteBufferSize(); + LOGGER.debug(bufferSize, size -> "Allocate a new write buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + } - @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { - LOGGER.debug(bufferSize, size -> "Allocate a new buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - } + @Override + public @NotNull ByteBuffer takeBuffer(int bufferSize) { + LOGGER.debug(bufferSize, size -> "Allocate a new buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + } - @Override - public @NotNull DefaultBufferAllocator putReadBuffer(@NotNull ByteBuffer buffer) { - LOGGER.debug("Skip storing a read buffer"); - return this; - } + @Override + public @NotNull DefaultBufferAllocator putReadBuffer(@NotNull ByteBuffer buffer) { + LOGGER.debug("Skip storing a read buffer"); + return this; + } - @Override - public @NotNull DefaultBufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer) { - LOGGER.debug("Skip storing a pending buffer"); - return this; - } + @Override + public @NotNull DefaultBufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer) { + LOGGER.debug("Skip storing a pending buffer"); + return this; + } - @Override - public @NotNull DefaultBufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer) { - LOGGER.debug("Skip storing a write buffer"); - return this; - } + @Override + public @NotNull DefaultBufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer) { + LOGGER.debug("Skip storing a write buffer"); + return this; + } - @Override - public @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer) { - LOGGER.debug("Skip storing a mapped byte buffer"); - return this; - } + @Override + public @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer) { + LOGGER.debug("Skip storing a mapped byte buffer"); + return this; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java index bfa599a1..db2d93b6 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java @@ -14,12 +14,11 @@ */ public class DefaultConnection extends IdBasedPacketConnection { - public DefaultConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry - ) { - super(network, channel, bufferAllocator, packetRegistry, 100, 2, 2); - } + public DefaultConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull ReadablePacketRegistry packetRegistry) { + super(network, channel, bufferAllocator, packetRegistry, 100, 2, 2); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java index 9feea0f2..f34f5afd 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java @@ -21,49 +21,46 @@ public abstract class DefaultDataConnection extends AbstractConnection { - private final @NotNull PacketReader packetReader; - private final @NotNull PacketWriter packetWriter; + private final @NotNull PacketReader packetReader; + private final @NotNull PacketWriter packetWriter; - private final int packetLengthHeaderSize; + private final int packetLengthHeaderSize; - public DefaultDataConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - int maxPacketsByRead, - int packetLengthHeaderSize - ) { - super(network, channel, bufferAllocator, maxPacketsByRead); - this.packetLengthHeaderSize = packetLengthHeaderSize; - this.packetReader = createPacketReader(); - this.packetWriter = createPacketWriter(); - } + public DefaultDataConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + int maxPacketsByRead, + int packetLengthHeaderSize) { + super(network, channel, bufferAllocator, maxPacketsByRead); + this.packetLengthHeaderSize = packetLengthHeaderSize; + this.packetReader = createPacketReader(); + this.packetWriter = createPacketWriter(); + } - protected @NotNull PacketReader createPacketReader() { - return new DefaultPacketReader<>( - this, - channel, - bufferAllocator, - this::updateLastActivity, - this::handleReceivedPacket, - value -> createReadablePacket(), - packetLengthHeaderSize, - maxPacketsByRead - ); - } + protected @NotNull PacketReader createPacketReader() { + return new DefaultPacketReader<>( + this, + channel, + bufferAllocator, + this::updateLastActivity, + this::handleReceivedPacket, + value -> createReadablePacket(), + packetLengthHeaderSize, + maxPacketsByRead); + } - protected @NotNull PacketWriter createPacketWriter() { - return new DefaultPacketWriter>( - this, - channel, - bufferAllocator, - this::updateLastActivity, - this::nextPacketToWrite, - this::onWrittenPacket, - this::onSentPacket, - packetLengthHeaderSize - ); - } + protected @NotNull PacketWriter createPacketWriter() { + return new DefaultPacketWriter>( + this, + channel, + bufferAllocator, + this::updateLastActivity, + this::nextPacketToWrite, + this::onWrittenPacket, + this::onSentPacket, + packetLengthHeaderSize); + } - protected abstract @NotNull R createReadablePacket(); + protected abstract @NotNull R createReadablePacket(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java index 528920ea..6ab0232a 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java @@ -22,56 +22,53 @@ public abstract class DefaultDataSSLConnection extends AbstractSSLConnection { - private final @NotNull PacketReader packetReader; - private final @NotNull PacketWriter packetWriter; + private final @NotNull PacketReader packetReader; + private final @NotNull PacketWriter packetWriter; - private final int packetLengthHeaderSize; + private final int packetLengthHeaderSize; - public DefaultDataSSLConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext, - int maxPacketsByRead, - int packetLengthHeaderSize, - boolean clientMode - ) { - super(network, channel, bufferAllocator, sslContext, maxPacketsByRead, clientMode); - this.packetLengthHeaderSize = packetLengthHeaderSize; - this.packetReader = createPacketReader(); - this.packetWriter = createPacketWriter(); - } + public DefaultDataSSLConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull SSLContext sslContext, + int maxPacketsByRead, + int packetLengthHeaderSize, + boolean clientMode) { + super(network, channel, bufferAllocator, sslContext, maxPacketsByRead, clientMode); + this.packetLengthHeaderSize = packetLengthHeaderSize; + this.packetReader = createPacketReader(); + this.packetWriter = createPacketWriter(); + } - protected @NotNull PacketReader createPacketReader() { - return new DefaultSSLPacketReader<>( - this, - channel, - bufferAllocator, - this::updateLastActivity, - this::handleReceivedPacket, - value -> createReadablePacket(), - sslEngine, - this::sendImpl, - packetLengthHeaderSize, - maxPacketsByRead - ); - } + protected @NotNull PacketReader createPacketReader() { + return new DefaultSSLPacketReader<>( + this, + channel, + bufferAllocator, + this::updateLastActivity, + this::handleReceivedPacket, + value -> createReadablePacket(), + sslEngine, + this::sendImpl, + packetLengthHeaderSize, + maxPacketsByRead); + } - protected @NotNull PacketWriter createPacketWriter() { - return new DefaultSSLPacketWriter>( - this, - channel, - bufferAllocator, - this::updateLastActivity, - this::nextPacketToWrite, - this::onWrittenPacket, - this::onSentPacket, - sslEngine, - this::sendImpl, - this::queueAtFirst, - packetLengthHeaderSize - ); - } + protected @NotNull PacketWriter createPacketWriter() { + return new DefaultSSLPacketWriter>( + this, + channel, + bufferAllocator, + this::updateLastActivity, + this::nextPacketToWrite, + this::onWrittenPacket, + this::onSentPacket, + sslEngine, + this::sendImpl, + this::queueAtFirst, + packetLengthHeaderSize); + } - protected abstract @NotNull R createReadablePacket(); + protected abstract @NotNull R createReadablePacket(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java index f3d73f29..a56a641b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java @@ -22,55 +22,52 @@ public class IdBasedPacketConnection, W extends IdBasedWritablePacket> extends AbstractConnection { - private final @NotNull PacketReader packetReader; - private final @NotNull PacketWriter packetWriter; - private final @NotNull ReadablePacketRegistry packetRegistry; + private final @NotNull PacketReader packetReader; + private final @NotNull PacketWriter packetWriter; + private final @NotNull ReadablePacketRegistry packetRegistry; - private final int packetLengthHeaderSize; - private final int packetIdHeaderSize; + private final int packetLengthHeaderSize; + private final int packetIdHeaderSize; - public IdBasedPacketConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry, - int maxPacketsByRead, - int packetLengthHeaderSize, - int packetIdHeaderSize - ) { - super(network, channel, bufferAllocator, maxPacketsByRead); - this.packetRegistry = packetRegistry; - this.packetLengthHeaderSize = packetLengthHeaderSize; - this.packetIdHeaderSize = packetIdHeaderSize; - this.packetReader = createPacketReader(); - this.packetWriter = createPacketWriter(); - } + public IdBasedPacketConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull ReadablePacketRegistry packetRegistry, + int maxPacketsByRead, + int packetLengthHeaderSize, + int packetIdHeaderSize) { + super(network, channel, bufferAllocator, maxPacketsByRead); + this.packetRegistry = packetRegistry; + this.packetLengthHeaderSize = packetLengthHeaderSize; + this.packetIdHeaderSize = packetIdHeaderSize; + this.packetReader = createPacketReader(); + this.packetWriter = createPacketWriter(); + } - protected @NotNull PacketReader createPacketReader() { - return new IdBasedPacketReader<>( - this, - channel, - bufferAllocator, - this::updateLastActivity, - this::handleReceivedPacket, - packetLengthHeaderSize, - maxPacketsByRead, - packetIdHeaderSize, - packetRegistry - ); - } + protected @NotNull PacketReader createPacketReader() { + return new IdBasedPacketReader<>( + this, + channel, + bufferAllocator, + this::updateLastActivity, + this::handleReceivedPacket, + packetLengthHeaderSize, + maxPacketsByRead, + packetIdHeaderSize, + packetRegistry); + } - protected @NotNull PacketWriter createPacketWriter() { - return new IdBasedPacketWriter<>( - this, - channel, - bufferAllocator, - this::updateLastActivity, - this::nextPacketToWrite, - this::onWrittenPacket, - this::onSentPacket, - packetLengthHeaderSize, - packetIdHeaderSize - ); - } + protected @NotNull PacketWriter createPacketWriter() { + return new IdBasedPacketWriter<>( + this, + channel, + bufferAllocator, + this::updateLastActivity, + this::nextPacketToWrite, + this::onWrittenPacket, + this::onSentPacket, + packetLengthHeaderSize, + packetIdHeaderSize); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/PackedIdBasedConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/PackedIdBasedConnection.java index 4cf933bc..9589f06e 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/PackedIdBasedConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/PackedIdBasedConnection.java @@ -9,17 +9,17 @@ */ public interface PackedIdBasedConnection extends Connection { - /** - * Get length of packet's header with packet's data length. - * - * @return the length of packet's header with packet's data length. - */ - int getPacketLengthHeaderSize(); + /** + * Get length of packet's header with packet's data length. + * + * @return the length of packet's header with packet's data length. + */ + int getPacketLengthHeaderSize(); - /** - * Get length of packet's header with packet's id. - * - * @return the length of packet's header with packet's id. - */ - int getPacketIdHeaderSize(); + /** + * Get length of packet's header with packet's id. + * + * @return the length of packet's header with packet's id. + */ + int getPacketIdHeaderSize(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java index 59fa9983..7ad99be2 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java @@ -20,130 +20,139 @@ @ToString public class ReuseBufferAllocator implements BufferAllocator { - protected static final Logger LOGGER = LoggerManager.getLogger(ReuseBufferAllocator.class); - - protected final @NotNull Pool readBufferPool; - protected final @NotNull Pool pendingBufferPool; - protected final @NotNull Pool writeBufferPool; - protected final @NotNull ConcurrentArray byteBuffers; - - protected final @NotNull NetworkConfig config; - - public ReuseBufferAllocator(@NotNull NetworkConfig config) { - this.config = config; - this.readBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); - this.pendingBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); - this.writeBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); - this.byteBuffers = ArrayFactory.newConcurrentStampedLockArray(ByteBuffer.class); - } - - @Override - public @NotNull ByteBuffer takeReadBuffer() { - return readBufferPool.take(config, readBufferFactory()) - .clear(); - } - - @Override - public @NotNull ByteBuffer takePendingBuffer() { - return pendingBufferPool.take(config, pendingBufferFactory()) - .clear(); - } - - @Override - public @NotNull ByteBuffer takeWriteBuffer() { - return writeBufferPool.take(config, writeBufferFactory()) - .clear(); - } - - protected @NotNull Function pendingBufferFactory() { - return config -> { - var bufferSize = config.getPendingBufferSize(); - LOGGER.debug(bufferSize, size -> "Allocate a new pending buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - }; - } - - protected @NotNull Function readBufferFactory() { - return config -> { - var bufferSize = config.getReadBufferSize(); - LOGGER.debug(bufferSize, size -> "Allocate a new read buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - }; - } - - protected @NotNull Function writeBufferFactory() { - return config -> { - var bufferSize = config.getWriteBufferSize(); - LOGGER.debug(bufferSize, size -> "Allocate a new write buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - }; - } - - @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { - - // check of existing enough buffer for the size under read lock - var exist = byteBuffers.findAnyInReadLock( - bufferSize, - (required, buffer) -> required < buffer.capacity() - ); - - // if we already possible have this buffer we need to take it under write lock - if (exist != null) { - long stamp = byteBuffers.writeLock(); - try { - - // re-find enough buffer again - exist = byteBuffers.findAny( - bufferSize, - (required, buffer) -> required < buffer.capacity() - ); - - // take it from pool if exist - if (exist != null && byteBuffers.fastRemove(exist)) { - LOGGER.debug(exist, buffer -> "Reuse old buffer: " + buffer + " - (" + buffer.hashCode() + ")"); - return exist; - } - - } finally { - byteBuffers.writeUnlock(stamp); - } + protected static final Logger LOGGER = LoggerManager.getLogger(ReuseBufferAllocator.class); + + protected final @NotNull Pool readBufferPool; + protected final @NotNull Pool pendingBufferPool; + protected final @NotNull Pool writeBufferPool; + protected final @NotNull ConcurrentArray byteBuffers; + + protected final @NotNull NetworkConfig config; + + public ReuseBufferAllocator(@NotNull NetworkConfig config) { + this.config = config; + this.readBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); + this.pendingBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); + this.writeBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); + this.byteBuffers = ArrayFactory.newConcurrentStampedLockArray(ByteBuffer.class); + } + + @Override + public @NotNull ByteBuffer takeReadBuffer() { + return readBufferPool + .take(config, readBufferFactory()) + .clear(); + } + + @Override + public @NotNull ByteBuffer takePendingBuffer() { + return pendingBufferPool + .take(config, pendingBufferFactory()) + .clear(); + } + + @Override + public @NotNull ByteBuffer takeWriteBuffer() { + return writeBufferPool + .take(config, writeBufferFactory()) + .clear(); + } + + protected @NotNull Function pendingBufferFactory() { + return config -> { + var bufferSize = config.getPendingBufferSize(); + LOGGER.debug(bufferSize, size -> "Allocate a new pending buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + }; + } + + protected @NotNull Function readBufferFactory() { + return config -> { + var bufferSize = config.getReadBufferSize(); + LOGGER.debug(bufferSize, size -> "Allocate a new read buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + }; + } + + protected @NotNull Function writeBufferFactory() { + return config -> { + var bufferSize = config.getWriteBufferSize(); + LOGGER.debug(bufferSize, size -> "Allocate a new write buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + }; + } + + @Override + public @NotNull ByteBuffer takeBuffer(int bufferSize) { + + // check of existing enough buffer for the size under read lock + var exist = byteBuffers.findAnyInReadLock(bufferSize, (required, buffer) -> required < buffer.capacity()); + + // if we already possible have this buffer we need to take it under write lock + if (exist != null) { + long stamp = byteBuffers.writeLock(); + try { + + // re-find enough buffer again + exist = byteBuffers.findAny(bufferSize, (required, buffer) -> required < buffer.capacity()); + + // take it from pool if exist + if (exist != null && byteBuffers.fastRemove(exist)) { + LOGGER.debug(exist, buffer -> "Reuse old buffer: " + buffer + " - (" + buffer.hashCode() + ")"); + return exist; } - LOGGER.debug(bufferSize, size -> "Allocate a new buffer with size: " + size); - return config.isDirectByteBuffer()? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize) - .order(config.getByteOrder()) - .clear(); - } - - @Override - public @NotNull ReuseBufferAllocator putReadBuffer(@NotNull ByteBuffer buffer) { - readBufferPool.put(buffer); - return this; - } - - @Override - public @NotNull ReuseBufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer) { - pendingBufferPool.put(buffer); - return this; + } finally { + byteBuffers.writeUnlock(stamp); + } } - @Override - public @NotNull ReuseBufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer) { - writeBufferPool.put(buffer); - return this; - } - - @Override - public @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer) { - LOGGER.debug(buffer, buf -> "Save used temp buffer: " + buf + " - (" + buf.hashCode() + ")"); - byteBuffers.runInWriteLock(buffer.clear(), Collection::add); - return this; - } + LOGGER.debug(bufferSize, size -> "Allocate a new buffer with size: " + size); + return config.isDirectByteBuffer() + ? ByteBuffer.allocateDirect(bufferSize) + : ByteBuffer + .allocate(bufferSize) + .order(config.getByteOrder()) + .clear(); + } + + @Override + public @NotNull ReuseBufferAllocator putReadBuffer(@NotNull ByteBuffer buffer) { + readBufferPool.put(buffer); + return this; + } + + @Override + public @NotNull ReuseBufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer) { + pendingBufferPool.put(buffer); + return this; + } + + @Override + public @NotNull ReuseBufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer) { + writeBufferPool.put(buffer); + return this; + } + + @Override + public @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer) { + LOGGER.debug(buffer, buf -> "Save used temp buffer: " + buf + " - (" + buf.hashCode() + ")"); + byteBuffers.runInWriteLock(buffer.clear(), Collection::add); + return this; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java index 4b6cdfce..4cd47239 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java @@ -13,16 +13,15 @@ */ public class StringDataConnection extends DefaultDataConnection { - public StringDataConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator - ) { - super(network, channel, bufferAllocator, 100, 2); - } + public StringDataConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator) { + super(network, channel, bufferAllocator, 100, 2); + } - @Override - protected @NotNull StringReadablePacket createReadablePacket() { - return new StringReadablePacket(); - } + @Override + protected @NotNull StringReadablePacket createReadablePacket() { + return new StringReadablePacket(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java index 68a9719c..eae9626e 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java @@ -14,18 +14,17 @@ */ public class StringDataSSLConnection extends DefaultDataSSLConnection { - public StringDataSSLConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext, - boolean clientMode - ) { - super(network, channel, bufferAllocator, sslContext, 100, 2, clientMode); - } + public StringDataSSLConnection( + @NotNull Network> network, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull SSLContext sslContext, + boolean clientMode) { + super(network, channel, bufferAllocator, sslContext, 100, 2, clientMode); + } - @Override - protected @NotNull StringReadablePacket createReadablePacket() { - return new StringReadablePacket(); - } + @Override + protected @NotNull StringReadablePacket createReadablePacket() { + return new StringReadablePacket(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedPacket.java index 468a7592..7be950ab 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedPacket.java @@ -7,14 +7,14 @@ */ public interface IdBasedPacket extends Packet { - /** - * Get id of this packet. - * - * @return the packet type's id. - */ - default int getPacketId() { - return getClass() - .getAnnotation(PacketDescription.class) - .id(); - } + /** + * Get id of this packet. + * + * @return the packet type's id. + */ + default int getPacketId() { + return getClass() + .getAnnotation(PacketDescription.class) + .id(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java index bcc88ca0..163b2310 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java @@ -9,21 +9,21 @@ */ public interface IdBasedReadablePacket> extends ReadablePacket, IdBasedPacket { - /** - * Create a new instance of this type. - * - * @return the new instance of this type. - */ - default @NotNull S newInstance() { - return ClassUtils.newInstance(getClass()); - } + /** + * Create a new instance of this type. + * + * @return the new instance of this type. + */ + default @NotNull S newInstance() { + return ClassUtils.newInstance(getClass()); + } - /** - * Execute a logic of this packet. - * - * @param connection the owner's connection. - */ - default void execute(@NotNull Connection connection) { + /** + * Execute a logic of this packet. + * + * @param connection the owner's connection. + */ + default void execute(@NotNull Connection connection) { - } + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java index e4663c6f..23bfa123 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java @@ -9,10 +9,10 @@ */ public interface Packet { - /** - * Get packet's name. - * - * @return the packet's name. - */ - @NotNull String getName(); + /** + * Get packet's name. + * + * @return the packet's name. + */ + @NotNull String getName(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketReader.java index ebf88793..1940e916 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketReader.java @@ -5,13 +5,13 @@ */ public interface PacketReader { - /** - * Activate a process of receiving packets. - */ - void startRead(); + /** + * Activate a process of receiving packets. + */ + void startRead(); - /** - * Close all used resources. - */ - void close(); + /** + * Close all used resources. + */ + void close(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketWriter.java index 1d918cea..db1d428c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/PacketWriter.java @@ -5,10 +5,10 @@ */ public interface PacketWriter { - void writeNextPacket(); + void writeNextPacket(); - /** - * Close all used resources. - */ - void close(); + /** + * Close all used resources. + */ + void close(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java index 14f5e88a..6487e044 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java @@ -11,13 +11,13 @@ */ public interface ReadablePacket extends Packet { - /** - * Read packet's data from byte buffer. - * - * @param connection the network connection. - * @param buffer the buffer with received data. - * @param length the data length. - * @return true if reading was success. - */ - boolean read(@NotNull Connection connection, @NotNull ByteBuffer buffer, int length); + /** + * Read packet's data from byte buffer. + * + * @param connection the network connection. + * @param buffer the buffer with received data. + * @param length the data length. + * @return true if reading was success. + */ + boolean read(@NotNull Connection connection, @NotNull ByteBuffer buffer, int length); } 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 a313507d..9ce22f30 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 @@ -11,48 +11,48 @@ */ public interface ReusableWritablePacket extends WritablePacket, Reusable { - /** - * Handle completion of packet sending. - */ - void complete(); - - /** - * Force complete this packet. - */ - void forceComplete(); - - /** - * Decrease sending count. - */ - void decreaseSends(); - - /** - * Decrease sending count. - * - * @param count the count. - */ - void decreaseSends(int count); - - /** - * Increase sending count. - */ - void increaseSends(); - - /** - * Increase sending count. - * - * @param count the count. - */ - void increaseSends(int count); - - /** - * Set the pool. - * - * @param pool the pool to store used packet. - */ - void setPool(@NotNull Pool pool); - - default void notifyAddedToSend() { - increaseSends(); - } + /** + * Handle completion of packet sending. + */ + void complete(); + + /** + * Force complete this packet. + */ + void forceComplete(); + + /** + * Decrease sending count. + */ + void decreaseSends(); + + /** + * Decrease sending count. + * + * @param count the count. + */ + void decreaseSends(int count); + + /** + * Increase sending count. + */ + void increaseSends(); + + /** + * Increase sending count. + * + * @param count the count. + */ + void increaseSends(int count); + + /** + * Set the pool. + * + * @param pool the pool to store used packet. + */ + void setPool(@NotNull Pool pool); + + default void notifyAddedToSend() { + increaseSends(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java index bc422dd4..db51eead 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java @@ -12,123 +12,125 @@ */ public interface WritablePacket extends Packet { - /** - * Write this packet to the buffer. - * - * @param buffer the buffer. - * @return true if writing was successful. - */ - boolean write(@NotNull ByteBuffer buffer); - - /** - * Return an expected data length of this packet or -1. - * - * @return expected data length of this packet or -1. - */ - default int getExpectedLength() { - return -1; - } - - /** - * Write 1 byte to the buffer. - * - * @param buffer the buffer. - * @param value the value. - */ - default void writeByte(@NotNull ByteBuffer buffer, int value) { - buffer.put((byte) value); - } - - /** - * Write 2 bytes to the buffer. - * - * @param buffer the buffer. - * @param value the value. - */ - default void writeChar(@NotNull ByteBuffer buffer, char value) { - buffer.putChar(value); - } - - /** - * Write 2 bytes to the buffer. - * - * @param buffer the buffer. - * @param value the value. - */ - default void writeChar(@NotNull final ByteBuffer buffer, final int value) { - buffer.putChar((char) value); - } - - /** - * Write 4 bytes to the buffer. - * - * @param buffer the buffer. - * @param value the value. - */ - default void writeFloat(@NotNull ByteBuffer buffer, float value) { - buffer.putFloat(value); - } - - /** - * Write 4 bytes to the buffer. - * - * @param buffer the buffer. - * @param value the value. - */ - default void writeInt(@NotNull ByteBuffer buffer, int value) { - buffer.putInt(value); - } - - /** - * Write 8 bytes to the buffer. - * - * @param buffer the buffer. - * @param value the value. - */ - default void writeLong(@NotNull ByteBuffer buffer, long value) { - buffer.putLong(value); - } - - /** - * Writes 2 bytes to the buffer. - * - * @param buffer the buffer. - * @param value the value for writing. - */ - default void writeShort(@NotNull ByteBuffer buffer, int value) { - buffer.putShort((short) value); - } - - /** - * Writes the string to the buffer. - * - * @param buffer the buffer. - * @param string the string for writing. - */ - default void writeString(@NotNull ByteBuffer buffer, @NotNull String string) { - try { - - writeInt(buffer, string.length()); - - for (int i = 0, length = string.length(); i < length; i++) { - buffer.putChar(string.charAt(i)); - } - - } catch (BufferOverflowException ex) { - LoggerManager.getLogger(WritablePacket.class) - .error("Cannot write a string to buffer because the string is too long." + - " String length: " + string.length() + ", buffer: " + buffer); - throw ex; - } - } - - /** - * Write a data buffer to packet buffer. - * - * @param buffer thr packet buffer. - * @param data the data buffer. - */ - default void writeBuffer(@NotNull ByteBuffer buffer, @NotNull ByteBuffer data) { - buffer.put(data.array(), data.position(), data.limit()); + /** + * Write this packet to the buffer. + * + * @param buffer the buffer. + * @return true if writing was successful. + */ + boolean write(@NotNull ByteBuffer buffer); + + /** + * Return an expected data length of this packet or -1. + * + * @return expected data length of this packet or -1. + */ + default int getExpectedLength() { + return -1; + } + + /** + * Write 1 byte to the buffer. + * + * @param buffer the buffer. + * @param value the value. + */ + default void writeByte(@NotNull ByteBuffer buffer, int value) { + buffer.put((byte) value); + } + + /** + * Write 2 bytes to the buffer. + * + * @param buffer the buffer. + * @param value the value. + */ + default void writeChar(@NotNull ByteBuffer buffer, char value) { + buffer.putChar(value); + } + + /** + * Write 2 bytes to the buffer. + * + * @param buffer the buffer. + * @param value the value. + */ + default void writeChar(@NotNull final ByteBuffer buffer, final int value) { + buffer.putChar((char) value); + } + + /** + * Write 4 bytes to the buffer. + * + * @param buffer the buffer. + * @param value the value. + */ + default void writeFloat(@NotNull ByteBuffer buffer, float value) { + buffer.putFloat(value); + } + + /** + * Write 4 bytes to the buffer. + * + * @param buffer the buffer. + * @param value the value. + */ + default void writeInt(@NotNull ByteBuffer buffer, int value) { + buffer.putInt(value); + } + + /** + * Write 8 bytes to the buffer. + * + * @param buffer the buffer. + * @param value the value. + */ + default void writeLong(@NotNull ByteBuffer buffer, long value) { + buffer.putLong(value); + } + + /** + * Writes 2 bytes to the buffer. + * + * @param buffer the buffer. + * @param value the value for writing. + */ + default void writeShort(@NotNull ByteBuffer buffer, int value) { + buffer.putShort((short) value); + } + + /** + * Writes the string to the buffer. + * + * @param buffer the buffer. + * @param string the string for writing. + */ + default void writeString(@NotNull ByteBuffer buffer, @NotNull String string) { + try { + + writeInt(buffer, string.length()); + + for (int i = 0, length = string.length(); i < length; i++) { + buffer.putChar(string.charAt(i)); + } + + } catch (BufferOverflowException ex) { + LoggerManager + .getLogger(WritablePacket.class) + .error( + "Cannot write a string to buffer because the string is too long." + " String length: " + string.length() + + ", buffer: " + buffer); + throw ex; } + } + + /** + * Write a data buffer to packet buffer. + * + * @param buffer thr packet buffer. + * @param data the data buffer. + */ + default void writeBuffer(@NotNull ByteBuffer buffer, @NotNull ByteBuffer data) { + buffer.put(data.array(), data.position(), data.limit()); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java index 2c63473d..9e4c962e 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java @@ -10,20 +10,21 @@ /** * @author JavaSaBr */ -public abstract class AbstractIdBasedReadablePacket, S extends AbstractIdBasedReadablePacket> extends +public abstract class AbstractIdBasedReadablePacket, + S extends AbstractIdBasedReadablePacket> extends AbstractReadablePacket implements IdBasedReadablePacket { - private static final Logger LOGGER = LoggerManager.getLogger(AbstractIdBasedReadablePacket.class); + private static final Logger LOGGER = LoggerManager.getLogger(AbstractIdBasedReadablePacket.class); - @Override - public void execute(@NotNull Connection connection) { - try { - executeImpl(ClassUtils.unsafeNNCast(connection)); - } catch (Exception e) { - LOGGER.error(e); - } + @Override + public void execute(@NotNull Connection connection) { + try { + executeImpl(ClassUtils.unsafeNNCast(connection)); + } catch (Exception e) { + LOGGER.error(e); } + } - protected void executeImpl(@NotNull C connection) { - } + protected void executeImpl(@NotNull C connection) { + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java index f48075a7..4004e12f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java @@ -15,33 +15,33 @@ */ public abstract class AbstractPacket implements Packet { - protected static final Logger LOGGER = LoggerManager.getLogger(Packet.class); - - /** - * Handle the exception. - * - * @param buffer the data buffer. - * @param exception the exception. - */ - protected void handleException(@NotNull ByteBuffer buffer, @NotNull Exception exception) { - LOGGER.warning(exception); - - if (buffer.isDirect()) { - var array = new byte[buffer.limit()]; - buffer.get(array, 0, buffer.limit()); - LOGGER.warning(getName() + " -> buffer: " + buffer + "\n" + hexDump(array, array.length)); - } else { - LOGGER.warning(getName() + " -> buffer: " + buffer + "\n" + hexDump(buffer.array(), buffer.limit())); - } + protected static final Logger LOGGER = LoggerManager.getLogger(Packet.class); + + /** + * Handle the exception. + * + * @param buffer the data buffer. + * @param exception the exception. + */ + protected void handleException(@NotNull ByteBuffer buffer, @NotNull Exception exception) { + LOGGER.warning(exception); + + if (buffer.isDirect()) { + var array = new byte[buffer.limit()]; + buffer.get(array, 0, buffer.limit()); + LOGGER.warning(getName() + " -> buffer: " + buffer + "\n" + hexDump(array, array.length)); + } else { + LOGGER.warning(getName() + " -> buffer: " + buffer + "\n" + hexDump(buffer.array(), buffer.limit())); } + } - @Override - public @NotNull String getName() { - return getClass().getSimpleName(); - } + @Override + public @NotNull String getName() { + return getClass().getSimpleName(); + } - @Override - public String toString() { - return getClass().getSimpleName() + "{" + "name='" + getName() + '\'' + '}'; - } + @Override + public String toString() { + return getClass().getSimpleName() + "{" + "name='" + getName() + '\'' + '}'; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java index d16522b8..8bd26bdb 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java @@ -32,472 +32,449 @@ public abstract class AbstractPacketReader> implements PacketReader { - private static final Logger LOGGER = LoggerManager.getLogger(AbstractPacketReader.class); + private static final Logger LOGGER = LoggerManager.getLogger(AbstractPacketReader.class); - private final CompletionHandler readHandler = new CompletionHandler<>() { + private final CompletionHandler readHandler = new CompletionHandler<>() { - @Override - public void completed(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { - handleReceivedData(receivedBytes, readingBuffer); - } - - @Override - public void failed(@NotNull Throwable exc, @NotNull ByteBuffer readingBuffer) { - handleFailedReceiving(exc, readingBuffer); - } - }; - - protected final @NotNull AtomicBoolean isReading = new AtomicBoolean(false); - - protected final @NotNull C connection; - protected final @NotNull AsynchronousSocketChannel channel; - protected final @NotNull BufferAllocator bufferAllocator; - - protected final @NotNull ByteBuffer readBuffer; - protected final @NotNull ByteBuffer pendingBuffer; - - protected final @NotNull Runnable updateActivityFunction; - protected final @NotNull Consumer readPacketHandler; - - @Getter(AccessLevel.PROTECTED) - @Setter(AccessLevel.PROTECTED) - protected volatile @Nullable ByteBuffer tempPendingBuffer; - - protected final int maxPacketsByRead; - - protected AbstractPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, - int maxPacketsByRead - ) { - this.connection = connection; - this.channel = channel; - this.bufferAllocator = bufferAllocator; - this.readBuffer = bufferAllocator.takeReadBuffer(); - this.pendingBuffer = bufferAllocator.takePendingBuffer(); - this.updateActivityFunction = updateActivityFunction; - this.readPacketHandler = readPacketHandler; - this.maxPacketsByRead = maxPacketsByRead; + @Override + public void completed(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { + handleReceivedData(receivedBytes, readingBuffer); } - protected @NotNull ByteBuffer getBufferToReadFromChannel() { - return readBuffer; + @Override + public void failed(@NotNull Throwable exc, @NotNull ByteBuffer readingBuffer) { + handleFailedReceiving(exc, readingBuffer); + } + }; + + protected final @NotNull AtomicBoolean isReading = new AtomicBoolean(false); + + protected final @NotNull C connection; + protected final @NotNull AsynchronousSocketChannel channel; + protected final @NotNull BufferAllocator bufferAllocator; + + protected final @NotNull ByteBuffer readBuffer; + protected final @NotNull ByteBuffer pendingBuffer; + + protected final @NotNull Runnable updateActivityFunction; + protected final @NotNull Consumer readPacketHandler; + + @Getter(AccessLevel.PROTECTED) + @Setter(AccessLevel.PROTECTED) + protected volatile @Nullable ByteBuffer tempPendingBuffer; + + protected final int maxPacketsByRead; + + protected AbstractPacketReader( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NotNullConsumer readPacketHandler, + int maxPacketsByRead) { + this.connection = connection; + this.channel = channel; + this.bufferAllocator = bufferAllocator; + this.readBuffer = bufferAllocator.takeReadBuffer(); + this.pendingBuffer = bufferAllocator.takePendingBuffer(); + this.updateActivityFunction = updateActivityFunction; + this.readPacketHandler = readPacketHandler; + this.maxPacketsByRead = maxPacketsByRead; + } + + protected @NotNull ByteBuffer getBufferToReadFromChannel() { + return readBuffer; + } + + @Override + public void startRead() { + + if (!isReading.compareAndSet(false, true)) { + return; } - @Override - public void startRead() { + LOGGER.debug(channel, ch -> "Start waiting for new data from channel \"" + getRemoteAddress(ch) + "\""); - if (!isReading.compareAndSet(false, true)) { - return; - } + var buffer = getBufferToReadFromChannel(); - LOGGER.debug(channel, ch -> "Start waiting for new data from channel \"" + getRemoteAddress(ch) + "\""); + channel.read(buffer, buffer, readHandler); + } - var buffer = getBufferToReadFromChannel(); + /** + * Read packets from the buffer with received data. + * + * @param receivedBuffer the buffer with received data. + * @return count of read packets. + */ + protected int readPackets(@NotNull ByteBuffer receivedBuffer) { + return readPackets(receivedBuffer, pendingBuffer); + } - channel.read(buffer, buffer, readHandler); - } + /** + * Read packets from the buffer with received data. + * + * @param receivedBuffer the buffer with received data. + * @param pendingBuffer the buffer with pending data from prev. received buffer. + * @return count of read packets. + */ + protected int readPackets(@NotNull ByteBuffer receivedBuffer, @NotNull ByteBuffer pendingBuffer) { + + LOGGER.debug(receivedBuffer, buf -> "Start reading packets from received buffer " + buf); + + var waitedBytes = pendingBuffer.position(); + var bufferToRead = receivedBuffer; + var tempPendingBuffer = getTempPendingBuffer(); + + // if we have a temp buffer it means that we are reading a really big packet now + if (tempPendingBuffer != null) { + + if (tempPendingBuffer.remaining() < receivedBuffer.remaining()) { + reAllocTempBuffers(tempPendingBuffer.flip(), tempPendingBuffer.capacity()); + tempPendingBuffer = notNull(getTempPendingBuffer()); + } + + LOGGER.debug( + receivedBuffer, + tempPendingBuffer, + (buf, mappedBuf) -> "Put received buffer " + buf + " to read mapped buffer " + mappedBuf); - /** - * Read packets from the buffer with received data. - * - * @param receivedBuffer the buffer with received data. - * @return count of read packets. - */ - protected int readPackets(@NotNull ByteBuffer receivedBuffer) { - return readPackets(receivedBuffer, pendingBuffer); + bufferToRead = BufferUtils.putToAndFlip(tempPendingBuffer, receivedBuffer); } + // if we have some pending data we need to append the received buffer to the pending buffer + // and start to read pending buffer with result received data + else if (waitedBytes > 0) { - /** - * Read packets from the buffer with received data. - * - * @param receivedBuffer the buffer with received data. - * @param pendingBuffer the buffer with pending data from prev. received buffer. - * @return count of read packets. - */ - protected int readPackets(@NotNull ByteBuffer receivedBuffer, @NotNull ByteBuffer pendingBuffer) { + if (pendingBuffer.remaining() < receivedBuffer.remaining()) { - LOGGER.debug(receivedBuffer, buf -> "Start reading packets from received buffer " + buf); + LOGGER.debug( + pendingBuffer, + receivedBuffer, + (penBuf, buf) -> "Pending buffer " + penBuf + " is too small to append received buffer " + buf + + ", will allocate new temp buffer for this"); - var waitedBytes = pendingBuffer.position(); - var bufferToRead = receivedBuffer; - var tempPendingBuffer = getTempPendingBuffer(); + allocTempBuffers(pendingBuffer.flip(), pendingBuffer.capacity()); - // if we have a temp buffer it means that we are reading a really big packet now - if (tempPendingBuffer != null) { + LOGGER.debug(pendingBuffer, buf -> "Clear pending buffer: " + buf); - if (tempPendingBuffer.remaining() < receivedBuffer.remaining()) { - reAllocTempBuffers(tempPendingBuffer.flip(), tempPendingBuffer.capacity()); - tempPendingBuffer = notNull(getTempPendingBuffer()); - } + pendingBuffer.clear(); - LOGGER.debug( - receivedBuffer, - tempPendingBuffer, - (buf, mappedBuf) -> "Put received buffer " + buf + " to read mapped buffer " + mappedBuf - ); + tempPendingBuffer = notNull(getTempPendingBuffer()); - bufferToRead = BufferUtils.putToAndFlip(tempPendingBuffer, receivedBuffer); - } - // if we have some pending data we need to append the received buffer to the pending buffer - // and start to read pending buffer with result received data - else if (waitedBytes > 0) { + LOGGER.debugNullable( + receivedBuffer, + tempPendingBuffer, + (buf, mappedBuf) -> "Put received buffer: " + buf + " to mapped buffer: " + mappedBuf); - if (pendingBuffer.remaining() < receivedBuffer.remaining()) { + bufferToRead = BufferUtils.putToAndFlip(tempPendingBuffer, receivedBuffer); - LOGGER.debug( - pendingBuffer, - receivedBuffer, - (penBuf, buf) -> "Pending buffer " + penBuf + " is too small to append received buffer " + - buf + ", will allocate new temp buffer for this" - ); + } else { - allocTempBuffers(pendingBuffer.flip(), pendingBuffer.capacity()); + LOGGER.debug( + receivedBuffer, + pendingBuffer, + (buf, penBuf) -> "Put received buffer: " + buf + " to pending buffer: " + penBuf); - LOGGER.debug(pendingBuffer, buf -> "Clear pending buffer: " + buf); + bufferToRead = BufferUtils.putToAndFlip(pendingBuffer, receivedBuffer); + } + } - pendingBuffer.clear(); + var maxPacketsByRead = getMaxPacketsByRead(); - tempPendingBuffer = notNull(getTempPendingBuffer()); + var readPackets = 0; + var endPosition = 0; - LOGGER.debugNullable( - receivedBuffer, - tempPendingBuffer, - (buf, mappedBuf) -> "Put received buffer: " + buf + " to mapped buffer: " + mappedBuf - ); + while (canStartReadPacket(bufferToRead) && readPackets < maxPacketsByRead) { - bufferToRead = BufferUtils.putToAndFlip(tempPendingBuffer, receivedBuffer); + // set position of start a next packet + bufferToRead.position(endPosition); - } else { + var positionBeforeRead = endPosition; + var packetLength = readPacketLength(bufferToRead); + var dataLength = getDataLength(packetLength, bufferToRead.position() - endPosition, bufferToRead); - LOGGER.debug( - receivedBuffer, - pendingBuffer, - (buf, penBuf) -> "Put received buffer: " + buf + " to pending buffer: " + penBuf - ); + LOGGER.debug( + packetLength, + positionBeforeRead, + (length, pos) -> "Find next packet from position: " + pos + " with length: " + length); - bufferToRead = BufferUtils.putToAndFlip(pendingBuffer, receivedBuffer); - } - } + // calculate position of end the next packet + endPosition += packetLength; + + // if the packet isn't full presented in this buffer + if (packetLength == -1 || endPosition > bufferToRead.limit()) { + + bufferToRead.position(positionBeforeRead); - var maxPacketsByRead = getMaxPacketsByRead(); - - var readPackets = 0; - var endPosition = 0; - - while (canStartReadPacket(bufferToRead) && readPackets < maxPacketsByRead) { - - // set position of start a next packet - bufferToRead.position(endPosition); - - var positionBeforeRead = endPosition; - var packetLength = readPacketLength(bufferToRead); - var dataLength = getDataLength(packetLength, bufferToRead.position() - endPosition, bufferToRead); - - LOGGER.debug( - packetLength, - positionBeforeRead, - (length, pos) -> "Find next packet from position: " + pos + " with length: " + length - ); - - // calculate position of end the next packet - endPosition += packetLength; - - // if the packet isn't full presented in this buffer - if (packetLength == -1 || endPosition > bufferToRead.limit()) { - - bufferToRead.position(positionBeforeRead); - - // if we read the received buffer we need to put - // not read data to the pending buffer or big mapped byte buffer - if (bufferToRead == receivedBuffer) { - if (packetLength <= pendingBuffer.capacity()) { - pendingBuffer.put(receivedBuffer); - LOGGER.debug( - pendingBuffer, - buf -> "Put pending data form received buffer to pending buffer: " + buf - ); - } else { - allocTempBuffers(receivedBuffer, packetLength); - } - } - // if we already read this pending buffer we need to compact it - else if (bufferToRead == pendingBuffer) { - - if (packetLength <= pendingBuffer.capacity()) { - pendingBuffer.compact(); - LOGGER.debug(pendingBuffer, buf -> "Compact pending buffer: " + buf); - } else { - allocTempBuffers(pendingBuffer, packetLength); - LOGGER.debug(pendingBuffer, buf -> "Clear pending buffer: " + buf); - pendingBuffer.clear(); - } - - } else if (bufferToRead == tempPendingBuffer) { - - // if not read data is less than pending buffer then we can switch to use the pending buffer - if (Math.max(packetLength, tempPendingBuffer.remaining()) <= pendingBuffer.capacity()) { - - pendingBuffer - .clear() - .put(tempPendingBuffer); - - LOGGER.debug( - pendingBuffer, - buf -> "Moved pending data from mapped buffer to pending buffer: " + buf - ); - - freeTempBuffers(); - } - // if a new packet is bigger than current read mapped buffer - else if (packetLength > tempPendingBuffer.capacity()) { - reAllocTempBuffers(tempPendingBuffer, packetLength); - } - // or just compact this current mapped buffer - else { - tempPendingBuffer.compact(); - LOGGER.debug(tempPendingBuffer, buf -> "Compact mapped buffer: " + buf); - } - } - - LOGGER.debug( - channel, - readPackets, - (ch, count) -> "Read " + count + " packets from received buffer of " + getRemoteAddress(ch) + ", " + - "but 1 packet is still waiting for receiving additional data." - ); - - receivedBuffer.clear(); - return readPackets; - } - - R packet = createPacketFor(bufferToRead, positionBeforeRead, packetLength, dataLength); - - if (packet != null) { - LOGGER.debug(packet, pck -> "Created instance of packet to read data: " + pck); - readAndHandlePacket(bufferToRead, dataLength, packet); - LOGGER.debug(packet, pck -> "Finished reading data of packet: " + pck); - readPackets++; - } else { - LOGGER.warning("Cannot create any instance of packet to read data"); - } - - bufferToRead.position(endPosition); + // if we read the received buffer we need to put + // not read data to the pending buffer or big mapped byte buffer + if (bufferToRead == receivedBuffer) { + if (packetLength <= pendingBuffer.capacity()) { + pendingBuffer.put(receivedBuffer); + LOGGER.debug(pendingBuffer, buf -> "Put pending data form received buffer to pending buffer: " + buf); + } else { + allocTempBuffers(receivedBuffer, packetLength); + } } + // if we already read this pending buffer we need to compact it + else if (bufferToRead == pendingBuffer) { + + if (packetLength <= pendingBuffer.capacity()) { + pendingBuffer.compact(); + LOGGER.debug(pendingBuffer, buf -> "Compact pending buffer: " + buf); + } else { + allocTempBuffers(pendingBuffer, packetLength); + LOGGER.debug(pendingBuffer, buf -> "Clear pending buffer: " + buf); + pendingBuffer.clear(); + } - if (bufferToRead.hasRemaining()) { + } else if (bufferToRead == tempPendingBuffer) { - if (bufferToRead == receivedBuffer) { - pendingBuffer.put(receivedBuffer); - LOGGER.debug("Found not yet read data from receive buffer, will put it to pending buffer."); - } else { - bufferToRead.compact(); - } + // if not read data is less than pending buffer then we can switch to use the pending buffer + if (Math.max(packetLength, tempPendingBuffer.remaining()) <= pendingBuffer.capacity()) { + + pendingBuffer + .clear() + .put(tempPendingBuffer); + + LOGGER.debug(pendingBuffer, buf -> "Moved pending data from mapped buffer to pending buffer: " + buf); - } else if (bufferToRead == pendingBuffer) { - pendingBuffer.clear(); - } else if (tempPendingBuffer != null) { freeTempBuffers(); + } + // if a new packet is bigger than current read mapped buffer + else if (packetLength > tempPendingBuffer.capacity()) { + reAllocTempBuffers(tempPendingBuffer, packetLength); + } + // or just compact this current mapped buffer + else { + tempPendingBuffer.compact(); + LOGGER.debug(tempPendingBuffer, buf -> "Compact mapped buffer: " + buf); + } } LOGGER.debug( channel, readPackets, - (ch, count) -> "Read " + count + " packets from received buffer of " + getRemoteAddress(ch) + "." - ); + (ch, count) -> "Read " + count + " packets from received buffer of " + getRemoteAddress(ch) + ", " + + "but 1 packet is still waiting for receiving additional data."); receivedBuffer.clear(); return readPackets; - } + } - protected void readAndHandlePacket(@NotNull ByteBuffer bufferToRead, int dataLength, @NotNull R packet) { - if (packet.read(connection, bufferToRead, dataLength)) { - readPacketHandler.accept(packet); - } else { - LOGGER.error("Packet " + packet + " was read incorrectly"); - } + R packet = createPacketFor(bufferToRead, positionBeforeRead, packetLength, dataLength); + + if (packet != null) { + LOGGER.debug(packet, pck -> "Created instance of packet to read data: " + pck); + readAndHandlePacket(bufferToRead, dataLength, packet); + LOGGER.debug(packet, pck -> "Finished reading data of packet: " + pck); + readPackets++; + } else { + LOGGER.warning("Cannot create any instance of packet to read data"); + } + + bufferToRead.position(endPosition); } - /** - * Check buffer's data. - * - * @param buffer the buffer to read. - * @return true if this buffer has enough data to start initial reading. - */ - protected abstract boolean canStartReadPacket(@NotNull ByteBuffer buffer); - - /** - * Calculate size of packet data. - * - * @param packetLength the full packet length. - * @param readBytes the count of already read bytes from buffer to get packet length. - * @param buffer the buffer. - * @return the length of packet data part. - */ - protected int getDataLength(int packetLength, int readBytes, @NotNull ByteBuffer buffer) { - return packetLength - readBytes; + if (bufferToRead.hasRemaining()) { + + if (bufferToRead == receivedBuffer) { + pendingBuffer.put(receivedBuffer); + LOGGER.debug("Found not yet read data from receive buffer, will put it to pending buffer."); + } else { + bufferToRead.compact(); + } + + } else if (bufferToRead == pendingBuffer) { + pendingBuffer.clear(); + } else if (tempPendingBuffer != null) { + freeTempBuffers(); } - /** - * Get the packet's data length of next packet in the buffer. - * - * @param buffer the buffer with received data. - * @return the packet length or -1 if we have no enough data to read length. - */ - protected abstract int readPacketLength(@NotNull ByteBuffer buffer); + LOGGER.debug( + channel, + readPackets, + (ch, count) -> "Read " + count + " packets from received buffer of " + getRemoteAddress(ch) + "."); - protected void reAllocTempBuffers( - @NotNull ByteBuffer sourceBuffer, - int packetLength - ) { + receivedBuffer.clear(); + return readPackets; + } - LOGGER.debug( - sourceBuffer.capacity(), - packetLength, - (currentSize, newSize) -> "Resize read temp buffer from " + currentSize + " to " + newSize - ); + protected void readAndHandlePacket(@NotNull ByteBuffer bufferToRead, int dataLength, @NotNull R packet) { + if (packet.read(connection, bufferToRead, dataLength)) { + readPacketHandler.accept(packet); + } else { + LOGGER.error("Packet " + packet + " was read incorrectly"); + } + } - var newReadTempBuffer = bufferAllocator.takeBuffer(packetLength + readBuffer.capacity()); + /** + * Check buffer's data. + * + * @param buffer the buffer to read. + * @return true if this buffer has enough data to start initial reading. + */ + protected abstract boolean canStartReadPacket(@NotNull ByteBuffer buffer); - LOGGER.debug( - sourceBuffer, - newReadTempBuffer, - (old, buf) -> "Moved pending data from old temp buffer " + old + " to new temp buffer " + buf - ); + /** + * Calculate size of packet data. + * + * @param packetLength the full packet length. + * @param readBytes the count of already read bytes from buffer to get packet length. + * @param buffer the buffer. + * @return the length of packet data part. + */ + protected int getDataLength(int packetLength, int readBytes, @NotNull ByteBuffer buffer) { + return packetLength - readBytes; + } - newReadTempBuffer.put(sourceBuffer); + /** + * Get the packet's data length of next packet in the buffer. + * + * @param buffer the buffer with received data. + * @return the packet length or -1 if we have no enough data to read length. + */ + protected abstract int readPacketLength(@NotNull ByteBuffer buffer); - freeTempBuffers(); + protected void reAllocTempBuffers(@NotNull ByteBuffer sourceBuffer, int packetLength) { - this.tempPendingBuffer = newReadTempBuffer; - } + LOGGER.debug( + sourceBuffer.capacity(), + packetLength, + (currentSize, newSize) -> "Resize read temp buffer from " + currentSize + " to " + newSize); - protected void allocTempBuffers(@NotNull ByteBuffer sourceBuffer, int packetLength) { + var newReadTempBuffer = bufferAllocator.takeBuffer(packetLength + readBuffer.capacity()); - LOGGER.debug( - packetLength, - sourceBuffer.remaining(), - (length, part) -> "Request temp buffer to store a part: " + part + " of big packet with length: " + length - ); + LOGGER.debug( + sourceBuffer, + newReadTempBuffer, + (old, buf) -> "Moved pending data from old temp buffer " + old + " to new temp buffer " + buf); - var readTempBuffer = bufferAllocator.takeBuffer(packetLength + readBuffer.capacity()); + newReadTempBuffer.put(sourceBuffer); - LOGGER.debug( - sourceBuffer, - readTempBuffer, - (recBuf, buf) -> "Put the part of packet: " + recBuf + " to mapped buffer: " + buf - ); + freeTempBuffers(); - readTempBuffer.put(sourceBuffer); + this.tempPendingBuffer = newReadTempBuffer; + } - this.tempPendingBuffer = readTempBuffer; - } + protected void allocTempBuffers(@NotNull ByteBuffer sourceBuffer, int packetLength) { - protected void freeTempBuffers() { + LOGGER.debug( + packetLength, + sourceBuffer.remaining(), + (length, part) -> "Request temp buffer to store a part: " + part + " of big packet with length: " + length); - var readTempBuffer = getTempPendingBuffer(); + var readTempBuffer = bufferAllocator.takeBuffer(packetLength + readBuffer.capacity()); - if (readTempBuffer != null) { - setTempPendingBuffer(null); - bufferAllocator.putBuffer(readTempBuffer); - } - } + LOGGER.debug( + sourceBuffer, + readTempBuffer, + (recBuf, buf) -> "Put the part of packet: " + recBuf + " to mapped buffer: " + buf); - /** - * Handle received data. - * - * @param receivedBytes the count of received bytes. - * @param readingBuffer the currently reading buffer. - */ - protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { - updateActivityFunction.run(); - - if (receivedBytes == -1) { - connection.close(); - return; - } + readTempBuffer.put(sourceBuffer); - LOGGER.debug( - receivedBytes, - channel, - (bytes, ch) -> "Received " + bytes + " bytes from channel \"" + NetworkUtils.getRemoteAddress(ch) + "\"" - ); - - readingBuffer.flip(); - try { - readPackets(readingBuffer); - } catch (Exception e) { - LOGGER.error(e); - } + this.tempPendingBuffer = readTempBuffer; + } - if (isReading.compareAndSet(true, false)) { - startRead(); - } - } + protected void freeTempBuffers() { - /** - * Handle the exception during receiving data. - * - * @param exception the exception. - * @param readingBuffer the currently reading buffer. - */ - protected void handleFailedReceiving(@NotNull Throwable exception, @NotNull ByteBuffer readingBuffer) { - if (exception instanceof AsynchronousCloseException) { - LOGGER.info(connection, cn -> "Connection " + cn.getRemoteAddress() + " was closed."); - } else { - LOGGER.error(exception); - connection.close(); - } - } + var readTempBuffer = getTempPendingBuffer(); - /** - * Get the how many packets can be read by the one method call {@link #readPackets(ByteBuffer, ByteBuffer)}}. - * - * @return the how many packets can be read. - */ - protected int getMaxPacketsByRead() { - return maxPacketsByRead; + if (readTempBuffer != null) { + setTempPendingBuffer(null); + bufferAllocator.putBuffer(readTempBuffer); } - - protected int readHeader(@NotNull ByteBuffer buffer, int headerSize) { - switch (headerSize) { - case 1: - return buffer.get() & 0xFF; - case 2: - return buffer.getShort() & 0xFFFF; - case 4: - return buffer.getInt(); - default: - throw new IllegalStateException("Wrong packet's header size: " + headerSize); - } + } + + /** + * Handle received data. + * + * @param receivedBytes the count of received bytes. + * @param readingBuffer the currently reading buffer. + */ + protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { + updateActivityFunction.run(); + + if (receivedBytes == -1) { + connection.close(); + return; } - /** - * Create a packet to read received data. - * - * @param buffer the buffer with received data. - * @param startPacketPosition the start position of the packet in the buffer. - * @param packetLength the length of packet. - * @param dataLength length of packet's data. - * @return the readable packet. - */ - protected abstract @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, - int startPacketPosition, - int packetLength, - int dataLength - ); - - @Override - public void close() { + LOGGER.debug( + receivedBytes, + channel, + (bytes, ch) -> "Received " + bytes + " bytes from channel \"" + NetworkUtils.getRemoteAddress(ch) + "\""); - bufferAllocator - .putReadBuffer(readBuffer) - .putPendingBuffer(pendingBuffer); + readingBuffer.flip(); + try { + readPackets(readingBuffer); + } catch (Exception e) { + LOGGER.error(e); + } - freeTempBuffers(); + if (isReading.compareAndSet(true, false)) { + startRead(); + } + } + + /** + * Handle the exception during receiving data. + * + * @param exception the exception. + * @param readingBuffer the currently reading buffer. + */ + protected void handleFailedReceiving(@NotNull Throwable exception, @NotNull ByteBuffer readingBuffer) { + if (exception instanceof AsynchronousCloseException) { + LOGGER.info(connection, cn -> "Connection " + cn.getRemoteAddress() + " was closed."); + } else { + LOGGER.error(exception); + connection.close(); + } + } + + /** + * Get the how many packets can be read by the one method call {@link #readPackets(ByteBuffer, ByteBuffer)}}. + * + * @return the how many packets can be read. + */ + protected int getMaxPacketsByRead() { + return maxPacketsByRead; + } + + protected int readHeader(@NotNull ByteBuffer buffer, int headerSize) { + switch (headerSize) { + case 1: + return buffer.get() & 0xFF; + case 2: + return buffer.getShort() & 0xFFFF; + case 4: + return buffer.getInt(); + default: + throw new IllegalStateException("Wrong packet's header size: " + headerSize); } + } + + /** + * Create a packet to read received data. + * + * @param buffer the buffer with received data. + * @param startPacketPosition the start position of the packet in the buffer. + * @param packetLength the length of packet. + * @param dataLength length of packet's data. + * @return the readable packet. + */ + protected abstract @Nullable R createPacketFor( + @NotNull ByteBuffer buffer, + int startPacketPosition, + int packetLength, + int dataLength); + + @Override + public void close() { + + bufferAllocator + .putReadBuffer(readBuffer) + .putPendingBuffer(pendingBuffer); + + freeTempBuffers(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java index d33ff5a9..350a6c11 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java @@ -29,364 +29,362 @@ public abstract class AbstractPacketWriter> implements PacketWriter { - private static final Logger LOGGER = LoggerManager.getLogger(AbstractPacketWriter.class); - - private final CompletionHandler writeHandler = new CompletionHandler<>() { - - @Override - public void completed(@NotNull Integer result, @NotNull WritablePacket packet) { - handleSuccessfulWriting(result, packet); - } - - @Override - public void failed(@NotNull Throwable exc, @NotNull WritablePacket packet) { - handleFailedWriting(exc, packet); - } - }; - - protected final @NotNull AtomicBoolean isWriting = new AtomicBoolean(); - - protected final @NotNull C connection; - protected final @NotNull AsynchronousSocketChannel channel; - protected final @NotNull BufferAllocator bufferAllocator; - protected final @NotNull ByteBuffer firstWriteBuffer; - protected final @NotNull ByteBuffer secondWriteBuffer; - - protected volatile @Nullable ByteBuffer firstWriteTempBuffer; - protected volatile @Nullable ByteBuffer secondWriteTempBuffer; - - protected volatile @NotNull ByteBuffer writingBuffer = EMPTY_BUFFER; - - protected final @NotNull Runnable updateActivityFunction; - protected final @NotNull NullableSupplier nextWritePacketSupplier; - protected final @NotNull NotNullConsumer writtenPacketHandler; - protected final @NotNull NotNullBiConsumer sentPacketHandler; - - public AbstractPacketWriter( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NullableSupplier packetProvider, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler - ) { - this.connection = connection; - this.channel = channel; - this.bufferAllocator = bufferAllocator; - this.firstWriteBuffer = bufferAllocator.takeWriteBuffer(); - this.secondWriteBuffer = bufferAllocator.takeWriteBuffer(); - this.updateActivityFunction = updateActivityFunction; - this.nextWritePacketSupplier = packetProvider; - this.writtenPacketHandler = writtenPacketHandler; - this.sentPacketHandler = sentPacketHandler; - } + private static final Logger LOGGER = LoggerManager.getLogger(AbstractPacketWriter.class); - @Override - public void writeNextPacket() { + private final CompletionHandler writeHandler = new CompletionHandler<>() { - if (connection.isClosed() || !isWriting.compareAndSet(false, true)) { - return; - } + @Override + public void completed(@NotNull Integer result, @NotNull WritablePacket packet) { + handleSuccessfulWriting(result, packet); + } - var waitPacket = nextWritePacketSupplier.get(); + @Override + public void failed(@NotNull Throwable exc, @NotNull WritablePacket packet) { + handleFailedWriting(exc, packet); + } + }; + + protected final @NotNull AtomicBoolean isWriting = new AtomicBoolean(); + + protected final @NotNull C connection; + protected final @NotNull AsynchronousSocketChannel channel; + protected final @NotNull BufferAllocator bufferAllocator; + protected final @NotNull ByteBuffer firstWriteBuffer; + protected final @NotNull ByteBuffer secondWriteBuffer; + + protected volatile @Nullable ByteBuffer firstWriteTempBuffer; + protected volatile @Nullable ByteBuffer secondWriteTempBuffer; + + protected volatile @NotNull ByteBuffer writingBuffer = EMPTY_BUFFER; + + protected final @NotNull Runnable updateActivityFunction; + protected final @NotNull NullableSupplier nextWritePacketSupplier; + protected final @NotNull NotNullConsumer writtenPacketHandler; + protected final @NotNull NotNullBiConsumer sentPacketHandler; + + public AbstractPacketWriter( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NullableSupplier packetProvider, + @NotNull NotNullConsumer writtenPacketHandler, + @NotNull NotNullBiConsumer sentPacketHandler) { + this.connection = connection; + this.channel = channel; + this.bufferAllocator = bufferAllocator; + this.firstWriteBuffer = bufferAllocator.takeWriteBuffer(); + this.secondWriteBuffer = bufferAllocator.takeWriteBuffer(); + this.updateActivityFunction = updateActivityFunction; + this.nextWritePacketSupplier = packetProvider; + this.writtenPacketHandler = writtenPacketHandler; + this.sentPacketHandler = sentPacketHandler; + } + + @Override + public void writeNextPacket() { + + if (connection.isClosed() || !isWriting.compareAndSet(false, true)) { + return; + } - if (waitPacket == null) { - isWriting.set(false); - return; - } + var waitPacket = nextWritePacketSupplier.get(); - var resultBuffer = serialize(waitPacket); + if (waitPacket == null) { + isWriting.set(false); + return; + } - if (resultBuffer.limit() != 0) { - writingBuffer = resultBuffer; + var resultBuffer = serialize(waitPacket); - LOGGER.debug( - channel, - resultBuffer, - (ch, buf) -> "Write to channel \"" + getRemoteAddress(ch) + "\" data:\n" + hexDump(buf) - ); + if (resultBuffer.limit() != 0) { + writingBuffer = resultBuffer; - channel.write(resultBuffer, waitPacket, writeHandler); - } else { - isWriting.set(false); - } + LOGGER.debug( + channel, + resultBuffer, + (ch, buf) -> "Write to channel \"" + getRemoteAddress(ch) + "\" data:\n" + hexDump(buf)); - writtenPacketHandler.accept(waitPacket); + channel.write(resultBuffer, waitPacket, writeHandler); + } else { + isWriting.set(false); } - protected @NotNull ByteBuffer serialize(@NotNull WritablePacket packet) { + writtenPacketHandler.accept(waitPacket); + } - if (packet instanceof WritablePacketWrapper) { - packet = ((WritablePacketWrapper) packet).getPacket(); - } + protected @NotNull ByteBuffer serialize(@NotNull WritablePacket packet) { - W resultPacket = (W) packet; + if (packet instanceof WritablePacketWrapper) { + packet = ((WritablePacketWrapper) packet).getPacket(); + } - var expectedLength = packet.getExpectedLength(); - var totalSize = expectedLength == -1 ? -1 : getTotalSize(packet, expectedLength); + W resultPacket = (W) packet; - // if the packet is too big to use a write buffer - if (expectedLength != -1 && totalSize > firstWriteBuffer.capacity()) { - var first = bufferAllocator.takeBuffer(totalSize); - var second = bufferAllocator.takeBuffer(totalSize); - firstWriteTempBuffer = first; - secondWriteTempBuffer = second; - return serialize(resultPacket, expectedLength, totalSize, first, second); - } else { - return serialize(resultPacket, expectedLength, totalSize, firstWriteBuffer, secondWriteBuffer); - } - } + var expectedLength = packet.getExpectedLength(); + var totalSize = expectedLength == -1 ? -1 : getTotalSize(packet, expectedLength); - /** - * Get a total size of packet if it possible. - * - * @param packet the packet. - * @param expectedLength the expected size. - * @return the total size or -1. - */ - protected abstract int getTotalSize(@NotNull WritablePacket packet, int expectedLength); - - /** - * Serialize packet to byte buffer. - * - * @param packet the packet to serialize. - * @param expectedLength the packet's expected size. - * @param totalSize the packet's total size. - * @param firstBuffer the first byte buffer. - * @param secondBuffer the second byte buffer. - * @return the buffer to write to channel. - */ - protected @NotNull ByteBuffer serialize( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - - if(!onBeforeWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer)) { - return firstBuffer.clear().limit(0); - } else if (!onWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer)) { - return firstBuffer.clear().limit(0); - } else if(!onAfterWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer)) { - return firstBuffer.clear().limit(0); - } - - return onResult(packet, expectedLength, totalSize, firstBuffer, secondBuffer); + // if the packet is too big to use a write buffer + if (expectedLength != -1 && totalSize > firstWriteBuffer.capacity()) { + var first = bufferAllocator.takeBuffer(totalSize); + var second = bufferAllocator.takeBuffer(totalSize); + firstWriteTempBuffer = first; + secondWriteTempBuffer = second; + return serialize(resultPacket, expectedLength, totalSize, first, second); + } else { + return serialize(resultPacket, expectedLength, totalSize, firstWriteBuffer, secondWriteBuffer); } - - /** - * Handle a byte buffer before writing packet's data. - * - * @param packet the packet. - * @param expectedLength the packet's expected size. - * @param totalSize the packet's total size. - * @param firstBuffer the first byte buffer. - * @param secondBuffer the second byte buffer. - * @return true if handling was successful. - */ - protected boolean onBeforeWrite( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - firstBuffer.clear(); - return true; + } + + /** + * Get a total size of packet if it possible. + * + * @param packet the packet. + * @param expectedLength the expected size. + * @return the total size or -1. + */ + protected abstract int getTotalSize(@NotNull WritablePacket packet, int expectedLength); + + /** + * Serialize packet to byte buffer. + * + * @param packet the packet to serialize. + * @param expectedLength the packet's expected size. + * @param totalSize the packet's total size. + * @param firstBuffer the first byte buffer. + * @param secondBuffer the second byte buffer. + * @return the buffer to write to channel. + */ + protected @NotNull ByteBuffer serialize( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + + if (!onBeforeWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer)) { + return firstBuffer + .clear() + .limit(0); + } else if (!onWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer)) { + return firstBuffer + .clear() + .limit(0); + } else if (!onAfterWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer)) { + return firstBuffer + .clear() + .limit(0); } - /** - * Write a packet to byte buffer. - * - * @param packet the packet. - * @param expectedLength the packet's expected size. - * @param totalSize the packet's total size. - * @param firstBuffer the first byte buffer. - * @param secondBuffer the second byte buffer. - * @return true if writing was successful. - */ - protected boolean onWrite( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - return packet.write(firstBuffer); + return onResult(packet, expectedLength, totalSize, firstBuffer, secondBuffer); + } + + /** + * Handle a byte buffer before writing packet's data. + * + * @param packet the packet. + * @param expectedLength the packet's expected size. + * @param totalSize the packet's total size. + * @param firstBuffer the first byte buffer. + * @param secondBuffer the second byte buffer. + * @return true if handling was successful. + */ + protected boolean onBeforeWrite( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + firstBuffer.clear(); + return true; + } + + /** + * Write a packet to byte buffer. + * + * @param packet the packet. + * @param expectedLength the packet's expected size. + * @param totalSize the packet's total size. + * @param firstBuffer the first byte buffer. + * @param secondBuffer the second byte buffer. + * @return true if writing was successful. + */ + protected boolean onWrite( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + return packet.write(firstBuffer); + } + + /** + * Handle a byte buffer after writing packet's data. + * + * @param packet the packet. + * @param expectedLength the packet's expected size. + * @param totalSize the packet's total size. + * @param firstBuffer the first byte buffer. + * @param secondBuffer the second byte buffer. + * @return true if handling was successful. + */ + protected boolean onAfterWrite( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + firstBuffer.flip(); + return true; + } + + /** + * Handle a final result byte buffer. + * + * @param packet the packet. + * @param expectedLength the packet's expected size. + * @param totalSize the packet's total size. + * @param firstBuffer the first byte buffer. + * @param secondBuffer the second byte buffer. + * @return the same byte buffer. + */ + protected @NotNull ByteBuffer onResult( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + return firstBuffer.position(0); + } + + protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int position, int value, int headerSize) { + try { + + switch (headerSize) { + case 1: + buffer.put(position, (byte) value); + break; + case 2: + buffer.putShort(position, (short) value); + break; + case 4: + buffer.putInt(position, value); + break; + default: + throw new IllegalStateException("Wrong packet's header size: " + headerSize); + } + + return buffer; + + } catch (IndexOutOfBoundsException ex) { + LOGGER.error( + "Cannot write header by position " + position + " with header size " + headerSize + " to buffer " + buffer); + throw ex; } - - /** - * Handle a byte buffer after writing packet's data. - * - * @param packet the packet. - * @param expectedLength the packet's expected size. - * @param totalSize the packet's total size. - * @param firstBuffer the first byte buffer. - * @param secondBuffer the second byte buffer. - * @return true if handling was successful. - */ - protected boolean onAfterWrite( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - firstBuffer.flip(); - return true; + } + + protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int value, int headerSize) { + + switch (headerSize) { + case 1: + buffer.put((byte) value); + break; + case 2: + buffer.putShort((short) value); + break; + case 4: + buffer.putInt(value); + break; + default: + throw new IllegalStateException("Wrong packet's header size: " + headerSize); } - /** - * Handle a final result byte buffer. - * - * @param packet the packet. - * @param expectedLength the packet's expected size. - * @param totalSize the packet's total size. - * @param firstBuffer the first byte buffer. - * @param secondBuffer the second byte buffer. - * @return the same byte buffer. - */ - protected @NotNull ByteBuffer onResult( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - return firstBuffer.position(0); + return buffer; + } + + /** + * Handle successful wrote data. + * + * @param result the count of wrote bytes. + * @param packet the sent packet. + */ + protected void handleSuccessfulWriting(@NotNull Integer result, @NotNull WritablePacket packet) { + updateActivityFunction.run(); + + if (result == -1) { + sentPacketHandler.accept(packet, Boolean.FALSE); + connection.close(); + return; } - protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int position, int value, int headerSize) { - try { - - switch (headerSize) { - case 1: - buffer.put(position, (byte) value); - break; - case 2: - buffer.putShort(position, (short) value); - break; - case 4: - buffer.putInt(position, value); - break; - default: - throw new IllegalStateException("Wrong packet's header size: " + headerSize); - } - - return buffer; - - } catch (IndexOutOfBoundsException ex) { - LOGGER.error("Cannot write header by position " + position + " with header size " + headerSize + - " to buffer " + buffer); - throw ex; - } + var writingBuffer = this.writingBuffer; + + if (writingBuffer.remaining() > 0) { + LOGGER.debug( + writingBuffer, + channel, + (buf, ch) -> "Buffer was not consumed fully, " + "try to write else " + buf.remaining() + " bytes to channel " + + NetworkUtils.getRemoteAddress(ch)); + channel.write(writingBuffer, packet, writeHandler); + return; + } else { + LOGGER.debug(result, bytes -> "Done writing " + bytes + " bytes"); } - protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int value, int headerSize) { - - switch (headerSize) { - case 1: - buffer.put((byte) value); - break; - case 2: - buffer.putShort((short) value); - break; - case 4: - buffer.putInt(value); - break; - default: - throw new IllegalStateException("Wrong packet's header size: " + headerSize); - } - - return buffer; - } + sentPacketHandler.accept(packet, Boolean.TRUE); - /** - * Handle successful wrote data. - * - * @param result the count of wrote bytes. - * @param packet the sent packet. - */ - protected void handleSuccessfulWriting(@NotNull Integer result, @NotNull WritablePacket packet) { - updateActivityFunction.run(); - - if (result == -1) { - sentPacketHandler.accept(packet, Boolean.FALSE); - connection.close(); - return; - } - - var writingBuffer = this.writingBuffer; - - if (writingBuffer.remaining() > 0) { - LOGGER.debug( - writingBuffer, - channel, - (buf, ch) -> "Buffer was not consumed fully, " + - "try to write else " + buf.remaining() + " bytes to channel " + NetworkUtils.getRemoteAddress(ch) - ); - channel.write(writingBuffer, packet, writeHandler); - return; - } else { - LOGGER.debug(result, bytes -> "Done writing " + bytes + " bytes"); - } - - sentPacketHandler.accept(packet, Boolean.TRUE); - - if (isWriting.compareAndSet(true, false)) { - - // if we have temp buffers, we can remove it after finishing writing a packet - if (firstWriteTempBuffer != null) { - clearTempBuffers(); - } - - writeNextPacket(); - } - } + if (isWriting.compareAndSet(true, false)) { + + // if we have temp buffers, we can remove it after finishing writing a packet + if (firstWriteTempBuffer != null) { + clearTempBuffers(); + } - /** - * Handle the exception during writing the packet. - * - * @param exception the exception. - * @param packet the packet. - */ - protected void handleFailedWriting(@NotNull Throwable exception, @NotNull WritablePacket packet) { - LOGGER.error(new RuntimeException("Failed writing packet: " + packet, exception)); - - if (!connection.isClosed()) { - if (isWriting.compareAndSet(true, false)) { - writeNextPacket(); - } - } + writeNextPacket(); } + } + + /** + * Handle the exception during writing the packet. + * + * @param exception the exception. + * @param packet the packet. + */ + protected void handleFailedWriting(@NotNull Throwable exception, @NotNull WritablePacket packet) { + LOGGER.error(new RuntimeException("Failed writing packet: " + packet, exception)); + + if (!connection.isClosed()) { + if (isWriting.compareAndSet(true, false)) { + writeNextPacket(); + } + } + } - @Override - public void close() { + @Override + public void close() { - bufferAllocator - .putWriteBuffer(firstWriteBuffer) - .putWriteBuffer(secondWriteBuffer); + bufferAllocator + .putWriteBuffer(firstWriteBuffer) + .putWriteBuffer(secondWriteBuffer); - clearTempBuffers(); + clearTempBuffers(); - writingBuffer = EMPTY_BUFFER; - } + writingBuffer = EMPTY_BUFFER; + } - protected void clearTempBuffers() { + protected void clearTempBuffers() { - var secondWriteTempBuffer = this.secondWriteTempBuffer; - var firstWriteTempBuffer = this.firstWriteTempBuffer; + var secondWriteTempBuffer = this.secondWriteTempBuffer; + var firstWriteTempBuffer = this.firstWriteTempBuffer; - if (secondWriteTempBuffer != null) { - this.secondWriteTempBuffer = null; - bufferAllocator.putBuffer(secondWriteTempBuffer); - } + if (secondWriteTempBuffer != null) { + this.secondWriteTempBuffer = null; + bufferAllocator.putBuffer(secondWriteTempBuffer); + } - if (firstWriteTempBuffer != null) { - this.firstWriteTempBuffer = null; - bufferAllocator.putBuffer(firstWriteTempBuffer); - } + if (firstWriteTempBuffer != null) { + this.firstWriteTempBuffer = null; + bufferAllocator.putBuffer(firstWriteTempBuffer); } + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java index 10409039..1ff0440e 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java @@ -18,144 +18,145 @@ public abstract class AbstractReadablePacket> extends AbstractPacket implements ReadablePacket { - @Override - public boolean read(@NotNull Connection connection, @NotNull ByteBuffer buffer, int length) { - var oldLimit = buffer.limit(); - try { - buffer.limit(buffer.position() + length); - readImpl(ClassUtils.unsafeNNCast(connection), buffer); - return true; - } catch (Exception e) { - handleException(buffer, e); - return false; - } finally { - buffer.limit(oldLimit); - } + @Override + public boolean read(@NotNull Connection connection, @NotNull ByteBuffer buffer, int length) { + var oldLimit = buffer.limit(); + try { + buffer.limit(buffer.position() + length); + readImpl(ClassUtils.unsafeNNCast(connection), buffer); + return true; + } catch (Exception e) { + handleException(buffer, e); + return false; + } finally { + buffer.limit(oldLimit); } - - /** - * Read packet's data from byte buffer. - * - * @param connection the network connection. - * @param buffer the buffer with received data. - */ - protected void readImpl(@NotNull C connection, @NotNull ByteBuffer buffer) { - } - - /** - * Read 1 byte from buffer. - * - * @param buffer the buffer to read. - * @return 1 byte from the buffer. - */ - protected int readByte(@NotNull ByteBuffer buffer) { - return buffer.get(); - } - - /** - * Fill byte array with data from received buffer. - * - * @param buffer the buffer to read. - * @param array the filled byte array. - */ - protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array) { - buffer.get(array); - } - - /** - * Fill byte array with data from received buffer. - * - * @param buffer the buffer to read. - * @param array the byte array. - * @param offset the offset to fill the byte array. - * @param length the length to fill the byte array. - */ - protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array, int offset, int length) { - buffer.get(array, offset, length); - } - - /** - * Read 4 bytes from buffer. - * - * @param buffer the buffer to read. - * @return 4 bytes as float from the buffer. - */ - protected float readFloat(@NotNull ByteBuffer buffer) { - return buffer.getFloat(); - } - - /** - * Read 8 bytes from buffer. - * - * @param buffer the buffer to read. - * @return 4 bytes as double from the buffer. - */ - protected double readDouble(@NotNull ByteBuffer buffer) { - return buffer.getDouble(); - } - - /** - * Read 4 bytes from buffer. - * - * @param buffer the buffer to read. - * @return 4 bytes as int from the buffer. - */ - protected int readInt(@NotNull ByteBuffer buffer) { - return buffer.getInt(); - } - - /** - * Read 8 bytes from buffer. - * - * @param buffer the buffer to read. - * @return 8 bytes as long from buffer. - */ - protected long readLong(@NotNull ByteBuffer buffer) { - return buffer.getLong(); - } - - /** - * Read 2 bytes from buffer. - * - * @param buffer the buffer to read. - * @return 2 bytes as short from buffer. - */ - protected int readShort(@NotNull ByteBuffer buffer) { - return buffer.getShort(); - } - - /** - * Read a string from buffer. - * - * @param buffer the buffer to read. - * @return the read string from the buffer. - */ - protected @NotNull String readString(@NotNull ByteBuffer buffer) { - - var length = readInt(buffer); - try { - - var requiredRemainingBytes = length * 2; - - if (requiredRemainingBytes > buffer.remaining()) { - throw new IllegalStateException("Found too long string " + length + " from buffer " + buffer); - } - - var array = new char[length]; - - for (int i = 0; i < length; i++) { - array[i] = buffer.getChar(); - } - - return new String(array); - - } catch (OutOfMemoryError ex) { - LOGGER.error("Cannot read too long \"" + length + "\" string by memory reason"); - throw ex; - } catch (BufferUnderflowException ex) { - LOGGER.error("Cannot read string because buffer doesn't contains enough data. " + - "Expected string length " + length + ", buffer " + buffer); - throw ex; - } + } + + /** + * Read packet's data from byte buffer. + * + * @param connection the network connection. + * @param buffer the buffer with received data. + */ + protected void readImpl(@NotNull C connection, @NotNull ByteBuffer buffer) { + } + + /** + * Read 1 byte from buffer. + * + * @param buffer the buffer to read. + * @return 1 byte from the buffer. + */ + protected int readByte(@NotNull ByteBuffer buffer) { + return buffer.get(); + } + + /** + * Fill byte array with data from received buffer. + * + * @param buffer the buffer to read. + * @param array the filled byte array. + */ + protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array) { + buffer.get(array); + } + + /** + * Fill byte array with data from received buffer. + * + * @param buffer the buffer to read. + * @param array the byte array. + * @param offset the offset to fill the byte array. + * @param length the length to fill the byte array. + */ + protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array, int offset, int length) { + buffer.get(array, offset, length); + } + + /** + * Read 4 bytes from buffer. + * + * @param buffer the buffer to read. + * @return 4 bytes as float from the buffer. + */ + protected float readFloat(@NotNull ByteBuffer buffer) { + return buffer.getFloat(); + } + + /** + * Read 8 bytes from buffer. + * + * @param buffer the buffer to read. + * @return 4 bytes as double from the buffer. + */ + protected double readDouble(@NotNull ByteBuffer buffer) { + return buffer.getDouble(); + } + + /** + * Read 4 bytes from buffer. + * + * @param buffer the buffer to read. + * @return 4 bytes as int from the buffer. + */ + protected int readInt(@NotNull ByteBuffer buffer) { + return buffer.getInt(); + } + + /** + * Read 8 bytes from buffer. + * + * @param buffer the buffer to read. + * @return 8 bytes as long from buffer. + */ + protected long readLong(@NotNull ByteBuffer buffer) { + return buffer.getLong(); + } + + /** + * Read 2 bytes from buffer. + * + * @param buffer the buffer to read. + * @return 2 bytes as short from buffer. + */ + protected int readShort(@NotNull ByteBuffer buffer) { + return buffer.getShort(); + } + + /** + * Read a string from buffer. + * + * @param buffer the buffer to read. + * @return the read string from the buffer. + */ + protected @NotNull String readString(@NotNull ByteBuffer buffer) { + + var length = readInt(buffer); + try { + + var requiredRemainingBytes = length * 2; + + if (requiredRemainingBytes > buffer.remaining()) { + throw new IllegalStateException("Found too long string " + length + " from buffer " + buffer); + } + + var array = new char[length]; + + for (int i = 0; i < length; i++) { + array[i] = buffer.getChar(); + } + + return new String(array); + + } catch (OutOfMemoryError ex) { + LOGGER.error("Cannot read too long \"" + length + "\" string by memory reason"); + throw ex; + } catch (BufferUnderflowException ex) { + LOGGER.error( + "Cannot read string because buffer doesn't contains enough data. " + "Expected string length " + length + + ", buffer " + buffer); + throw ex; } + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java index 919d4787..ff282f20 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java @@ -5,7 +5,7 @@ import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.pools.Pool; import javasabr.rlib.common.util.pools.PoolFactory; @@ -14,195 +14,198 @@ import org.jetbrains.annotations.Nullable; /** - * The reusable implementation of {@link AbstractWritablePacket} using the counter to control the life cycle of - * this packet. + * The reusable implementation of {@link AbstractWritablePacket} using the counter to control the life cycle of this + * packet. * * @author JavaSaBr */ public abstract class AbstractReusableWritablePacket extends AbstractWritablePacket implements ReusableWritablePacket { - protected static final ThreadLocal, Pool>> - LOCAL_POOLS = ThreadLocal.withInitial(HashMap::new); - - protected final AtomicInteger counter; - - /** - * The pool to store this packet after using. - */ - protected volatile @Nullable Pool pool; - protected volatile int barrier; - - protected int barrierSink; - - public AbstractReusableWritablePacket() { - this.counter = new AtomicInteger(); - } - - @Override - public boolean write(@NotNull ByteBuffer buffer) { - - if (counter.get() < 1) { - LOGGER.warning( - this, - arg -> "Attempt to write is already finished packet " + arg + " on thread " + Thread.currentThread().getName() - ); - return false; - } - - notifyStartedWriting(); - try { - super.write(buffer); - } finally { - notifyFinishedWriting(); - } - - return true; - } - - /** - * Notify about started preparing data. - */ - protected void notifyStartedPreparing() { - barrierSink = barrier; - } - - /** - * Notify about finished preparing data. - */ - protected void notifyFinishedPreparing() { - barrier = barrierSink + 1; - } - - /** - * Notify about started writing data. - */ - protected void notifyStartedWriting() { - barrierSink = barrier; - } - - /** - * Notify about finished writing data. - */ - protected void notifyFinishedWriting() { - barrier = barrierSink + 1; - } - - /** - * Notify about started storing instance to a pool. - */ - protected void notifyStartedStoring() { - barrierSink = barrier; - } - - /** - * Notify about finished storing instance to a pool. - */ - protected void notifyFinishedStoring() { - barrier = barrierSink + 1; - } - - @Override - public void complete() { - if (counter.decrementAndGet() == 0) { - completeImpl(); - } - } - - @Override - public void forceComplete() { - counter.set(1); - complete(); - } - - /** - * Get thread local pool. - * - * @return thread local pool. - */ - protected @NotNull Pool getThreadLocalPool() { - Class packetClass = ClassUtils.unsafeNNCast(getClass()); - return LOCAL_POOLS.get().computeIfAbsent(packetClass, PoolFactory::newConcurrentStampedLockReusablePool); - } - - @Override - public void reuse() { - this.pool = getThreadLocalPool(); - } - - /** - * Get the pool to store used packet. - * - * @return the pool to store used packet. - */ - protected @NotNull Pool getPool() { - - Pool local = this.pool; - - if (local != null) { - return local; - } - - this.pool = getThreadLocalPool(); - - local = this.pool; - - return notNull(local); - } - - /** - * Implementation of handling completion of packet sending. - */ - protected void completeImpl() { - notifyStartedStoring(); - try { - getPool().put(this); - } finally { - notifyFinishedStoring(); - } - } - - /** - * Get a new instance of this packet. - * - * @param the result packet's type. - * @return the new instance. - */ - public @NotNull T newInstance() { - - Pool pool = getPool(); - ReusableWritablePacket result = pool.take(getClass(), ClassUtils::newInstance); - result.setPool(pool); - - return notNull(ClassUtils.unsafeCast(result)); - } - - @Override - public final void setPool(@NotNull Pool pool) { - this.pool = pool; - } - - @Override - public final void decreaseSends() { - counter.decrementAndGet(); - } - - @Override - public void decreaseSends(int count) { - counter.subAndGet(count); - } - - @Override - public void increaseSends() { - counter.incrementAndGet(); - } - - @Override - public void increaseSends(int count) { - counter.addAndGet(count); - } - - @Override - public String toString() { - return "AbstractReusableSendablePacket{" + "counter=" + counter + "} " + super.toString(); - } + protected static final ThreadLocal, Pool>> LOCAL_POOLS = ThreadLocal.withInitial( + HashMap::new); + + protected final ReusableAtomicInteger counter; + + /** + * The pool to store this packet after using. + */ + protected volatile @Nullable Pool pool; + protected volatile int barrier; + + protected int barrierSink; + + public AbstractReusableWritablePacket() { + this.counter = new ReusableAtomicInteger(); + } + + @Override + public boolean write(@NotNull ByteBuffer buffer) { + + if (counter.get() < 1) { + LOGGER.warning( + this, + arg -> "Attempt to write is already finished packet " + arg + " on thread " + Thread + .currentThread() + .getName()); + return false; + } + + notifyStartedWriting(); + try { + super.write(buffer); + } finally { + notifyFinishedWriting(); + } + + return true; + } + + /** + * Notify about started preparing data. + */ + protected void notifyStartedPreparing() { + barrierSink = barrier; + } + + /** + * Notify about finished preparing data. + */ + protected void notifyFinishedPreparing() { + barrier = barrierSink + 1; + } + + /** + * Notify about started writing data. + */ + protected void notifyStartedWriting() { + barrierSink = barrier; + } + + /** + * Notify about finished writing data. + */ + protected void notifyFinishedWriting() { + barrier = barrierSink + 1; + } + + /** + * Notify about started storing instance to a pool. + */ + protected void notifyStartedStoring() { + barrierSink = barrier; + } + + /** + * Notify about finished storing instance to a pool. + */ + protected void notifyFinishedStoring() { + barrier = barrierSink + 1; + } + + @Override + public void complete() { + if (counter.decrementAndGet() == 0) { + completeImpl(); + } + } + + @Override + public void forceComplete() { + counter.set(1); + complete(); + } + + /** + * Get thread local pool. + * + * @return thread local pool. + */ + protected @NotNull Pool getThreadLocalPool() { + Class packetClass = ClassUtils.unsafeNNCast(getClass()); + return LOCAL_POOLS + .get() + .computeIfAbsent(packetClass, PoolFactory::newConcurrentStampedLockReusablePool); + } + + @Override + public void reuse() { + this.pool = getThreadLocalPool(); + } + + /** + * Get the pool to store used packet. + * + * @return the pool to store used packet. + */ + protected @NotNull Pool getPool() { + + Pool local = this.pool; + + if (local != null) { + return local; + } + + this.pool = getThreadLocalPool(); + + local = this.pool; + + return notNull(local); + } + + /** + * Implementation of handling completion of packet sending. + */ + protected void completeImpl() { + notifyStartedStoring(); + try { + getPool().put(this); + } finally { + notifyFinishedStoring(); + } + } + + /** + * Get a new instance of this packet. + * + * @param the result packet's type. + * @return the new instance. + */ + public @NotNull T newInstance() { + + Pool pool = getPool(); + ReusableWritablePacket result = pool.take(getClass(), ClassUtils::newInstance); + result.setPool(pool); + + return notNull(ClassUtils.unsafeCast(result)); + } + + @Override + public final void setPool(@NotNull Pool pool) { + this.pool = pool; + } + + @Override + public final void decreaseSends() { + counter.decrementAndGet(); + } + + @Override + public void decreaseSends(int count) { + counter.subAndGet(count); + } + + @Override + public void increaseSends() { + counter.incrementAndGet(); + } + + @Override + public void increaseSends(int count) { + counter.addAndGet(count); + } + + @Override + public String toString() { + return "AbstractReusableSendablePacket{" + "counter=" + counter + "} " + super.toString(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java index e2245f7b..76763953 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java @@ -26,244 +26,239 @@ public abstract class AbstractSSLPacketReader> extends AbstractPacketReader { - private static final Logger LOGGER = LoggerManager.getLogger(AbstractSSLPacketReader.class); - - private static final ByteBuffer[] EMPTY_BUFFERS = { - NetworkUtils.EMPTY_BUFFER - }; - - private static final int SKIP_READ_PACKETS = -1; - - protected final @NotNull SSLEngine sslEngine; - protected final @NotNull NotNullConsumer packetWriter; - - protected volatile @NotNull ByteBuffer sslNetworkBuffer; - protected volatile @NotNull ByteBuffer sslDataBuffer; - - protected AbstractSSLPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, - int maxPacketsByRead - ) { - super(connection, channel, bufferAllocator, updateActivityFunction, readPacketHandler, maxPacketsByRead); - this.sslEngine = sslEngine; - this.sslDataBuffer = bufferAllocator.takeBuffer(sslEngine.getSession().getApplicationBufferSize()); - this.sslNetworkBuffer = bufferAllocator.takeBuffer(sslEngine.getSession().getPacketBufferSize()); - this.packetWriter = packetWriter; + private static final Logger LOGGER = LoggerManager.getLogger(AbstractSSLPacketReader.class); + + private static final ByteBuffer[] EMPTY_BUFFERS = { + NetworkUtils.EMPTY_BUFFER + }; + + private static final int SKIP_READ_PACKETS = -1; + + protected final @NotNull SSLEngine sslEngine; + protected final @NotNull NotNullConsumer packetWriter; + + protected volatile @NotNull ByteBuffer sslNetworkBuffer; + protected volatile @NotNull ByteBuffer sslDataBuffer; + + protected AbstractSSLPacketReader( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NotNullConsumer readPacketHandler, + @NotNull SSLEngine sslEngine, + @NotNull NotNullConsumer packetWriter, + int maxPacketsByRead) { + super(connection, channel, bufferAllocator, updateActivityFunction, readPacketHandler, maxPacketsByRead); + this.sslEngine = sslEngine; + this.sslDataBuffer = bufferAllocator.takeBuffer(sslEngine + .getSession() + .getApplicationBufferSize()); + this.sslNetworkBuffer = bufferAllocator.takeBuffer(sslEngine + .getSession() + .getPacketBufferSize()); + this.packetWriter = packetWriter; + } + + @Override + protected @NotNull ByteBuffer getBufferToReadFromChannel() { + return sslNetworkBuffer; + } + + @Override + protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { + + if (receivedBytes == -1) { + doHandshake(readingBuffer, -1); + return; } - @Override - protected @NotNull ByteBuffer getBufferToReadFromChannel() { - return sslNetworkBuffer; - } + super.handleReceivedData(receivedBytes, readingBuffer); + } - @Override - protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { + @Override + protected int readPackets(@NotNull ByteBuffer receivedBuffer) { - if (receivedBytes == -1) { - doHandshake(readingBuffer, -1); - return; - } + var handshakeStatus = sslEngine.getHandshakeStatus(); - super.handleReceivedData(receivedBytes, readingBuffer); + // ssl engine is ready to decrypt + if (handshakeStatus == HandshakeStatus.FINISHED || handshakeStatus == HandshakeStatus.NOT_HANDSHAKING) { + return decryptAndRead(receivedBuffer); + } else { + return doHandshake(receivedBuffer, receivedBuffer.limit()); } + } - @Override - protected int readPackets(@NotNull ByteBuffer receivedBuffer) { + protected int doHandshake(@NotNull ByteBuffer receivedBuffer, int receivedBytes) { - var handshakeStatus = sslEngine.getHandshakeStatus(); + var handshakeStatus = sslEngine.getHandshakeStatus(); - // ssl engine is ready to decrypt - if (handshakeStatus == HandshakeStatus.FINISHED || handshakeStatus == HandshakeStatus.NOT_HANDSHAKING) { - return decryptAndRead(receivedBuffer); - } else { - return doHandshake(receivedBuffer, receivedBuffer.limit()); - } - } + while (handshakeStatus != HandshakeStatus.FINISHED && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING) { + LOGGER.debug(handshakeStatus, status -> "Do handshake with status: " + status); - protected int doHandshake(@NotNull ByteBuffer receivedBuffer, int receivedBytes) { + SSLEngineResult result; - var handshakeStatus = sslEngine.getHandshakeStatus(); + switch (handshakeStatus) { + case NEED_UNWRAP: { - while (handshakeStatus != HandshakeStatus.FINISHED && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING) { - LOGGER.debug(handshakeStatus, status -> "Do handshake with status: " + status); - - SSLEngineResult result; - - switch (handshakeStatus) { - case NEED_UNWRAP: { - - if (receivedBytes == -1) { - - if (sslEngine.isInboundDone() && sslEngine.isOutboundDone()) { - return SKIP_READ_PACKETS; - } - - try { - sslEngine.closeInbound(); - } catch (SSLException e) { - LOGGER.error("This engine was forced to close inbound, without having received the " + - "proper SSL/TLS close notification message from the peer, due to end of stream."); - } - - sslEngine.closeOutbound(); - handshakeStatus = sslEngine.getHandshakeStatus(); - break; - - } else if (!receivedBuffer.hasRemaining()) { - receivedBuffer.clear(); - return SKIP_READ_PACKETS; - } - - try { - LOGGER.debug(receivedBuffer, buff -> "Try to unwrap data:\n" + hexDump(buff)); - result = sslEngine.unwrap(receivedBuffer, EMPTY_BUFFERS); - handshakeStatus = result.getHandshakeStatus(); - LOGGER.debug(handshakeStatus, status -> "Handshake status: " + status + " after unwrapping"); - } catch (SSLException sslException) { - LOGGER.error("A problem was encountered while processing the data that caused the " + - "SSLEngine to abort. Will try to properly close connection..."); - sslEngine.closeOutbound(); - handshakeStatus = sslEngine.getHandshakeStatus(); - break; - } - - switch (result.getStatus()) { - case OK: - break; - case BUFFER_OVERFLOW: - throw new IllegalStateException("Unexpected ssl engine result"); - case BUFFER_UNDERFLOW: - LOGGER.debug("Increase ssl network buffer"); - increaseNetworkBuffer(); - break; - case CLOSED: - if (sslEngine.isOutboundDone()) { - return SKIP_READ_PACKETS; - } else { - sslEngine.closeOutbound(); - handshakeStatus = sslEngine.getHandshakeStatus(); - break; - } - default: - throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); - } - break; - } - case NEED_WRAP: - LOGGER.debug("Send command to wrap data"); - packetWriter.accept(SSLWritablePacket.getInstance()); - sslNetworkBuffer.clear(); - return SKIP_READ_PACKETS; - case NEED_TASK: - - Runnable task; - - while ((task = sslEngine.getDelegatedTask()) != null) { - LOGGER.debug(task, t -> "Execute SSL Engine's task: " + t.getClass()); - task.run(); - } - - handshakeStatus = sslEngine.getHandshakeStatus(); - - LOGGER.debug(handshakeStatus, status -> "Handshake status: " + status + " after engine tasks"); - - if (handshakeStatus == HandshakeStatus.NEED_UNWRAP && !receivedBuffer.hasRemaining()) { - sslNetworkBuffer.clear(); - return SKIP_READ_PACKETS; - } - - break; - default: - throw new IllegalStateException("Invalid SSL status: " + handshakeStatus); - } - } + if (receivedBytes == -1) { - if (!receivedBuffer.hasRemaining()) { + if (sslEngine.isInboundDone() && sslEngine.isOutboundDone()) { + return SKIP_READ_PACKETS; + } - // if buffer is empty and status is FINISHED then we can notify writer - if (handshakeStatus == HandshakeStatus.FINISHED) { - packetWriter.accept(SSLWritablePacket.getInstance()); + try { + sslEngine.closeInbound(); + } catch (SSLException e) { + LOGGER.error("This engine was forced to close inbound, without having received the " + + "proper SSL/TLS close notification message from the peer, due to end of stream."); } - receivedBuffer.clear(); + sslEngine.closeOutbound(); + handshakeStatus = sslEngine.getHandshakeStatus(); + break; + } else if (!receivedBuffer.hasRemaining()) { + receivedBuffer.clear(); return SKIP_READ_PACKETS; + } + + try { + LOGGER.debug(receivedBuffer, buff -> "Try to unwrap data:\n" + hexDump(buff)); + result = sslEngine.unwrap(receivedBuffer, EMPTY_BUFFERS); + handshakeStatus = result.getHandshakeStatus(); + LOGGER.debug(handshakeStatus, status -> "Handshake status: " + status + " after unwrapping"); + } catch (SSLException sslException) { + LOGGER.error("A problem was encountered while processing the data that caused the " + + "SSLEngine to abort. Will try to properly close connection..."); + sslEngine.closeOutbound(); + handshakeStatus = sslEngine.getHandshakeStatus(); + break; + } + + switch (result.getStatus()) { + case OK: + break; + case BUFFER_OVERFLOW: + throw new IllegalStateException("Unexpected ssl engine result"); + case BUFFER_UNDERFLOW: + LOGGER.debug("Increase ssl network buffer"); + increaseNetworkBuffer(); + break; + case CLOSED: + if (sslEngine.isOutboundDone()) { + return SKIP_READ_PACKETS; + } else { + sslEngine.closeOutbound(); + handshakeStatus = sslEngine.getHandshakeStatus(); + break; + } + default: + throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); + } + break; } + case NEED_WRAP: + LOGGER.debug("Send command to wrap data"); + packetWriter.accept(SSLWritablePacket.getInstance()); + sslNetworkBuffer.clear(); + return SKIP_READ_PACKETS; + case NEED_TASK: - return decryptAndRead(receivedBuffer); - } + Runnable task; - protected int decryptAndRead(@NotNull ByteBuffer receivedBuffer) { + while ((task = sslEngine.getDelegatedTask()) != null) { + LOGGER.debug(task, t -> "Execute SSL Engine's task: " + t.getClass()); + task.run(); + } - int total = 0; + handshakeStatus = sslEngine.getHandshakeStatus(); - while (receivedBuffer.hasRemaining()) { + LOGGER.debug(handshakeStatus, status -> "Handshake status: " + status + " after engine tasks"); - SSLEngineResult result; - try { - LOGGER.debug(receivedBuffer, buf -> "Try to decrypt data:\n" + hexDump(buf)); - result = sslEngine.unwrap(receivedBuffer, sslDataBuffer.clear()); - } catch (SSLException e) { - var handshakeStatus = sslEngine.getHandshakeStatus(); - throw new IllegalStateException(e); - } + if (handshakeStatus == HandshakeStatus.NEED_UNWRAP && !receivedBuffer.hasRemaining()) { + sslNetworkBuffer.clear(); + return SKIP_READ_PACKETS; + } - switch (result.getStatus()) { - case OK: - sslDataBuffer.flip(); - LOGGER.debug(sslDataBuffer, buf -> "Decrypted data:\n" + hexDump(buf)); - total += readPackets(sslDataBuffer, pendingBuffer); - break; - case BUFFER_OVERFLOW: - increaseDataBuffer(); - return decryptAndRead(receivedBuffer); - case CLOSED: - closeConnection(); - return SKIP_READ_PACKETS; - default: - - if (receivedBuffer.position() > 0) { - receivedBuffer.compact(); - return total; - } - - throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); - } - } + break; + default: + throw new IllegalStateException("Invalid SSL status: " + handshakeStatus); + } + } - receivedBuffer.clear(); + if (!receivedBuffer.hasRemaining()) { - return total; - } + // if buffer is empty and status is FINISHED then we can notify writer + if (handshakeStatus == HandshakeStatus.FINISHED) { + packetWriter.accept(SSLWritablePacket.getInstance()); + } + + receivedBuffer.clear(); - private void increaseNetworkBuffer() { - sslNetworkBuffer = NetworkUtils.increasePacketBuffer( - sslNetworkBuffer, - bufferAllocator, - sslEngine - ); + return SKIP_READ_PACKETS; } - private void increaseDataBuffer() { - sslDataBuffer = NetworkUtils.increaseApplicationBuffer( - sslDataBuffer, - bufferAllocator, - sslEngine - ); + return decryptAndRead(receivedBuffer); + } + + protected int decryptAndRead(@NotNull ByteBuffer receivedBuffer) { + + int total = 0; + + while (receivedBuffer.hasRemaining()) { + + SSLEngineResult result; + try { + LOGGER.debug(receivedBuffer, buf -> "Try to decrypt data:\n" + hexDump(buf)); + result = sslEngine.unwrap(receivedBuffer, sslDataBuffer.clear()); + } catch (SSLException e) { + var handshakeStatus = sslEngine.getHandshakeStatus(); + throw new IllegalStateException(e); + } + + switch (result.getStatus()) { + case OK: + sslDataBuffer.flip(); + LOGGER.debug(sslDataBuffer, buf -> "Decrypted data:\n" + hexDump(buf)); + total += readPackets(sslDataBuffer, pendingBuffer); + break; + case BUFFER_OVERFLOW: + increaseDataBuffer(); + return decryptAndRead(receivedBuffer); + case CLOSED: + closeConnection(); + return SKIP_READ_PACKETS; + default: + + if (receivedBuffer.position() > 0) { + receivedBuffer.compact(); + return total; + } + + throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); + } } - protected void closeConnection() { - try { - sslEngine.closeOutbound(); - channel.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } + receivedBuffer.clear(); + + return total; + } + + private void increaseNetworkBuffer() { + sslNetworkBuffer = NetworkUtils.increasePacketBuffer(sslNetworkBuffer, bufferAllocator, sslEngine); + } + + private void increaseDataBuffer() { + sslDataBuffer = NetworkUtils.increaseApplicationBuffer(sslDataBuffer, bufferAllocator, sslEngine); + } + + protected void closeConnection() { + try { + sslEngine.closeOutbound(); + channel.close(); + } catch (IOException e) { + throw new RuntimeException(e); } + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java index d5901889..27ad65e2 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java @@ -25,196 +25,188 @@ public abstract class AbstractSSLPacketWriter> extends AbstractPacketWriter { - private static final Logger LOGGER = LoggerManager.getLogger(AbstractSSLPacketWriter.class); - - private static final ByteBuffer[] EMPTY_BUFFERS = { - NetworkUtils.EMPTY_BUFFER - }; - - protected final @NotNull SSLEngine sslEngine; - protected final @NotNull NotNullConsumer packetWriter; - protected final @NotNull NotNullConsumer queueAtFirst; - - protected volatile @NotNull ByteBuffer sslNetworkBuffer; - - public AbstractSSLPacketWriter( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NullableSupplier packetProvider, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, - @NotNull NotNullConsumer queueAtFirst - ) { - super( - connection, - channel, - bufferAllocator, - updateActivityFunction, - packetProvider, - writtenPacketHandler, - sentPacketHandler - ); - this.sslEngine = sslEngine; - this.packetWriter = packetWriter; - this.queueAtFirst = queueAtFirst; - this.sslNetworkBuffer = bufferAllocator.takeBuffer(sslEngine.getSession().getPacketBufferSize()); + private static final Logger LOGGER = LoggerManager.getLogger(AbstractSSLPacketWriter.class); + + private static final ByteBuffer[] EMPTY_BUFFERS = { + NetworkUtils.EMPTY_BUFFER + }; + + protected final @NotNull SSLEngine sslEngine; + protected final @NotNull NotNullConsumer packetWriter; + protected final @NotNull NotNullConsumer queueAtFirst; + + protected volatile @NotNull ByteBuffer sslNetworkBuffer; + + public AbstractSSLPacketWriter( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NullableSupplier packetProvider, + @NotNull NotNullConsumer writtenPacketHandler, + @NotNull NotNullBiConsumer sentPacketHandler, + @NotNull SSLEngine sslEngine, + @NotNull NotNullConsumer packetWriter, + @NotNull NotNullConsumer queueAtFirst) { + super( + connection, + channel, + bufferAllocator, + updateActivityFunction, + packetProvider, + writtenPacketHandler, + sentPacketHandler); + this.sslEngine = sslEngine; + this.packetWriter = packetWriter; + this.queueAtFirst = queueAtFirst; + this.sslNetworkBuffer = bufferAllocator.takeBuffer(sslEngine + .getSession() + .getPacketBufferSize()); + } + + @Override + public void writeNextPacket() { + + var status = sslEngine.getHandshakeStatus(); + + switch (status) { + case NEED_UNWRAP: + return; } - @Override - public void writeNextPacket() { + super.writeNextPacket(); + } - var status = sslEngine.getHandshakeStatus(); + @Override + protected @NotNull ByteBuffer serialize(@NotNull WritablePacket packet) { - switch (status) { - case NEED_UNWRAP: - return; - } + var status = sslEngine.getHandshakeStatus(); - super.writeNextPacket(); + if (status == HandshakeStatus.FINISHED || status == HandshakeStatus.NOT_HANDSHAKING) { + + if (packet instanceof SSLWritablePacket) { + return EMPTY_BUFFER; + } + + var dataBuffer = super.serialize(packet); + + LOGGER.debug(dataBuffer, buff -> "Try to encrypt data:\n" + hexDump(buff)); + + SSLEngineResult result; + try { + result = sslEngine.wrap(dataBuffer, sslNetworkBuffer.clear()); + } catch (SSLException e) { + throw new RuntimeException(e); + } + + switch (result.getStatus()) { + case BUFFER_UNDERFLOW: + increaseNetworkBuffer(); + break; + case BUFFER_OVERFLOW: + throw new IllegalStateException("Unexpected ssl engine result"); + case OK: + return sslNetworkBuffer.flip(); + case CLOSED: + closeConnection(); + return EMPTY_BUFFER; + } } - @Override - protected @NotNull ByteBuffer serialize(@NotNull WritablePacket packet) { + var bufferToWrite = doHandshake(packet); - var status = sslEngine.getHandshakeStatus(); + if (bufferToWrite != null) { + return bufferToWrite; + } - if (status == HandshakeStatus.FINISHED || status == HandshakeStatus.NOT_HANDSHAKING) { + throw new IllegalStateException(); + } - if (packet instanceof SSLWritablePacket) { - return EMPTY_BUFFER; - } - - var dataBuffer = super.serialize(packet); - - LOGGER.debug(dataBuffer, buff -> "Try to encrypt data:\n" + hexDump(buff)); - - SSLEngineResult result; - try { - result = sslEngine.wrap(dataBuffer, sslNetworkBuffer.clear()); - } catch (SSLException e) { - throw new RuntimeException(e); - } - - switch (result.getStatus()) { - case BUFFER_UNDERFLOW: - increaseNetworkBuffer(); - break; - case BUFFER_OVERFLOW: - throw new IllegalStateException("Unexpected ssl engine result"); - case OK: - return sslNetworkBuffer.flip(); - case CLOSED: - closeConnection(); - return EMPTY_BUFFER; - } - } - - var bufferToWrite = doHandshake(packet); - - if (bufferToWrite != null) { - return bufferToWrite; - } - - throw new IllegalStateException(); + protected @Nullable ByteBuffer doHandshake(@NotNull WritablePacket packet) { + + if (!(packet instanceof SSLWritablePacket)) { + LOGGER.debug(packet, pck -> "Return packet " + pck + " to queue as first"); + queueAtFirst.accept(packet); } - protected @Nullable ByteBuffer doHandshake(@NotNull WritablePacket packet) { - - if (!(packet instanceof SSLWritablePacket)) { - LOGGER.debug(packet, pck -> "Return packet " + pck + " to queue as first"); - queueAtFirst.accept(packet); - } - - var handshakeStatus = sslEngine.getHandshakeStatus(); - - while (handshakeStatus != HandshakeStatus.FINISHED && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING) { - - SSLEngineResult result; - - switch (handshakeStatus) { - - case NEED_WRAP: - try { - // check result - result = sslEngine.wrap(EMPTY_BUFFERS, sslNetworkBuffer.clear()); - handshakeStatus = result.getHandshakeStatus(); - } catch (SSLException sslException) { - LOGGER.error("A problem was encountered while processing the data that caused the SSLEngine " + - "to abort. Will try to properly close connection..."); - sslEngine.closeOutbound(); - handshakeStatus = sslEngine.getHandshakeStatus(); - break; - } - switch (result.getStatus()) { - case OK: - - sslNetworkBuffer.flip(); - - if (handshakeStatus == HandshakeStatus.NEED_WRAP) { - LOGGER.debug("Send command to wrap data again"); - queueAtFirst.accept(SSLWritablePacket.getInstance()); - } - - LOGGER.debug( - sslNetworkBuffer, - result, - (buf, res) -> "Send wrapped data:\n" + hexDump(buf, res) - ); - - return sslNetworkBuffer; - case BUFFER_OVERFLOW: - sslNetworkBuffer = NetworkUtils.enlargePacketBuffer(bufferAllocator, sslEngine); - break; - case BUFFER_UNDERFLOW: - throw new IllegalStateException("Unexpected ssl engine result"); - case CLOSED: - try { - return EMPTY_BUFFER; - } catch (Exception e) { - LOGGER.error("Failed to send server's CLOSE message due to socket channel's failure."); - handshakeStatus = sslEngine.getHandshakeStatus(); - } - break; - default: - throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); - } - break; - case NEED_TASK: - Runnable task; - while ((task = sslEngine.getDelegatedTask()) != null) { - LOGGER.debug(task, t -> "Execute SSL Engine's task: " + t.getClass()); - task.run(); - } - handshakeStatus = sslEngine.getHandshakeStatus(); - break; - case NEED_UNWRAP: - break; - default: - throw new IllegalStateException("Invalid SSL status: " + handshakeStatus); - } - } + var handshakeStatus = sslEngine.getHandshakeStatus(); - return EMPTY_BUFFER; - } + while (handshakeStatus != HandshakeStatus.FINISHED && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING) { - private void increaseNetworkBuffer() { - sslNetworkBuffer = NetworkUtils.increasePacketBuffer( - sslNetworkBuffer, - bufferAllocator, - sslEngine - ); - } + SSLEngineResult result; + + switch (handshakeStatus) { - protected void closeConnection() { - try { + case NEED_WRAP: + try { + // check result + result = sslEngine.wrap(EMPTY_BUFFERS, sslNetworkBuffer.clear()); + handshakeStatus = result.getHandshakeStatus(); + } catch (SSLException sslException) { + LOGGER.error("A problem was encountered while processing the data that caused the SSLEngine " + + "to abort. Will try to properly close connection..."); sslEngine.closeOutbound(); - channel.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } + handshakeStatus = sslEngine.getHandshakeStatus(); + break; + } + switch (result.getStatus()) { + case OK: + + sslNetworkBuffer.flip(); + + if (handshakeStatus == HandshakeStatus.NEED_WRAP) { + LOGGER.debug("Send command to wrap data again"); + queueAtFirst.accept(SSLWritablePacket.getInstance()); + } + + LOGGER.debug(sslNetworkBuffer, result, (buf, res) -> "Send wrapped data:\n" + hexDump(buf, res)); + + return sslNetworkBuffer; + case BUFFER_OVERFLOW: + sslNetworkBuffer = NetworkUtils.enlargePacketBuffer(bufferAllocator, sslEngine); + break; + case BUFFER_UNDERFLOW: + throw new IllegalStateException("Unexpected ssl engine result"); + case CLOSED: + try { + return EMPTY_BUFFER; + } catch (Exception e) { + LOGGER.error("Failed to send server's CLOSE message due to socket channel's failure."); + handshakeStatus = sslEngine.getHandshakeStatus(); + } + break; + default: + throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); + } + break; + case NEED_TASK: + Runnable task; + while ((task = sslEngine.getDelegatedTask()) != null) { + LOGGER.debug(task, t -> "Execute SSL Engine's task: " + t.getClass()); + task.run(); + } + handshakeStatus = sslEngine.getHandshakeStatus(); + break; + case NEED_UNWRAP: + break; + default: + throw new IllegalStateException("Invalid SSL status: " + handshakeStatus); + } + } + + return EMPTY_BUFFER; + } + + private void increaseNetworkBuffer() { + sslNetworkBuffer = NetworkUtils.increasePacketBuffer(sslNetworkBuffer, bufferAllocator, sslEngine); + } + + protected void closeConnection() { + try { + sslEngine.closeOutbound(); + channel.close(); + } catch (IOException e) { + throw new RuntimeException(e); } + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java index bf599c70..65a024c0 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java @@ -11,22 +11,22 @@ */ public abstract class AbstractWritablePacket extends AbstractPacket implements WritablePacket { - @Override - public boolean write(@NotNull ByteBuffer buffer) { - try { - writeImpl(buffer); - return true; - } catch (Exception e) { - handleException(buffer, e); - return false; - } + @Override + public boolean write(@NotNull ByteBuffer buffer) { + try { + writeImpl(buffer); + return true; + } catch (Exception e) { + handleException(buffer, e); + return false; } + } - /** - * The process of writing this packet to the buffer. - * - * @param buffer the buffer - */ - protected void writeImpl(@NotNull ByteBuffer buffer) { - } + /** + * The process of writing this packet to the buffer. + * + * @param buffer the buffer + */ + protected void writeImpl(@NotNull ByteBuffer buffer) { + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java index 507ab2a3..b5cca044 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java @@ -18,48 +18,39 @@ public class DefaultPacketReader> extends AbstractPacketReader { - private final IntFunction readPacketFactory; - private final int packetLengthHeaderSize; + private final IntFunction readPacketFactory; + private final int packetLengthHeaderSize; - public DefaultPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, - @NotNull IntFunction readPacketFactory, - int packetLengthHeaderSize, - int maxPacketsByRead - ) { - super( - connection, - channel, - bufferAllocator, - updateActivityFunction, - readPacketHandler, - maxPacketsByRead - ); - this.readPacketFactory = readPacketFactory; - this.packetLengthHeaderSize = packetLengthHeaderSize; - } + public DefaultPacketReader( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NotNullConsumer readPacketHandler, + @NotNull IntFunction readPacketFactory, + int packetLengthHeaderSize, + int maxPacketsByRead) { + super(connection, channel, bufferAllocator, updateActivityFunction, readPacketHandler, maxPacketsByRead); + this.readPacketFactory = readPacketFactory; + this.packetLengthHeaderSize = packetLengthHeaderSize; + } - @Override - protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { - return buffer.remaining() >= packetLengthHeaderSize; - } + @Override + protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { + return buffer.remaining() >= packetLengthHeaderSize; + } - @Override - protected int readPacketLength(@NotNull ByteBuffer buffer) { - return readHeader(buffer, packetLengthHeaderSize); - } + @Override + protected int readPacketLength(@NotNull ByteBuffer buffer) { + return readHeader(buffer, packetLengthHeaderSize); + } - @Override - protected @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, - int startPacketPosition, - int packetLength, - int dataLength - ) { - return readPacketFactory.apply(dataLength); - } + @Override + protected @Nullable R createPacketFor( + @NotNull ByteBuffer buffer, + int startPacketPosition, + int packetLength, + int dataLength) { + return readPacketFactory.apply(dataLength); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java index dcd52ff0..6406ecd6 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java @@ -16,59 +16,57 @@ public class DefaultPacketWriter> extends AbstractPacketWriter { - protected final int packetLengthHeaderSize; + protected final int packetLengthHeaderSize; - public DefaultPacketWriter( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NullableSupplier nextWritePacketSupplier, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, - int packetLengthHeaderSize - ) { - super( - connection, - channel, - bufferAllocator, - updateActivityFunction, - nextWritePacketSupplier, - writtenPacketHandler, - sentPacketHandler - ); - this.packetLengthHeaderSize = packetLengthHeaderSize; - } + public DefaultPacketWriter( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NullableSupplier nextWritePacketSupplier, + @NotNull NotNullConsumer writtenPacketHandler, + @NotNull NotNullBiConsumer sentPacketHandler, + int packetLengthHeaderSize) { + super( + connection, + channel, + bufferAllocator, + updateActivityFunction, + nextWritePacketSupplier, + writtenPacketHandler, + sentPacketHandler); + this.packetLengthHeaderSize = packetLengthHeaderSize; + } - @Override - protected int getTotalSize(@NotNull WritablePacket packet, int expectedLength) { - return expectedLength + packetLengthHeaderSize; - } + @Override + protected int getTotalSize(@NotNull WritablePacket packet, int expectedLength) { + return expectedLength + packetLengthHeaderSize; + } - @Override - protected boolean onBeforeWrite( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - firstBuffer.clear().position(packetLengthHeaderSize); - return true; - } + @Override + protected boolean onBeforeWrite( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + firstBuffer + .clear() + .position(packetLengthHeaderSize); + return true; + } - @Override - protected @NotNull ByteBuffer onResult( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - return writePacketLength(firstBuffer, firstBuffer.limit()).position(0); - } + @Override + protected @NotNull ByteBuffer onResult( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + return writePacketLength(firstBuffer, firstBuffer.limit()).position(0); + } - protected @NotNull ByteBuffer writePacketLength(@NotNull ByteBuffer buffer, int packetLength) { - return writeHeader(buffer, 0, packetLength, packetLengthHeaderSize); - } + protected @NotNull ByteBuffer writePacketLength(@NotNull ByteBuffer buffer, int packetLength) { + return writeHeader(buffer, 0, packetLength, packetLengthHeaderSize); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultReadablePacket.java index cd07d802..2246885c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultReadablePacket.java @@ -7,5 +7,4 @@ */ public class DefaultReadablePacket extends AbstractIdBasedReadablePacket { - } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java index a7bf4c01..d3693252 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java @@ -20,52 +20,49 @@ public class DefaultSSLPacketReader> extends AbstractSSLPacketReader { - private final IntFunction readPacketFactory; - private final int packetLengthHeaderSize; + private final IntFunction readPacketFactory; + private final int packetLengthHeaderSize; - public DefaultSSLPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, - @NotNull IntFunction readPacketFactory, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, - int packetLengthHeaderSize, - int maxPacketsByRead - ) { - super( - connection, - channel, - bufferAllocator, - updateActivityFunction, - readPacketHandler, - sslEngine, - packetWriter, - maxPacketsByRead - ); - this.readPacketFactory = readPacketFactory; - this.packetLengthHeaderSize = packetLengthHeaderSize; - } + public DefaultSSLPacketReader( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NotNullConsumer readPacketHandler, + @NotNull IntFunction readPacketFactory, + @NotNull SSLEngine sslEngine, + @NotNull NotNullConsumer packetWriter, + int packetLengthHeaderSize, + int maxPacketsByRead) { + super( + connection, + channel, + bufferAllocator, + updateActivityFunction, + readPacketHandler, + sslEngine, + packetWriter, + maxPacketsByRead); + this.readPacketFactory = readPacketFactory; + this.packetLengthHeaderSize = packetLengthHeaderSize; + } - @Override - protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { - return buffer.remaining() >= packetLengthHeaderSize; - } + @Override + protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { + return buffer.remaining() >= packetLengthHeaderSize; + } - @Override - protected int readPacketLength(@NotNull ByteBuffer buffer) { - return readHeader(buffer, packetLengthHeaderSize); - } + @Override + protected int readPacketLength(@NotNull ByteBuffer buffer) { + return readHeader(buffer, packetLengthHeaderSize); + } - @Override - protected @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, - int startPacketPosition, - int packetLength, - int dataLength - ) { - return readPacketFactory.apply(dataLength); - } + @Override + protected @Nullable R createPacketFor( + @NotNull ByteBuffer buffer, + int startPacketPosition, + int packetLength, + int dataLength) { + return readPacketFactory.apply(dataLength); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java index 9a0a9316..c14162b9 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java @@ -17,65 +17,63 @@ public class DefaultSSLPacketWriter> extends AbstractSSLPacketWriter { - protected final int packetLengthHeaderSize; + protected final int packetLengthHeaderSize; - public DefaultSSLPacketWriter( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NullableSupplier nextWritePacketSupplier, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, - @NotNull NotNullConsumer queueAtFirst, - int packetLengthHeaderSize - ) { - super( - connection, - channel, - bufferAllocator, - updateActivityFunction, - nextWritePacketSupplier, - writtenPacketHandler, - sentPacketHandler, - sslEngine, - packetWriter, - queueAtFirst - ); - this.packetLengthHeaderSize = packetLengthHeaderSize; - } + public DefaultSSLPacketWriter( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NullableSupplier nextWritePacketSupplier, + @NotNull NotNullConsumer writtenPacketHandler, + @NotNull NotNullBiConsumer sentPacketHandler, + @NotNull SSLEngine sslEngine, + @NotNull NotNullConsumer packetWriter, + @NotNull NotNullConsumer queueAtFirst, + int packetLengthHeaderSize) { + super( + connection, + channel, + bufferAllocator, + updateActivityFunction, + nextWritePacketSupplier, + writtenPacketHandler, + sentPacketHandler, + sslEngine, + packetWriter, + queueAtFirst); + this.packetLengthHeaderSize = packetLengthHeaderSize; + } - @Override - protected int getTotalSize(@NotNull WritablePacket packet, int expectedLength) { - return expectedLength + packetLengthHeaderSize; - } + @Override + protected int getTotalSize(@NotNull WritablePacket packet, int expectedLength) { + return expectedLength + packetLengthHeaderSize; + } - @Override - protected boolean onBeforeWrite( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - firstBuffer.clear().position(packetLengthHeaderSize); - return true; - } + @Override + protected boolean onBeforeWrite( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + firstBuffer + .clear() + .position(packetLengthHeaderSize); + return true; + } - @Override - protected @NotNull ByteBuffer onResult( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - return writePacketLength(firstBuffer, firstBuffer.limit()).position(0); - } + @Override + protected @NotNull ByteBuffer onResult( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + return writePacketLength(firstBuffer, firstBuffer.limit()).position(0); + } - protected @NotNull ByteBuffer writePacketLength(@NotNull ByteBuffer buffer, int packetLength) { - return writeHeader(buffer, 0, packetLength, packetLengthHeaderSize); - } + protected @NotNull ByteBuffer writePacketLength(@NotNull ByteBuffer buffer, int packetLength) { + return writeHeader(buffer, 0, packetLength, packetLengthHeaderSize); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java index 9022313c..b77a8343 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java @@ -18,52 +18,44 @@ public class IdBasedPacketReader, C extends Connection> extends AbstractPacketReader { - private final ReadablePacketRegistry packetRegistry; - private final int packetLengthHeaderSize; - private final int packetIdHeaderSize; + private final ReadablePacketRegistry packetRegistry; + private final int packetLengthHeaderSize; + private final int packetIdHeaderSize; - public IdBasedPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, - int packetLengthHeaderSize, - int maxPacketsByRead, - int packetIdHeaderSize, - @NotNull ReadablePacketRegistry packetRegistry - ) { - super( - connection, - channel, - bufferAllocator, - updateActivityFunction, - readPacketHandler, - maxPacketsByRead - ); - this.packetLengthHeaderSize = packetLengthHeaderSize; - this.packetIdHeaderSize = packetIdHeaderSize; - this.packetRegistry = packetRegistry; - } + public IdBasedPacketReader( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NotNullConsumer readPacketHandler, + int packetLengthHeaderSize, + int maxPacketsByRead, + int packetIdHeaderSize, + @NotNull ReadablePacketRegistry packetRegistry) { + super(connection, channel, bufferAllocator, updateActivityFunction, readPacketHandler, maxPacketsByRead); + this.packetLengthHeaderSize = packetLengthHeaderSize; + this.packetIdHeaderSize = packetIdHeaderSize; + this.packetRegistry = packetRegistry; + } - @Override - protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { - return buffer.remaining() > packetLengthHeaderSize; - } + @Override + protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { + return buffer.remaining() > packetLengthHeaderSize; + } - @Override - protected int readPacketLength(@NotNull ByteBuffer buffer) { - return readHeader(buffer, packetLengthHeaderSize); - } + @Override + protected int readPacketLength(@NotNull ByteBuffer buffer) { + return readHeader(buffer, packetLengthHeaderSize); + } - @Override - protected @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, - int startPacketPosition, - int packetLength, - int dataLength - ) { - return packetRegistry.findById(readHeader(buffer, packetIdHeaderSize)) - .newInstance(); - } + @Override + protected @Nullable R createPacketFor( + @NotNull ByteBuffer buffer, + int startPacketPosition, + int packetLength, + int dataLength) { + return packetRegistry + .findById(readHeader(buffer, packetIdHeaderSize)) + .newInstance(); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java index 5ba0aadc..96ed5805 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java @@ -17,41 +17,38 @@ public class IdBasedPacketWriter> extends DefaultPacketWriter { - protected final int packetIdHeaderSize; + protected final int packetIdHeaderSize; - public IdBasedPacketWriter( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NullableSupplier nextWritePacketSupplier, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, - int packetLengthHeaderSize, - int packetIdHeaderSize - ) { - super( - connection, - channel, - bufferAllocator, - updateActivityFunction, - nextWritePacketSupplier, - writtenPacketHandler, - sentPacketHandler, - packetLengthHeaderSize - ); - this.packetIdHeaderSize = packetIdHeaderSize; - } + public IdBasedPacketWriter( + @NotNull C connection, + @NotNull AsynchronousSocketChannel channel, + @NotNull BufferAllocator bufferAllocator, + @NotNull Runnable updateActivityFunction, + @NotNull NullableSupplier nextWritePacketSupplier, + @NotNull NotNullConsumer writtenPacketHandler, + @NotNull NotNullBiConsumer sentPacketHandler, + int packetLengthHeaderSize, + int packetIdHeaderSize) { + super( + connection, + channel, + bufferAllocator, + updateActivityFunction, + nextWritePacketSupplier, + writtenPacketHandler, + sentPacketHandler, + packetLengthHeaderSize); + this.packetIdHeaderSize = packetIdHeaderSize; + } - @Override - protected boolean onWrite( - @NotNull W packet, - int expectedLength, - int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer - ) { - writeHeader(firstBuffer, packet.getPacketId(), packetIdHeaderSize); - return super.onWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer); - } + @Override + protected boolean onWrite( + @NotNull W packet, + int expectedLength, + int totalSize, + @NotNull ByteBuffer firstBuffer, + @NotNull ByteBuffer secondBuffer) { + writeHeader(firstBuffer, packet.getPacketId(), packetIdHeaderSize); + return super.onWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer); + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java index 9ddb9e6b..9167a1d8 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java @@ -8,14 +8,14 @@ */ public class SSLWritablePacket extends AbstractWritablePacket { - private static final SSLWritablePacket INSTANCE = new SSLWritablePacket(); + private static final SSLWritablePacket INSTANCE = new SSLWritablePacket(); - public static SSLWritablePacket getInstance() { - return INSTANCE; - } + public static SSLWritablePacket getInstance() { + return INSTANCE; + } - @Override - public boolean write(@NotNull ByteBuffer buffer) { - return true; - } + @Override + public boolean write(@NotNull ByteBuffer buffer) { + return true; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java index 36c7f5ae..1f34505f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java @@ -12,25 +12,25 @@ @Getter public class StringReadablePacket extends AbstractReadablePacket> { - /** - * Read data. - */ - private volatile @Nullable String data; - - @Override - protected void readImpl(@NotNull Connection connection, @NotNull ByteBuffer buffer) { - this.data = readString(buffer); - } + /** + * Read data. + */ + private volatile @Nullable String data; - @Override - public @NotNull String toString() { + @Override + protected void readImpl(@NotNull Connection connection, @NotNull ByteBuffer buffer) { + this.data = readString(buffer); + } - var data = getData(); + @Override + public @NotNull String toString() { - if (data != null && data.length() > 20) { - data = data.substring(0, 9) + "..." + data.substring(9, 19); - } + var data = getData(); - return "StringReadablePacket(" + "data='" + data + '\'' + ')'; + if (data != null && data.length() > 20) { + data = data.substring(0, 9) + "..." + data.substring(9, 19); } + + return "StringReadablePacket(" + "data='" + data + '\'' + ')'; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java index f8678846..b66c42ae 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java @@ -10,21 +10,21 @@ @RequiredArgsConstructor public class StringWritablePacket extends AbstractWritablePacket { - private final @NotNull String data; + private final @NotNull String data; - @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { - super.writeImpl(buffer); - writeString(buffer, data); - } + @Override + protected void writeImpl(@NotNull ByteBuffer buffer) { + super.writeImpl(buffer); + writeString(buffer, data); + } - @Override - public int getExpectedLength() { - return 4 + data.length() * 2; - } + @Override + public int getExpectedLength() { + return 4 + data.length() * 2; + } - @Override - public @NotNull String toString() { - return "StringWritablePacket {\n" + "\"\tdataLength\":" + data.length() + "\n}"; - } + @Override + public @NotNull String toString() { + return "StringWritablePacket {\n" + "\"\tdataLength\":" + data.length() + "\n}"; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java index 69fc9b8f..dd87b530 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java @@ -16,21 +16,21 @@ @RequiredArgsConstructor public class WritablePacketWrapper implements WritablePacket { - private final A attachment; - private final W packet; + private final A attachment; + private final W packet; - @Override - public boolean write(@NotNull ByteBuffer buffer) { - return packet.write(buffer); - } + @Override + public boolean write(@NotNull ByteBuffer buffer) { + return packet.write(buffer); + } - @Override - public int getExpectedLength() { - return packet.getExpectedLength(); - } + @Override + public int getExpectedLength() { + return packet.getExpectedLength(); + } - @Override - public @NotNull String getName() { - return "WritablePacketWrapper"; - } + @Override + public @NotNull String getName() { + return "WritablePacketWrapper"; + } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java index 71512c02..f5221c6a 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java @@ -16,117 +16,116 @@ */ public interface ReadablePacketRegistry> { - /** - * Create a new empty readable packet registry. - * - * @return the new packet registry. - */ - static @NotNull ReadablePacketRegistry empty() { - return new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class); - } - - /** - * Create a new empty readable packet registry. - * - * @param type the packet's type. - * @param the packet's type. - * @return the new packet registry. - */ - static > @NotNull ReadablePacketRegistry empty(@NotNull Class type) { - return new IdBasedReadablePacketRegistry<>(type); - } - - /** - * Create a new default readable packet registry. - * - * @return the new packet registry. - */ - static @NotNull ReadablePacketRegistry newDefault() { - - var scanner = ClassPathScannerFactory.newDefaultScanner(); - scanner.setUseSystemClasspath(true); - scanner.scan(); - - return of(scanner); - } - - /** - * Create a new default readable packet registry by the result of scanning classpath of the main class. - * - * @param mainClass the main class of application. - * @return the new packet registry. - */ - static @NotNull ReadablePacketRegistry newDefault(@NotNull Class mainClass) { - - var scanner = ClassPathScannerFactory.newManifestScanner(mainClass); - scanner.setUseSystemClasspath(false); - scanner.scan(); - - return of(scanner); - } - - /** - * Creates a new default readable packet registry by the classpath scanner. - * - * @param scanner the classpath scanner. - * @return the new packet registry. - */ - static @NotNull ReadablePacketRegistry of(@NotNull ClassPathScanner scanner) { - - var result = scanner.findImplements(IdBasedReadablePacket.class) - .stream() - .filter(type -> type.getAnnotation(PacketDescription.class) != null) - .collect(ArrayCollectors.>toArray(Class.class)); - - var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class); - registry.register(result); - - return registry; - } - - /** - * Create a new readable packet registry by array of classes. - * - * @param type the base packet's type. - * @param classes the classes array. - * @param the packet's type. - * @return the new packet registry. - */ - @SafeVarargs - static > @NotNull ReadablePacketRegistry of( - @NotNull Class type, - @NotNull Class... classes - ) { - var registry = new IdBasedReadablePacketRegistry<>(type); - registry.register(classes, classes.length); - return registry; - } - - /** - * Create a new readable packet registry by array of classes. - * - * @param type the base packet's type. - * @param classes the classes array. - * @param the packet's type. - * @return the new packet registry. - */ - static > @NotNull ReadablePacketRegistry of( - @NotNull Class type, - @NotNull Array> classes - ) { - - var registry = new IdBasedReadablePacketRegistry<>(type); - registry.register(classes); - - return registry; - } - - /** - * Find a packet by the id. - * - * @param id the packet id. - * @return the packet. - * @throws IllegalArgumentException if can't find a packet by the id. - */ - @NotNull R findById(int id); + /** + * Create a new empty readable packet registry. + * + * @return the new packet registry. + */ + static @NotNull ReadablePacketRegistry empty() { + return new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class); + } + + /** + * Create a new empty readable packet registry. + * + * @param type the packet's type. + * @param the packet's type. + * @return the new packet registry. + */ + static > @NotNull ReadablePacketRegistry empty(@NotNull Class type) { + return new IdBasedReadablePacketRegistry<>(type); + } + + /** + * Create a new default readable packet registry. + * + * @return the new packet registry. + */ + static @NotNull ReadablePacketRegistry newDefault() { + + var scanner = ClassPathScannerFactory.newDefaultScanner(); + scanner.setUseSystemClasspath(true); + scanner.scan(); + + return of(scanner); + } + + /** + * Create a new default readable packet registry by the result of scanning classpath of the main class. + * + * @param mainClass the main class of application. + * @return the new packet registry. + */ + static @NotNull ReadablePacketRegistry newDefault(@NotNull Class mainClass) { + + var scanner = ClassPathScannerFactory.newManifestScanner(mainClass); + scanner.setUseSystemClasspath(false); + scanner.scan(); + + return of(scanner); + } + + /** + * Creates a new default readable packet registry by the classpath scanner. + * + * @param scanner the classpath scanner. + * @return the new packet registry. + */ + static @NotNull ReadablePacketRegistry of(@NotNull ClassPathScanner scanner) { + + var result = scanner + .findImplements(IdBasedReadablePacket.class) + .stream() + .filter(type -> type.getAnnotation(PacketDescription.class) != null) + .collect(ArrayCollectors.>toArray(Class.class)); + + var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class); + registry.register(result); + + return registry; + } + + /** + * Create a new readable packet registry by array of classes. + * + * @param type the base packet's type. + * @param classes the classes array. + * @param the packet's type. + * @return the new packet registry. + */ + @SafeVarargs + static > @NotNull ReadablePacketRegistry of( + @NotNull Class type, + @NotNull Class... classes) { + var registry = new IdBasedReadablePacketRegistry<>(type); + registry.register(classes, classes.length); + return registry; + } + + /** + * Create a new readable packet registry by array of classes. + * + * @param type the base packet's type. + * @param classes the classes array. + * @param the packet's type. + * @return the new packet registry. + */ + static > @NotNull ReadablePacketRegistry of( + @NotNull Class type, + @NotNull Array> classes) { + + var registry = new IdBasedReadablePacketRegistry<>(type); + registry.register(classes); + + return registry; + } + + /** + * Find a packet by the id. + * + * @param id the packet id. + * @return the packet. + * @throws IllegalArgumentException if can't find a packet by the id. + */ + @NotNull R findById(int id); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java index d9efaace..f71acfc0 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java @@ -22,178 +22,181 @@ */ public class IdBasedReadablePacketRegistry> implements ReadablePacketRegistry { - private static final Logger LOGGER = LoggerManager.getLogger(IdBasedReadablePacketRegistry.class); - - /** - * The packet's type in this registry. - */ - private final Class type; - - /** - * The array of packet id to packet instance. - */ - @Getter(AccessLevel.PRIVATE) - @Setter(AccessLevel.PRIVATE) - private volatile R[] idToPacket; - - public IdBasedReadablePacketRegistry(@NotNull Class type) { - this.idToPacket = ArrayUtils.create(type, 0); - this.type = type; + private static final Logger LOGGER = LoggerManager.getLogger(IdBasedReadablePacketRegistry.class); + + /** + * The packet's type in this registry. + */ + private final Class type; + + /** + * The array of packet id to packet instance. + */ + @Getter(AccessLevel.PRIVATE) + @Setter(AccessLevel.PRIVATE) + private volatile R[] idToPacket; + + public IdBasedReadablePacketRegistry(@NotNull Class type) { + this.idToPacket = ArrayUtils.create(type, 0); + this.type = type; + } + + /** + * Register classes of readable packets. + * + * @param classes the classes array. + * @return the reference to this registry. + * @throws IllegalArgumentException if found a class without packet description annotation or if found duplication by + * id. + */ + public @NotNull IdBasedReadablePacketRegistry register(@NotNull Array> classes) { + return register(classes.array(), classes.size()); + } + + /** + * Register classes of readable packets. + * + * @param classes the classes array. + * @return the reference to this registry. + * @throws IllegalArgumentException if found a class without packet description annotation or if found duplication by + * id. + */ + @SafeVarargs + public final @NotNull IdBasedReadablePacketRegistry register(@NotNull Class... classes) { + return register(classes, classes.length); + } + + /** + * Register classes of readable packets. + * + * @param classes the classes array. + * @param length the length of the classes. + * @return the reference to this registry. + * @throws IllegalArgumentException if found a class without packet description annotation or if found duplication by + * id. + */ + public @NotNull IdBasedReadablePacketRegistry register(@NotNull Class[] classes, int length) { + + var incorrectClass = Arrays + .stream(classes, 0, length) + .filter(type -> type.getAnnotation(PacketDescription.class) == null) + .findFirst(); + + if (incorrectClass.isPresent()) { + throw new IllegalArgumentException( + "Have found a class " + incorrectClass.get() + " without the packet description annotation."); } - /** - * Register classes of readable packets. - * - * @param classes the classes array. - * @return the reference to this registry. - * @throws IllegalArgumentException if found a class without packet description annotation or - * if found duplication by id. - */ - public @NotNull IdBasedReadablePacketRegistry register(@NotNull Array> classes) { - return register(classes.array(), classes.size()); - } - - /** - * Register classes of readable packets. - * - * @param classes the classes array. - * @return the reference to this registry. - * @throws IllegalArgumentException if found a class without packet description annotation or - * if found duplication by id. - */ - @SafeVarargs - public final @NotNull IdBasedReadablePacketRegistry register(@NotNull Class... classes) { - return register(classes, classes.length); - } + var maxId = Arrays + .stream(classes, 0, length) + .map(type -> type.getAnnotation(PacketDescription.class)) + .mapToInt(PacketDescription::id) + .max() + .orElseThrow(() -> new IllegalStateException("Not found any packet id")); - /** - * Register classes of readable packets. - * - * @param classes the classes array. - * @param length the length of the classes. - * @return the reference to this registry. - * @throws IllegalArgumentException if found a class without packet description annotation or - * if found duplication by id. - */ - public @NotNull IdBasedReadablePacketRegistry register(@NotNull Class[] classes, int length) { + setIdToPacket(Arrays.copyOf(getIdToPacket(), maxId + 1)); - var incorrectClass = Arrays.stream(classes, 0, length) - .filter(type -> type.getAnnotation(PacketDescription.class) == null) - .findFirst(); + var idToPacket = getIdToPacket(); - if (incorrectClass.isPresent()) { - throw new IllegalArgumentException("Have found a class " + incorrectClass.get() + - " without the packet description annotation."); - } + for (int i = 0; i < length; i++) { - var maxId = Arrays.stream(classes, 0, length) - .map(type -> type.getAnnotation(PacketDescription.class)) - .mapToInt(PacketDescription::id) - .max() - .orElseThrow(() -> new IllegalStateException("Not found any packet id")); + var cs = classes[i]; - setIdToPacket(Arrays.copyOf(getIdToPacket(), maxId + 1)); + if (!type.isAssignableFrom(cs)) { + LOGGER.warning( + cs, + type, + (detected, check) -> "Found incompatibility packet's type: " + detected + " with type: " + check); + continue; + } - var idToPacket = getIdToPacket(); + var description = cs.getAnnotation(PacketDescription.class); + var id = description.id(); - for (int i = 0; i < length; i++) { + if (idToPacket[id] != null) { + throw new IllegalArgumentException( + "Have found duplication by id " + id + ", existed packet is " + idToPacket[id].getClass() + + ", new packet is " + cs); + } - var cs = classes[i]; + idToPacket[id] = ClassUtils.newInstance(cs); + } - if (!type.isAssignableFrom(cs)) { - LOGGER.warning(cs, type, - (detected, check) -> "Found incompatibility packet's type: " + detected + " with type: " + check); - continue; - } + return this; + } + + /** + * Register a class of readable packet. + * + * @param cs the class. + * @return the reference to this registry. + * @throws IllegalArgumentException if this class doesn't have {@link PacketDescription}, wrong id or some class is + * already presented with the same id. + */ + public @NotNull IdBasedReadablePacketRegistry register(@NotNull Class cs) { + return register(cs, () -> ClassUtils.newInstance(cs)); + } + + /** + * Register a class of readable packet. + * + * @param cs the class. + * @param factory the instance factory. + * @param

the packet's type. + * @return the reference to this registry. + * @throws IllegalArgumentException if this class doesn't have {@link PacketDescription}, wrong id or some class is + * already presented with the same id. + */ + public

@NotNull IdBasedReadablePacketRegistry register( + @NotNull Class

cs, + @NotNull Supplier

factory) { + + var description = cs.getAnnotation(PacketDescription.class); + + if (description == null) { + throw new IllegalArgumentException("Class " + cs + " doesn't have packet description annotation."); + } - var description = cs.getAnnotation(PacketDescription.class); - var id = description.id(); + var id = description.id(); - if (idToPacket[id] != null) { - throw new IllegalArgumentException("Have found duplication by id " + id + ", existed packet is " + - idToPacket[id].getClass() + ", new packet is " + cs); - } + if (id < 0) { + throw new IllegalArgumentException("Class " + cs + " has wrong packet id: " + id); + } - idToPacket[id] = ClassUtils.newInstance(cs); - } + var idToPacket = getIdToPacket(); + if (id < idToPacket.length) { + if (idToPacket[id] != null) { + throw new IllegalArgumentException("Class " + idToPacket[id].getClass() + " is already has the same id: " + id); + } else { + idToPacket[id] = ClassUtils.newInstance(cs); return this; + } } - /** - * Register a class of readable packet. - * - * @param cs the class. - * @return the reference to this registry. - * @throws IllegalArgumentException if this class doesn't have {@link PacketDescription}, - * wrong id or some class is already presented with the same id. - */ - public @NotNull IdBasedReadablePacketRegistry register(@NotNull Class cs) { - return register(cs, () -> ClassUtils.newInstance(cs)); - } - - /** - * Register a class of readable packet. - * - * @param cs the class. - * @param factory the instance factory. - * @param

the packet's type. - * @return the reference to this registry. - * @throws IllegalArgumentException if this class doesn't have {@link PacketDescription}, - * wrong id or some class is already presented with the same id. - */ - public

@NotNull IdBasedReadablePacketRegistry register( - @NotNull Class

cs, - @NotNull Supplier

@NotNull IdBasedReadablePacketRegistry register( - @NotNull Class

cs, - @NotNull Supplier

factory) { + public

IdBasedReadablePacketRegistry register( + Class

cs, + Supplier

factory) { var description = cs.getAnnotation(PacketDescription.class); @@ -183,7 +182,7 @@ public IdBasedReadablePacketRegistry(@NotNull Class type) { } @Override - public @NotNull R findById(int id) { + public R findById(int id) { R[] idToPacket = getIdToPacket(); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/package-info.java new file mode 100644 index 00000000..a5580a7e --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.packet.registry.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/package-info.java new file mode 100644 index 00000000..29de48b2 --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.packet.registry; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file 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 07561724..877cd9ac 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 @@ -4,7 +4,6 @@ import java.util.function.Consumer; import javasabr.rlib.network.Connection; import javasabr.rlib.network.Network; -import org.jetbrains.annotations.NotNull; import reactor.core.publisher.Flux; /** @@ -19,7 +18,7 @@ public interface ServerNetwork> extends Network { * * @return this server's address. */ - @NotNull InetSocketAddress start(); + InetSocketAddress start(); /** * Start a server by the address. @@ -28,19 +27,19 @@ public interface ServerNetwork> extends Network { * @param the server network's type. * @return this network. */ - > @NotNull S start(@NotNull InetSocketAddress serverAddress); + > S start(InetSocketAddress serverAddress); /** * Register a consumer of new connections. * * @param consumer the consumer of new connections. */ - void onAccept(@NotNull Consumer consumer); + void onAccept(Consumer consumer); /** * Get a stream of new accepted connections. * * @return the stream of new accepted connections. */ - @NotNull Flux accepted(); + Flux accepted(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java index b6c033ad..faabd95c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java @@ -30,7 +30,6 @@ import javasabr.rlib.network.impl.AbstractNetwork; import javasabr.rlib.network.server.ServerNetwork; import javasabr.rlib.network.util.NetworkUtils; -import org.jetbrains.annotations.NotNull; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; @@ -50,7 +49,7 @@ private interface ServerCompletionHandler> exte private final ServerCompletionHandler acceptHandler = new ServerCompletionHandler<>() { @Override - public void completed(@NotNull AsynchronousSocketChannel channel, @NotNull DefaultServerNetwork network) { + public void completed(AsynchronousSocketChannel channel, DefaultServerNetwork network) { var connection = network.channelToConnection.apply(DefaultServerNetwork.this, channel); LOGGER.debug(connection, conn -> "Accepted new connection: " + conn.getRemoteAddress()); network.onAccept(connection); @@ -58,7 +57,7 @@ public void completed(@NotNull AsynchronousSocketChannel channel, @NotNull Defau } @Override - public void failed(@NotNull Throwable exc, @NotNull DefaultServerNetwork network) { + public void failed(Throwable exc, DefaultServerNetwork network) { if (exc instanceof AsynchronousCloseException) { LOGGER.warning("Server network was closed"); } else { @@ -77,8 +76,8 @@ public void failed(@NotNull Throwable exc, @NotNull DefaultServerNetwork netw protected final Array> subscribers; public DefaultServerNetwork( - @NotNull ServerNetworkConfig config, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + ServerNetworkConfig config, + BiFunction, AsynchronousSocketChannel, C> channelToConnection) { super(config, channelToConnection); @@ -116,7 +115,7 @@ public DefaultServerNetwork( } @Override - public @NotNull InetSocketAddress start() { + public InetSocketAddress start() { InetSocketAddress address = null; @@ -140,7 +139,7 @@ public DefaultServerNetwork( } @Override - public > @NotNull S start(@NotNull InetSocketAddress serverAddress) { + public > S start(InetSocketAddress serverAddress) { Utils.unchecked(channel, serverAddress, AsynchronousServerSocketChannel::bind); LOGGER.info(serverAddress, addr -> "Started server socket on address: " + addr); @@ -163,23 +162,23 @@ protected void acceptNext() { } } - protected void onAccept(@NotNull C connection) { + protected void onAccept(C connection) { connection.onConnected(); subscribers.forEachR(connection, Consumer::accept); } @Override - public void onAccept(@NotNull Consumer consumer) { + public void onAccept(Consumer consumer) { subscribers.add(consumer); acceptNext(); } @Override - public @NotNull Flux accepted() { + public Flux accepted() { return Flux.create(this::registerFluxOnAccepted); } - protected void registerFluxOnAccepted(@NotNull FluxSink sink) { + protected void registerFluxOnAccepted(FluxSink sink) { Consumer listener = sink::next; onAccept(listener); sink.onDispose(() -> subscribers.remove(listener)); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/server/impl/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/package-info.java new file mode 100644 index 00000000..cc6bc178 --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.server.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-network/src/main/java/javasabr/rlib/network/server/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/server/package-info.java new file mode 100644 index 00000000..15a0e7ef --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/server/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.server; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file 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 2933049e..374a2186 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 @@ -21,45 +21,44 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr */ public class NetworkUtils { - public static final @NotNull ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); + public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); public static class AllTrustManager implements X509TrustManager { - public static final @NotNull X509Certificate[] EMPTY_CERTS = new X509Certificate[0]; + public static final X509Certificate[] EMPTY_CERTS = new X509Certificate[0]; - public @NotNull X509Certificate[] getAcceptedIssuers() { + public X509Certificate[] getAcceptedIssuers() { return EMPTY_CERTS; } - public void checkClientTrusted(@NotNull X509Certificate[] certificates, @NotNull String arg1) { + public void checkClientTrusted(X509Certificate[] certificates, String arg1) { } - public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull String arg1) { + public void checkServerTrusted(X509Certificate[] certificates, String arg1) { } } - public static @NotNull SocketAddress getRemoteAddress(@NotNull AsynchronousSocketChannel socketChannel) { + public static SocketAddress getRemoteAddress(AsynchronousSocketChannel socketChannel) { return Utils.uncheckedGet(socketChannel, AsynchronousSocketChannel::getRemoteAddress); } - public static @NotNull SSLContext createSslContext( - @NotNull InputStream keyStoreData, - @NotNull String keyStorePassword) { + public static SSLContext createSslContext( + InputStream keyStoreData, + String keyStorePassword) { return createSslContext("PKCS12", keyStoreData, keyStorePassword, null, null, null); } - public static @NotNull SSLContext createSslContext( - @NotNull String keyStoreType, - @NotNull InputStream keyStoreData, - @NotNull String keyStorePassword, + public static SSLContext createSslContext( + String keyStoreType, + InputStream keyStoreData, + String keyStorePassword, @Nullable String trustStoreType, @Nullable InputStream trustStoreData, @Nullable String trustStorePassword) { @@ -97,7 +96,7 @@ public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull } } - public static @NotNull SSLContext createAllTrustedClientSslContext() { + public static SSLContext createAllTrustedClientSslContext() { try { @@ -118,7 +117,7 @@ public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull * @return the hex dump string. * @since 9.9.0 */ - public static @NotNull String hexDump(@NotNull ByteBuffer buffer) { + public static String hexDump(ByteBuffer buffer) { if (!buffer.hasRemaining()) { return ""; } else { @@ -134,7 +133,7 @@ public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull * @return the hex dump string. * @since 9.9.0 */ - public static @NotNull String hexDump(@NotNull ByteBuffer buffer, @NotNull SSLEngineResult result) { + public static String hexDump(ByteBuffer buffer, SSLEngineResult result) { if (result.bytesProduced() < 1) { return ""; } else { @@ -149,7 +148,7 @@ public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull * @param length the length. * @return the hex dump string. */ - public static @NotNull String hexDump(@NotNull byte[] array, int length) { + public static String hexDump(byte[] array, int length) { return hexDump(array, 0, length); } @@ -161,7 +160,7 @@ public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull * @param length the length. * @return the hex dump string. */ - public static @NotNull String hexDump(@NotNull byte[] array, int offset, int length) { + public static String hexDump(byte[] array, int offset, int length) { var builder = new StringBuilder(); var count = 0; @@ -237,7 +236,7 @@ public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull return builder.toString(); } - private static @NotNull StringBuilder hexDigit(@NotNull StringBuilder builder, byte value) { + private static StringBuilder hexDigit(StringBuilder builder, byte value) { char ch = (char) ((value >> 4) & 0xF); @@ -279,7 +278,7 @@ public static boolean isPortAvailable(int port) { * @param port the port. * @return true if the port is available. */ - public static boolean isPortAvailable(@NotNull String host, int port) { + public static boolean isPortAvailable(String host, int port) { try (var ignored = "*".equals(host) ? new ServerSocket(port) : new ServerSocket(port, 50, InetAddress.getByName(host))) { @@ -303,16 +302,16 @@ public static int getAvailablePort(int port) { .orElse(-1); } - public static @NotNull ByteBuffer enlargePacketBuffer(@NotNull BufferAllocator allocator, @NotNull SSLEngine engine) { + public static ByteBuffer enlargePacketBuffer(BufferAllocator allocator, SSLEngine engine) { return allocator.takeBuffer(engine .getSession() .getPacketBufferSize()); } - public static @NotNull ByteBuffer increaseApplicationBuffer( - @NotNull ByteBuffer current, - @NotNull BufferAllocator allocator, - @NotNull SSLEngine engine) { + public static ByteBuffer increaseApplicationBuffer( + ByteBuffer current, + BufferAllocator allocator, + SSLEngine engine) { var newBuffer = allocator.takeBuffer(engine .getSession() @@ -326,10 +325,10 @@ public static int getAvailablePort(int port) { return newBuffer; } - public static @NotNull ByteBuffer increasePacketBuffer( - @NotNull ByteBuffer current, - @NotNull BufferAllocator allocator, - @NotNull SSLEngine engine) { + public static ByteBuffer increasePacketBuffer( + ByteBuffer current, + BufferAllocator allocator, + SSLEngine engine) { var newBuffer = allocator.takeBuffer(engine .getSession() @@ -343,9 +342,9 @@ public static int getAvailablePort(int port) { return newBuffer; } - public static @NotNull ByteBuffer enlargeApplicationBuffer( - @NotNull BufferAllocator allocator, - @NotNull SSLEngine engine) { + public static ByteBuffer enlargeApplicationBuffer( + BufferAllocator allocator, + SSLEngine engine) { return allocator.takeBuffer(engine .getSession() .getApplicationBufferSize()); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/util/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/util/package-info.java new file mode 100644 index 00000000..e79b5688 --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/util/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.util; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file From 01f14d44cf5ee5542f95c213acd143c8ce26e7ff Mon Sep 17 00:00:00 2001 From: javasabr Date: Fri, 8 Aug 2025 21:23:43 +0200 Subject: [PATCH 5/8] continue global refactoring --- build.gradle | 2 - gradle/libs.versions.toml | 3 - .../classpath/ClassPathScannerFactory.java | 1 - .../rlib/common/compiler/ByteCode.java | 1 - .../rlib/common/compiler/Compiler.java | 13 +- .../rlib/common/compiler/CompilerFactory.java | 2 - .../common/compiler/impl/CompileByteCode.java | 8 +- .../compiler/impl/CompileClassLoader.java | 8 +- .../compiler/impl/CompileJavaFileManager.java | 17 +- .../common/compiler/impl/CompileListener.java | 6 +- .../common/compiler/impl/CompilerImpl.java | 35 ++-- .../common/compiler/impl/JavaFileSource.java | 7 +- .../common/compiler/impl/package-info.java | 4 + .../rlib/common/compiler/package-info.java | 4 + .../concurrent/executor/TaskExecutor.java | 1 - .../common/concurrent/lock/LockFactory.java | 17 +- .../lock/impl/ReentrantARSWLock.java | 1 - .../common/concurrent/task/PeriodicTask.java | 8 +- .../common/concurrent/task/SimpleTask.java | 6 +- .../common/concurrent/task/package-info.java | 4 + .../common/function/BiObjectIntConsumer.java | 2 +- .../common/function/DoubleObjectConsumer.java | 2 +- .../common/function/FiveObjectConsumer.java | 5 +- .../function/FloatBiObjectConsumer.java | 5 +- .../common/function/FloatObjectConsumer.java | 2 +- .../common/function/FourObjectConsumer.java | 5 +- .../rlib/common/function/FunctionInt.java | 2 +- .../rlib/common/function/Functions.java | 13 +- .../common/function/IntBiObjectConsumer.java | 5 +- .../common/function/IntObjectConsumer.java | 2 +- .../common/function/IntObjectPredicate.java | 2 +- .../common/function/LongBiObjectConsumer.java | 5 +- .../common/function/LongObjectConsumer.java | 2 +- .../common/function/LongObjectPredicate.java | 2 +- .../common/function/NotNullBiConsumer.java | 3 +- .../common/function/NotNullBiFunction.java | 3 +- .../common/function/NotNullBiPredicate.java | 3 +- .../rlib/common/function/NotNullConsumer.java | 3 +- .../NotNullFloatBiObjectConsumer.java | 4 +- .../rlib/common/function/NotNullFunction.java | 3 +- .../common/function/NotNullFunctionInt.java | 4 +- .../function/NotNullIntBiObjectConsumer.java | 4 +- .../function/NotNullIntObjectPredicate.java | 4 +- .../function/NotNullLongBiObjectConsumer.java | 4 +- .../function/NotNullLongObjectPredicate.java | 4 +- .../function/NotNullNullableBiFunction.java | 5 +- .../function/NotNullNullableFunction.java | 6 +- .../NotNullNullableTripleFunction.java | 5 +- .../function/NotNullObjectIntPredicate.java | 4 +- .../function/NotNullObjectLongPredicate.java | 4 +- .../common/function/NotNullPredicate.java | 3 +- .../function/NotNullSafeBiConsumer.java | 4 +- .../function/NotNullSafeBiFunction.java | 4 +- .../common/function/NotNullSafeConsumer.java | 4 +- .../common/function/NotNullSafeFactory.java | 4 +- .../common/function/NotNullSafeFunction.java | 4 +- .../common/function/NotNullSafeSupplier.java | 4 +- .../function/NotNullSafeTriFunction.java | 4 +- .../rlib/common/function/NotNullSupplier.java | 3 +- .../function/NotNullTripleConsumer.java | 4 +- .../function/NotNullTriplePredicate.java | 4 +- .../common/function/NullableSupplier.java | 2 +- .../common/function/ObjectFloatConsumer.java | 2 +- .../common/function/ObjectFloatFunction.java | 2 +- .../function/ObjectFloatObjectConsumer.java | 2 +- .../common/function/ObjectIntConsumer.java | 2 +- .../common/function/ObjectIntFunction.java | 2 +- .../function/ObjectIntObjectConsumer.java | 2 +- .../function/ObjectIntObjectFunction.java | 2 +- .../common/function/ObjectLongConsumer.java | 2 +- .../function/ObjectLongObjectConsumer.java | 2 +- .../common/function/ObjectLongPredicate.java | 2 +- .../rlib/common/function/SafeBiConsumer.java | 2 +- .../rlib/common/function/SafeBiFunction.java | 2 +- .../rlib/common/function/SafeConsumer.java | 2 +- .../rlib/common/function/SafeFactory.java | 2 +- .../rlib/common/function/SafeFunction.java | 2 +- .../rlib/common/function/SafeSupplier.java | 2 +- .../rlib/common/function/SafeTriFunction.java | 5 +- .../common/function/SafeTripleConsumer.java | 5 +- .../common/function/SafeTripleFunction.java | 5 +- .../common/function/SixObjectConsumer.java | 11 +- .../rlib/common/function/TripleConsumer.java | 5 +- .../rlib/common/function/TripleFunction.java | 5 +- .../rlib/common/function/TriplePredicate.java | 5 +- .../rlib/common/function/package-info.java | 4 + .../io/impl/RedirectImageOutputStream.java | 1 - .../common/monitoring/MemoryMonitoring.java | 2 - .../common/monitoring/MonitoringManager.java | 3 - .../common/monitoring/RuntimeMonitoring.java | 3 - .../rlib/common/monitoring/package-info.java | 4 + .../plugin/annotation/PluginDescription.java | 1 - .../plugin/exception/PluginException.java | 1 - .../exception/PreloadPluginException.java | 1 - .../ConcurrentAtomicARSWLockReusablePool.java | 1 - .../impl/ConcurrentReentrantRWLockPool.java | 1 - .../pools/impl/ConcurrentStampedLockPool.java | 1 - .../ConcurrentStampedLockReusablePool.java | 1 - .../rlib/common/util/random/FastRandom.java | 3 +- .../rlib/common/util/random/Random.java | 1 - .../common/util/random/RandomFactory.java | 1 - .../rlib/common/util/random/package-info.java | 4 + .../rlib/fx/control/dialog/ControlDialog.java | 28 ++- .../control/dialog/ControlDialogSupport.java | 5 +- .../control/dialog/DefaultControlDialog.java | 17 +- .../fx/control/input/FloatArrayTextField.java | 3 +- .../rlib/fx/control/input/FloatTextField.java | 5 +- .../control/input/IntegerArrayTextField.java | 3 +- .../fx/control/input/IntegerTextField.java | 5 +- .../fx/control/input/NumberTextField.java | 7 +- .../input/ScrollableTypedTextField.java | 7 +- .../rlib/fx/control/input/TypedTextField.java | 13 +- .../rlib/fx/dialog/AbstractPopupDialog.java | 14 +- .../rlib/fx/dialog/SimplePopupDialog.java | 17 +- .../rlib/fx/handler/ControlDragHandler.java | 13 +- .../rlib/fx/handler/ControlResizeHandler.java | 11 +- .../rlib/fx/handler/WindowDragHandler.java | 16 +- .../rlib/fx/handler/WindowResizeHandler.java | 11 +- .../javasabr/rlib/fx/impl/DraggablePanel.java | 9 +- .../rlib/fx/impl/SimpleDraggableElement.java | 9 +- .../rlib/fx/impl/SimpleDroppedPanel.java | 11 +- .../rlib/fx/input/InternalContent.java | 2 +- .../java/javasabr/rlib/fx/util/FXUtils.java | 173 +++++++++--------- .../javasabr/rlib/fx/util/FxControlUtils.java | 65 ++++--- .../java/javasabr/rlib/fx/util/FxUtils.java | 131 +++++++------ .../rlib/fx/util/ObservableUtils.java | 47 +++-- .../converter/FloatArrayStringConverter.java | 2 +- .../IntegerArrayStringConverter.java | 2 +- .../LimitedFloatStringConverter.java | 2 +- .../LimitedIntegerStringConverter.java | 2 +- .../LimitedNumberStringConverter.java | 5 +- .../network/packet/impl/AbstractPacket.java | 1 - .../packet/impl/AbstractWritablePacket.java | 1 - .../packet/impl/SSLWritablePacket.java | 1 - .../testcontainers/FakeSMTPTestContainer.java | 9 +- .../rlib/testcontainers/package-info.java | 4 + 136 files changed, 482 insertions(+), 584 deletions(-) create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/package-info.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/compiler/package-info.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/package-info.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/function/package-info.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/monitoring/package-info.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/util/random/package-info.java create mode 100644 rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/package-info.java diff --git a/build.gradle b/build.gradle index 984af453..15464723 100644 --- a/build.gradle +++ b/build.gradle @@ -27,14 +27,12 @@ subprojects { } dependencies { - compileOnly libs.jetbrains.annotations compileOnly libs.jspecify compileOnly libs.lombok annotationProcessor libs.lombok testImplementation libs.junit.api testCompileOnly libs.lombok - testCompileOnly libs.jetbrains.annotations testCompileOnly libs.jspecify testRuntimeOnly libs.junit.engine testRuntimeOnly libs.junit.platform.launcher diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c16a80ac..5caa7583 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -11,8 +11,6 @@ angus-mail = "2.0.4" testcontainers = "1.21.3" # https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine junit-jupiter = "5.13.4" -# https://mvnrepository.com/artifact/org.jetbrains/annotations -jetbrains-annotations = "26.0.2" # https://mvnrepository.com/artifact/org.projectlombok/lombok lombok = "1.18.38" # https://mvnrepository.com/artifact/org.jspecify/jspecify @@ -22,7 +20,6 @@ junit-platform-launcher = "1.13.4" [libraries] project-reactor-core = { module = "io.projectreactor:reactor-core", version.ref = "project-reactor" } -jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" } lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" } junit-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit-jupiter" } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java index 6d80b2c3..d7fc3634 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/classpath/ClassPathScannerFactory.java @@ -2,7 +2,6 @@ import javasabr.rlib.common.classpath.impl.ClassPathScannerImpl; import javasabr.rlib.common.classpath.impl.ManifestClassPathScannerImpl; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java index 381e478c..399b0bd8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/ByteCode.java @@ -7,7 +7,6 @@ * * @author JavaSaBr */ -@NullMarked public interface ByteCode { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java index 5b02c189..3f10b701 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/Compiler.java @@ -3,15 +3,12 @@ import java.io.File; import java.net.URI; import java.nio.file.Path; -import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NullMarked; /** * The interface to implement a compiler. * * @author JavaSaBr */ -@NullMarked public interface Compiler { /** @@ -30,7 +27,7 @@ public interface Compiler { * @param files the file list. * @return the classes list. */ - Class[] compile(@NotNull File... files); + Class[] compile(File... files); /** * Compile files. @@ -38,7 +35,7 @@ public interface Compiler { * @param paths the file list. * @return the classes list. */ - Class[] compile(@NotNull Path... paths); + Class[] compile(Path... paths); /** * Compile resources. @@ -46,7 +43,7 @@ public interface Compiler { * @param uris the resource list. * @return the classes list. */ - Class[] compile(@NotNull URI... uris); + Class[] compile(URI... uris); /** * Compile all classes from directories. @@ -54,7 +51,7 @@ public interface Compiler { * @param files the directory list. * @return the classes list. */ - Class[] compileDirectory(@NotNull File... files); + Class[] compileDirectory(File... files); /** * Compile all classes from directories. @@ -62,5 +59,5 @@ public interface Compiler { * @param paths the directory list. * @return the classes list. */ - Class[] compileDirectory(@NotNull Path... paths); + Class[] compileDirectory(Path... paths); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java index ba0d258d..794cacc4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/CompilerFactory.java @@ -2,7 +2,6 @@ import javasabr.rlib.common.compiler.impl.CompilerImpl; import javax.tools.ToolProvider; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** @@ -10,7 +9,6 @@ * * @author JavaSaBr */ -@NullMarked public class CompilerFactory { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java index 43466b7f..5edbdf52 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileByteCode.java @@ -6,7 +6,6 @@ import javasabr.rlib.common.compiler.ByteCode; import javasabr.rlib.common.compiler.Compiler; import javax.tools.SimpleJavaFileObject; -import org.jetbrains.annotations.NotNull; /** * The implementation of byte code container. @@ -18,21 +17,20 @@ public class CompileByteCode extends SimpleJavaFileObject implements ByteCode { /** * The stream with byte code. */ - @NotNull private final ByteArrayOutputStream outputStream; - public CompileByteCode(@NotNull final String name) { + public CompileByteCode(final String name) { super(URI.create("byte:///" + name.replace('/', '.') + Compiler.CLASS_EXTENSION), Kind.CLASS); this.outputStream = new ByteArrayOutputStream(); } @Override - public @NotNull byte[] getByteCode() { + public byte[] getByteCode() { return outputStream.toByteArray(); } @Override - public @NotNull OutputStream openOutputStream() { + public OutputStream openOutputStream() { return outputStream; } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java index 7fdacb3f..e880a995 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileClassLoader.java @@ -4,8 +4,7 @@ import javasabr.rlib.common.util.Utils; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayFactory; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of a class loader of compiled classes. @@ -17,7 +16,6 @@ public class CompileClassLoader extends ClassLoader { /** * The list of byte codes of loaded classes. */ - @NotNull private final Array byteCode; public CompileClassLoader() { @@ -29,12 +27,12 @@ public CompileClassLoader() { * * @param byteCode the byte code */ - public synchronized void addByteCode(@NotNull ByteCode byteCode) { + public synchronized void addByteCode(ByteCode byteCode) { this.byteCode.add(byteCode); } @Override - protected synchronized @Nullable Class findClass(@NotNull String name) { + protected synchronized @Nullable Class findClass(String name) { if (byteCode.isEmpty()) { return null; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java index 9e33fd9f..6f9f4b0c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileJavaFileManager.java @@ -7,7 +7,6 @@ import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.StandardJavaFileManager; -import org.jetbrains.annotations.NotNull; /** * The manager to load byte code of classes. @@ -19,18 +18,16 @@ public class CompileJavaFileManager extends ForwardingJavaFileManager classNames; /** * The loaded of compiled classes. */ - @NotNull private final CompileClassLoader loader; public CompileJavaFileManager( - @NotNull final StandardJavaFileManager fileManager, - @NotNull final CompileClassLoader loader) { + final StandardJavaFileManager fileManager, + final CompileClassLoader loader) { super(fileManager); this.loader = loader; this.classNames = ArrayFactory.newArray(String.class); @@ -48,16 +45,16 @@ public void clear() { * * @return the list of names of loaded classes. */ - public @NotNull String[] getClassNames() { + public String[] getClassNames() { return classNames.toArray(new String[classNames.size()]); } @Override public JavaFileObject getJavaFileForOutput( - @NotNull final Location location, - @NotNull final String name, - @NotNull final Kind kind, - @NotNull final FileObject sibling) { + final Location location, + final String name, + final Kind kind, + final FileObject sibling) { final CompileByteCode byteCode = new CompileByteCode(name); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java index d62be3df..f5889aad 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompileListener.java @@ -8,7 +8,6 @@ import javax.tools.Diagnostic; import javax.tools.DiagnosticListener; import javax.tools.JavaFileObject; -import org.jetbrains.annotations.NotNull; /** * The listener of compile events. @@ -20,7 +19,6 @@ public class CompileListener implements DiagnosticListener { /** * The list of diagnostic reports. */ - @NotNull private final Array> diagnostics; public CompileListener() { @@ -39,13 +37,13 @@ public void clear() { * * @return the list of diagnostic reports. */ - public @NotNull Diagnostic[] getDiagnostics() { + public Diagnostic[] getDiagnostics() { final Diagnostic[] array = diagnostics.toArray(Diagnostic.class); return notNull(unsafeCast(array)); } @Override - public void report(@NotNull final Diagnostic diagnostic) { + public void report(final Diagnostic diagnostic) { diagnostics.add(diagnostic); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java index 3b4b2037..1e33566b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/CompilerImpl.java @@ -19,8 +19,7 @@ import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The base implementation of a compiler using a compiler from JDK. @@ -29,37 +28,31 @@ */ public class CompilerImpl implements Compiler { - @NotNull private static final Logger LOGGER = LoggerManager.getLogger(Compiler.class); /** * The constant EMPTY_CLASSES. */ - @NotNull private static final Class[] EMPTY_CLASSES = new Class[0]; /** * The compile listener. */ - @NotNull private final CompileListener listener; /** * The java compiler. */ - @NotNull private final JavaCompiler compiler; /** * The class loader. */ - @NotNull private final CompileClassLoader loader; /** * The java files manager. */ - @NotNull private final CompileJavaFileManager fileManager; /** @@ -79,7 +72,7 @@ public CompilerImpl(final boolean showDiagnostic) { } @Override - public @NotNull Class[] compile(@NotNull final File... files) { + public Class[] compile(final File... files) { if (files.length < 1) { return EMPTY_CLASSES; } @@ -93,7 +86,7 @@ public CompilerImpl(final boolean showDiagnostic) { } @Override - public @NotNull Class[] compile(@NotNull final Path... paths) { + public Class[] compile(final Path... paths) { if (paths.length < 1) { return EMPTY_CLASSES; } @@ -107,7 +100,7 @@ public CompilerImpl(final boolean showDiagnostic) { } @Override - public @NotNull Class[] compile(@NotNull final URI... uris) { + public Class[] compile(final URI... uris) { final Array javaSource = Arrays .stream(uris) @@ -124,9 +117,9 @@ public CompilerImpl(final boolean showDiagnostic) { * @param source the list of sources. * @return the list of compiled classes. */ - protected synchronized @NotNull Class[] compile( + protected synchronized Class[] compile( @Nullable final Iterable options, - @NotNull final Iterable source) { + final Iterable source) { final JavaCompiler compiler = getCompiler(); @@ -176,7 +169,7 @@ public CompilerImpl(final boolean showDiagnostic) { * @param container the container. * @param directory the directory. */ - private void compileDirectory(@NotNull final Array> container, @NotNull final File directory) { + private void compileDirectory(final Array> container, final File directory) { final File[] files = directory.listFiles(); if (files == null || files.length < 1) { @@ -195,7 +188,7 @@ private void compileDirectory(@NotNull final Array> container, @NotNull } @Override - public @NotNull Class[] compileDirectory(@NotNull final File... files) { + public Class[] compileDirectory(final File... files) { final Array> container = ArrayFactory.newArray(Class.class); @@ -217,7 +210,7 @@ private void compileDirectory(@NotNull final Array> container, @NotNull * @param container the container. * @param directory the directory. */ - private void compileDirectory(@NotNull final Array> container, @NotNull final Path directory) { + private void compileDirectory(final Array> container, final Path directory) { try (DirectoryStream stream = Files.newDirectoryStream(directory)) { for (final Path path : stream) { @@ -236,7 +229,7 @@ private void compileDirectory(@NotNull final Array> container, @NotNull } @Override - public @NotNull Class[] compileDirectory(@NotNull Path... paths) { + public Class[] compileDirectory(Path... paths) { final Array> container = ArrayFactory.newArray(Class.class); @@ -258,7 +251,7 @@ private void compileDirectory(@NotNull final Array> container, @NotNull * * @return the java compiler. */ - protected @NotNull JavaCompiler getCompiler() { + protected JavaCompiler getCompiler() { return compiler; } @@ -267,7 +260,7 @@ private void compileDirectory(@NotNull final Array> container, @NotNull * * @return the java files manager. */ - protected @NotNull CompileJavaFileManager getFileManager() { + protected CompileJavaFileManager getFileManager() { return fileManager; } @@ -276,7 +269,7 @@ private void compileDirectory(@NotNull final Array> container, @NotNull * * @return the compile listener. */ - protected @NotNull CompileListener getListener() { + protected CompileListener getListener() { return listener; } @@ -285,7 +278,7 @@ private void compileDirectory(@NotNull final Array> container, @NotNull * * @return the class loader. */ - protected @NotNull CompileClassLoader getLoader() { + protected CompileClassLoader getLoader() { return loader; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java index bd7f1cb9..136c52ce 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/JavaFileSource.java @@ -7,7 +7,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import javax.tools.SimpleJavaFileObject; -import org.jetbrains.annotations.NotNull; /** * The implementation of java class source. @@ -16,15 +15,15 @@ */ public class JavaFileSource extends SimpleJavaFileObject { - protected JavaFileSource(@NotNull final File file) { + protected JavaFileSource(final File file) { super(file.toURI(), Kind.SOURCE); } - protected JavaFileSource(@NotNull final Path path) { + protected JavaFileSource(final Path path) { super(path.toUri(), Kind.SOURCE); } - protected JavaFileSource(@NotNull final URI uri) { + protected JavaFileSource(final URI uri) { super(uri, Kind.SOURCE); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/package-info.java new file mode 100644 index 00000000..8ef935d3 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.compiler.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/compiler/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/compiler/package-info.java new file mode 100644 index 00000000..742de599 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/compiler/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.compiler; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java index b9a16a93..5a0fae4f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/executor/TaskExecutor.java @@ -3,7 +3,6 @@ import java.util.concurrent.Future; import javasabr.rlib.common.concurrent.task.CallableTask; import javasabr.rlib.common.concurrent.task.SimpleTask; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java index 05e83f6d..00bbd9a2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/LockFactory.java @@ -2,8 +2,13 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.StampedLock; +import javasabr.rlib.common.concurrent.lock.impl.AtomicLock; +import javasabr.rlib.common.concurrent.lock.impl.AtomicReadWriteLock; import javasabr.rlib.common.concurrent.lock.impl.ReentrantARSWLock; +import javasabr.rlib.common.concurrent.lock.impl.ReentrantAtomicLock; import org.jspecify.annotations.NullMarked; /** @@ -29,7 +34,7 @@ public static AsyncReadSyncWriteLock newReentrantARSWLock() { * @return the new lock. */ public static StampedLock newStampedLock() { - return new FinalStampedLock(); + return new StampedLock(); } /** @@ -38,7 +43,7 @@ public static StampedLock newStampedLock() { * @return the new lock. */ public static Lock newReentrantLock() { - return new FinalReentrantLock(); + return new ReentrantLock(); } /** @@ -47,7 +52,7 @@ public static Lock newReentrantLock() { * @return the new lock. */ public static AsyncReadSyncWriteLock newAtomicARSWLock() { - return new FinalAtomicReadWriteLock(); + return new AtomicReadWriteLock(); } /** @@ -56,7 +61,7 @@ public static AsyncReadSyncWriteLock newAtomicARSWLock() { * @return the new lock. */ public static Lock newAtomicLock() { - return new FinalAtomicLock(); + return new AtomicLock(); } /** @@ -65,7 +70,7 @@ public static Lock newAtomicLock() { * @return the new lock. */ public static ReadWriteLock newReentrantRWLock() { - return new FinalReentrantReadWriteLock(); + return new ReentrantReadWriteLock(); } /** @@ -74,6 +79,6 @@ public static ReadWriteLock newReentrantRWLock() { * @return the new lock. */ public static Lock newReentrantAtomicLock() { - return new FinalReentrantAtomicLock(); + return new ReentrantAtomicLock(); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java index 0ac18ab6..54eae40b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/lock/impl/ReentrantARSWLock.java @@ -5,7 +5,6 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import javasabr.rlib.common.concurrent.lock.AsyncReadSyncWriteLock; import javasabr.rlib.common.concurrent.lock.LockFactory; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java index f866c5c2..d1b4dce6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/PeriodicTask.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.concurrent.task; -import org.jetbrains.annotations.NotNull; - /** * The interface to implement a periodic tasks. * @@ -11,7 +9,7 @@ public interface PeriodicTask extends CallableTask { @Override - default Boolean call(@NotNull final L local, final long currentTime) { + default Boolean call(final L local, final long currentTime) { if (update(local, currentTime)) { return Boolean.TRUE; } @@ -23,7 +21,7 @@ default Boolean call(@NotNull final L local, final long currentTime) { * * @param local the thread local container. */ - default void onFinish(@NotNull final L local) { + default void onFinish(final L local) { } /** @@ -33,5 +31,5 @@ default void onFinish(@NotNull final L local) { * @param currentTime the current time. * @return true if this task is finished. */ - boolean update(@NotNull L local, long currentTime); + boolean update(L local, long currentTime); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java index 6dbf3b63..99667de0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/SimpleTask.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.concurrent.task; -import org.jetbrains.annotations.NotNull; - /** * The interface to implement a simple task. * @@ -11,7 +9,7 @@ public interface SimpleTask extends CallableTask { @Override - default Void call(@NotNull final L local, final long currentTime) { + default Void call(final L local, final long currentTime) { execute(local, currentTime); return null; } @@ -22,5 +20,5 @@ default Void call(@NotNull final L local, final long currentTime) { * @param local the thread local container. * @param currentTime the current time. */ - void execute(@NotNull L local, long currentTime); + void execute(L local, long currentTime); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/package-info.java new file mode 100644 index 00000000..2f56d368 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/concurrent/task/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.concurrent.task; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java index 7a544e83..f8c16f27 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java index 63ba38f3..ed466073 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/DoubleObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java index 369654ba..10d7b7da 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The consumer with 5 arguments. @@ -12,6 +12,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface FiveObjectConsumer { @@ -24,5 +25,5 @@ public interface FiveObjectConsumer { * @param fourth the fourth * @param five the five */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FO fourth, @Nullable FI five); + void accept(F first, S second, T third, FO fourth, FI five); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java index 67aca096..2f82b8e8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatBiObjectConsumer.java @@ -1,12 +1,13 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface FloatBiObjectConsumer { - void accept(float first, @Nullable S second, @Nullable T third); + void accept(float first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java index 27ea75e0..0370d84f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function to consume float and object. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java index d2b2282c..eba827b6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The consumer with 4 arguments. @@ -11,6 +11,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface FourObjectConsumer { @@ -22,5 +23,5 @@ public interface FourObjectConsumer { * @param third the third * @param fourth the fourth */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FO fourth); + void accept(F first, S second, T third, FO fourth); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java index a6a1be2d..6cdad4d0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/FunctionInt.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java b/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java index 04349775..374c09b1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/Functions.java @@ -2,18 +2,17 @@ import java.util.function.Predicate; import java.util.function.Supplier; -import org.jetbrains.annotations.NotNull; public class Functions { public static class Predicates { - public static @NotNull Predicate isTrue() { + public static Predicate isTrue() { return bool -> bool; } - public static @NotNull Predicate ifTrue(@NotNull Runnable task) { + public static Predicate ifTrue(Runnable task) { return bool -> { @@ -25,7 +24,7 @@ public static class Predicates { }; } - public static @NotNull Predicate throwIfTrue(@NotNull Supplier factory) { + public static Predicate throwIfTrue(Supplier factory) { return bool -> { @@ -37,12 +36,12 @@ public static class Predicates { }; } - public static @NotNull Predicate isFalse() { + public static Predicate isFalse() { return bool -> !bool; } - public static @NotNull Predicate ifFalse(@NotNull Runnable task) { + public static Predicate ifFalse(Runnable task) { return bool -> { @@ -54,7 +53,7 @@ public static class Predicates { }; } - public static @NotNull Predicate throwIfFalse(@NotNull Supplier factory) { + public static Predicate throwIfFalse(Supplier factory) { return bool -> { diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java index 000e633a..c376f780 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/IntBiObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The function. @@ -9,6 +9,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface IntBiObjectConsumer { @@ -19,5 +20,5 @@ public interface IntBiObjectConsumer { * @param second the second * @param third the third */ - void accept(int first, @Nullable S second, @Nullable T third); + void accept(int first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java index 3161ae2c..34126dd2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java index d8467e12..49ab72a6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/IntObjectPredicate.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java index ee1428a6..7fbff7c0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/LongBiObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The function. @@ -9,6 +9,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface LongBiObjectConsumer { @@ -19,5 +20,5 @@ public interface LongBiObjectConsumer { * @param second the second * @param third the third */ - void accept(long first, @Nullable S second, @Nullable T third); + void accept(long first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java index b37ff04c..7f57c686 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java index 2b6626aa..4e5b7bc6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectPredicate.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * ФThe function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java index 6ba4801f..98777de7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiConsumer.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; import java.util.function.BiConsumer; -import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface NotNullBiConsumer extends BiConsumer { @Override - void accept(@NotNull T first, @NotNull U second); + void accept(T first, U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java index c5d27ca0..d4fab15a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; import java.util.function.BiFunction; -import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface NotNullBiFunction extends BiFunction { @Override - @NotNull R apply(@NotNull T first, @NotNull U second); + R apply(T first, U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java index c84df536..027fca77 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; import java.util.function.BiPredicate; -import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface NotNullBiPredicate extends BiPredicate { @Override - boolean test(@NotNull T first, @NotNull U second); + boolean test(T first, U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java index 8e4ddf71..4e12ded8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullConsumer.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; import java.util.function.Consumer; -import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface NotNullConsumer extends Consumer { @Override - void accept(@NotNull T object); + void accept(T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java index cd1a80e8..94072b5a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullFloatBiObjectConsumer extends FloatBiObjectConsumer { @Override - void accept(float first, @NotNull S second, @NotNull T third); + void accept(float first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java index 832f09a6..4783928e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; import java.util.function.Function; -import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface NotNullFunction extends Function { @Override - @NotNull R apply(@NotNull T object); + R apply(T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java index 8b4e9aff..50b9a7d0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java @@ -1,9 +1,7 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - @FunctionalInterface public interface NotNullFunctionInt extends FunctionInt { - int apply(@NotNull T object); + int apply(T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java index 7558da83..055b85ac 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullIntBiObjectConsumer extends IntBiObjectConsumer { @Override - void accept(int first, @NotNull S second, @NotNull T third); + void accept(int first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java index 624173da..da03fb4c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java @@ -1,12 +1,10 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @FunctionalInterface public interface NotNullIntObjectPredicate extends IntObjectPredicate { - boolean test(int first, @NotNull T second); + boolean test(int first, T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java index 4dd5a941..59070ea8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullLongBiObjectConsumer extends LongBiObjectConsumer { @Override - void accept(long first, @NotNull S second, @NotNull T third); + void accept(long first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java index 8d82e019..6d0e778c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java @@ -1,12 +1,10 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @FunctionalInterface public interface NotNullLongObjectPredicate extends LongObjectPredicate { - boolean test(long first, @NotNull T second); + boolean test(long first, T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java index 5e5a4db2..2597fb0d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java @@ -1,12 +1,11 @@ package javasabr.rlib.common.function; import java.util.function.BiFunction; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; @FunctionalInterface public interface NotNullNullableBiFunction extends BiFunction { @Override - @Nullable R apply(@NotNull T first, @NotNull U second); + @Nullable R apply(T first, U second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java index 2de9055f..070fdf9a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java @@ -1,12 +1,12 @@ package javasabr.rlib.common.function; import java.util.function.Function; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; @FunctionalInterface public interface NotNullNullableFunction extends Function { @Override - @Nullable R apply(@NotNull T object); + @Nullable + R apply(T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java index 17a66b66..e762720e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; @FunctionalInterface public interface NotNullNullableTripleFunction extends TripleFunction { @Override - @Nullable R apply(@NotNull F first, @NotNull S second, @NotNull T third); + @Nullable R apply(F first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java index 120eb47a..eacd8586 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullObjectIntPredicate extends ObjectIntPredicate { @Override - boolean test(@NotNull T first, int second); + boolean test(T first, int second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java index 9c29c486..2629b863 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java @@ -1,10 +1,8 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - @FunctionalInterface public interface NotNullObjectLongPredicate extends ObjectLongPredicate { @Override - boolean test(@NotNull T first, long second); + boolean test(T first, long second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java index bb3e23fd..ced6424e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; import java.util.function.Predicate; -import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface NotNullPredicate extends Predicate { @Override - boolean test(@NotNull T object); + boolean test(T object); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java index 8ea4a4fc..605ff62b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiConsumer.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullSafeBiConsumer extends SafeBiConsumer { @Override - void accept(@NotNull F first, @NotNull S second) throws Exception; + void accept(F first, S second) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java index 70c178f5..f355483b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeBiFunction.java @@ -1,10 +1,8 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - @FunctionalInterface public interface NotNullSafeBiFunction extends SafeBiFunction { @Override - @NotNull R apply(@NotNull F first, @NotNull S second) throws Exception; + R apply(F first, S second) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java index 89e8ca48..bbb7760b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeConsumer.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullSafeConsumer extends SafeConsumer { @Override - void accept(@NotNull T argument) throws Exception; + void accept(T argument) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java index b0dc9806..c613fd45 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFactory.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullSafeFactory extends SafeFactory { @Override - @NotNull R get() throws Exception; + R get() throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java index 76098aba..db4f2135 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeFunction.java @@ -1,10 +1,8 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - @FunctionalInterface public interface NotNullSafeFunction extends SafeFunction { @Override - @NotNull R apply(@NotNull F first) throws Exception; + R apply(F first) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java index 779dc298..8e22851b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeSupplier.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullSafeSupplier extends SafeSupplier { @Override - @NotNull T get() throws Exception; + T get() throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java index b5e78742..ef4b91e0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSafeTriFunction.java @@ -1,10 +1,8 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - @FunctionalInterface public interface NotNullSafeTriFunction extends SafeTriFunction { @Override - @NotNull R apply(@NotNull F first, @NotNull S second, @NotNull T third) throws Exception; + R apply(F first, S second, T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java index 5bb6f8a7..d9c144a1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java @@ -1,11 +1,10 @@ package javasabr.rlib.common.function; import java.util.function.Supplier; -import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface NotNullSupplier extends Supplier { @Override - @NotNull T get(); + T get(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java index dbd7aa95..720ec4e1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java @@ -1,7 +1,5 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @@ -9,5 +7,5 @@ public interface NotNullTripleConsumer extends TripleConsumer { @Override - void accept(@NotNull F first, @NotNull S second, @NotNull T third); + void accept(F first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java index 0e71330d..1029aa40 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java @@ -1,12 +1,10 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.NotNull; - /** * @author JavaSaBr */ @FunctionalInterface public interface NotNullTriplePredicate extends TriplePredicate { - boolean test(@NotNull F first, @NotNull S second, @NotNull T third); + boolean test(F first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java index 4c9d90d7..1749584f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/NullableSupplier.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.function; import java.util.function.Supplier; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; @FunctionalInterface public interface NullableSupplier extends Supplier { diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java index 7c8360cb..e69df57c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java index fd50016f..e6b8c206 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java index 482a7c0c..acff3db3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The consumer with 3 arguments. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java index 40df9ffe..7306b275 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java index 31baace9..0fbd2093 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntFunction.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java index 7302bc9d..c8ddcb46 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java index 1d350bc0..e23cad0c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java index 552cd2db..ba62e39b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java index 8aede10c..0b90c249 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java index 1d8e807a..58caee26 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongPredicate.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The function. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java index 2c16bc94..823ed828 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java index 4919d0b2..8f5e95a2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeBiFunction.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; @FunctionalInterface public interface SafeBiFunction { diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java index cf2915c1..ea0ce44f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java index bda4b325..0eb7a2df 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFactory.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java index 7639cf9f..f7fb2a5d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeFunction.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; @FunctionalInterface public interface SafeFunction { diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java index a0dcf98f..57e9013b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeSupplier.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java index 7100bcf2..409125be 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTriFunction.java @@ -1,9 +1,10 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; +@NullUnmarked @FunctionalInterface public interface SafeTriFunction { - @Nullable R apply(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; + R apply(F first, S second, T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java index 3e3e2d1d..9401dd91 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The function. @@ -10,6 +10,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface SafeTripleConsumer { @@ -21,5 +22,5 @@ public interface SafeTripleConsumer { * @param third the third * @throws Exception the exception */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; + void accept(F first, S second, T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java index 98b87998..4ae269ed 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The function. @@ -11,6 +11,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface SafeTripleFunction { @@ -23,5 +24,5 @@ public interface SafeTripleFunction { * @return the r * @throws Exception the exception */ - @Nullable R apply(@Nullable F first, @Nullable S second, @Nullable T third) throws Exception; + R apply(F first, S second, T third) throws Exception; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java index 61a93b1c..974ab1e9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The consumer with 5 arguments. @@ -13,6 +13,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface SixObjectConsumer { @@ -26,11 +27,5 @@ public interface SixObjectConsumer { * @param five the five * @param six the six */ - void accept( - @Nullable F first, - @Nullable S second, - @Nullable T third, - @Nullable FO fourth, - @Nullable FI five, - @Nullable SX six); + void accept(F first, S second, T third, FO fourth, FI five, SX six); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java index 257012ba..3b692bcf 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleConsumer.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The function. @@ -10,6 +10,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface TripleConsumer { @@ -20,5 +21,5 @@ public interface TripleConsumer { * @param second the second * @param third the third */ - void accept(@Nullable F first, @Nullable S second, @Nullable T third); + void accept(F first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java index 1d23b57f..148c9af4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/TripleFunction.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The function. @@ -11,6 +11,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface TripleFunction { @@ -22,5 +23,5 @@ public interface TripleFunction { * @param third the third * @return the r */ - @Nullable R apply(@Nullable F first, @Nullable S second, @Nullable T third); + R apply(F first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java index 345bf7d9..ef962c50 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/TriplePredicate.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.function; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullUnmarked; /** * The function. @@ -10,6 +10,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullUnmarked @FunctionalInterface public interface TriplePredicate { @@ -21,5 +22,5 @@ public interface TriplePredicate { * @param third the third * @return the boolean */ - boolean test(@Nullable F first, @Nullable S second, @Nullable T third); + boolean test(F first, S second, T third); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/function/package-info.java new file mode 100644 index 00000000..61ee1040 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/function/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.function; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java index c2e3b316..16dea634 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/io/impl/RedirectImageOutputStream.java @@ -4,7 +4,6 @@ import java.io.InputStream; import java.io.OutputStream; import javax.imageio.stream.ImageOutputStreamImpl; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java index 983669dc..2d634677 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java @@ -5,7 +5,6 @@ import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.util.List; -import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** @@ -13,7 +12,6 @@ * * @author JavaSaBr */ -@NullMarked public class MemoryMonitoring { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java index 4cf0a8e5..c91e07d9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java @@ -1,13 +1,10 @@ package javasabr.rlib.common.monitoring; -import org.jspecify.annotations.NullMarked; - /** * The class to monitor a state a Java process. * * @author JavaSaBr */ -@NullMarked public final class MonitoringManager { private static final MonitoringManager INSTANCE = new MonitoringManager(); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java index b9deef49..0797a668 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java @@ -7,15 +7,12 @@ import java.lang.management.RuntimeMXBean; import java.text.SimpleDateFormat; import java.util.Date; -import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NullMarked; /** * The class to monitor a runtime state of a java process. * * @author JavaSaBr */ -@NullMarked public class RuntimeMonitoring { private static final ThreadLocal LOCAL_DATE_FORMAT = withInitial(SimpleDateFormat::new); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/package-info.java new file mode 100644 index 00000000..12d6d08d --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.monitoring; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java index 669dcffb..e9b3af2c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/annotation/PluginDescription.java @@ -5,7 +5,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java index 736c3813..ffc9a8b1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PluginException.java @@ -1,6 +1,5 @@ package javasabr.rlib.common.plugin.exception; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java index be484425..e2e998bc 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/plugin/exception/PreloadPluginException.java @@ -1,7 +1,6 @@ package javasabr.rlib.common.plugin.exception; import java.nio.file.Path; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java index 64d502d4..14b1dd1a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentAtomicARSWLockReusablePool.java @@ -5,7 +5,6 @@ import javasabr.rlib.common.util.array.impl.ConcurrentAtomicARSWLockArray; import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java index 84b46ddc..1f69c238 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentReentrantRWLockPool.java @@ -5,7 +5,6 @@ import javasabr.rlib.common.util.array.impl.ConcurrentReentrantRWLockArray; import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java index 1b7be3de..f553fd18 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockPool.java @@ -4,7 +4,6 @@ import javasabr.rlib.common.util.array.ConcurrentArray; import javasabr.rlib.common.util.array.impl.ConcurrentStampedLockArray; import javasabr.rlib.common.util.pools.Pool; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java index 9a5d2401..07000796 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/pools/impl/ConcurrentStampedLockReusablePool.java @@ -5,7 +5,6 @@ import javasabr.rlib.common.util.array.impl.ConcurrentStampedLockArray; import javasabr.rlib.common.util.pools.Reusable; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java index 104b82fe..0f97cd39 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java @@ -1,6 +1,5 @@ package javasabr.rlib.common.util.random; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NullMarked; /** @@ -22,7 +21,7 @@ public FastRandom() { } @Override - public void byteArray(byte @NotNull [] array, int offset, int length) { + public void byteArray(byte [] array, int offset, int length) { length += offset; for (int i = offset; i < length; i++) { array[i] = (byte) nextInt(256); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java index ee44d261..0291bc5b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java @@ -7,7 +7,6 @@ * * @author JavaSaBr */ -@NullMarked public interface Random { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java index 236ec549..3d2c3c42 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java @@ -7,7 +7,6 @@ * * @author JavaSaBr */ -@NullMarked public final class RandomFactory { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/package-info.java new file mode 100644 index 00000000..b426bf69 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/random/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.util.random; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java index 6c570a1b..ef63ba63 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/dialog/ControlDialog.java @@ -13,8 +13,7 @@ import javasabr.rlib.fx.handler.ControlDragHandler; import javasabr.rlib.fx.handler.ControlResizeHandler; import javasabr.rlib.fx.util.FxUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * Implementing a dialog like a control to be inside a main window. @@ -26,19 +25,16 @@ public abstract class ControlDialog { - @NotNull protected final Label titleLabel; - @NotNull protected final Button closeButton; public DefaultControlDialog() { @@ -25,22 +22,22 @@ public DefaultControlDialog() { this.closeButton = createCloseButton(); } - protected @NotNull Button createCloseButton() { + protected Button createCloseButton() { return new Button("X"); } @Override - protected @NotNull GridPane createHeader() { + protected GridPane createHeader() { return new GridPane(); } @Override - protected @NotNull GridPane createContainer() { + protected GridPane createContainer() { return new GridPane(); } @Override - protected @NotNull GridPane createActions() { + protected GridPane createActions() { return new GridPane(); } @@ -62,7 +59,7 @@ protected void configure() { } @Override - protected void fillHeader(@NotNull GridPane header) { + protected void fillHeader(GridPane header) { super.fillHeader(header); titleLabel @@ -78,13 +75,13 @@ protected void fillHeader(@NotNull GridPane header) { } @Override - protected void fillContent(@NotNull GridPane content) { + protected void fillContent(GridPane content) { super.fillContent(content); } @Override - protected void fillActions(@NotNull GridPane actions) { + protected void fillActions(GridPane actions) { super.fillActions(actions); } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java index f0976735..e50a82d4 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatArrayTextField.java @@ -1,7 +1,6 @@ package javasabr.rlib.fx.control.input; import javasabr.rlib.fx.util.converter.FloatArrayStringConverter; -import org.jetbrains.annotations.NotNull; /** * The implementation of a text field control to edit float values. @@ -11,7 +10,7 @@ public final class FloatArrayTextField extends TypedTextField { @Override - protected @NotNull FloatArrayStringConverter createValueConverter() { + protected FloatArrayStringConverter createValueConverter() { return new FloatArrayStringConverter(); } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java index 10f02556..092cbcae 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java @@ -3,7 +3,6 @@ import javafx.scene.input.ScrollEvent; import javasabr.rlib.fx.util.converter.LimitedFloatStringConverter; import javasabr.rlib.fx.util.converter.LimitedNumberStringConverter; -import org.jetbrains.annotations.NotNull; /** * The implementation of a text field control to edit float values. @@ -17,12 +16,12 @@ public FloatTextField() { } @Override - protected @NotNull LimitedNumberStringConverter createValueConverter() { + protected LimitedNumberStringConverter createValueConverter() { return new LimitedFloatStringConverter(); } @Override - protected void scrollValueImpl(@NotNull ScrollEvent event) { + protected void scrollValueImpl(ScrollEvent event) { super.scrollValueImpl(event); var value = getValue(); diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java index 479b30d1..eb67e9dd 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerArrayTextField.java @@ -1,7 +1,6 @@ package javasabr.rlib.fx.control.input; import javasabr.rlib.fx.util.converter.IntegerArrayStringConverter; -import org.jetbrains.annotations.NotNull; /** * The implementation of a text field control to edit integer values. @@ -11,7 +10,7 @@ public final class IntegerArrayTextField extends TypedTextField { @Override - protected @NotNull IntegerArrayStringConverter createValueConverter() { + protected IntegerArrayStringConverter createValueConverter() { return new IntegerArrayStringConverter(); } } \ No newline at end of file diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java index ca9a6970..819b39a0 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/IntegerTextField.java @@ -3,7 +3,6 @@ import javafx.scene.input.ScrollEvent; import javasabr.rlib.fx.util.converter.LimitedIntegerStringConverter; import javasabr.rlib.fx.util.converter.LimitedNumberStringConverter; -import org.jetbrains.annotations.NotNull; /** * The implementation of a text field control to edit integer values. @@ -17,12 +16,12 @@ public IntegerTextField() { } @Override - protected @NotNull LimitedNumberStringConverter createValueConverter() { + protected LimitedNumberStringConverter createValueConverter() { return new LimitedIntegerStringConverter(); } @Override - protected void scrollValueImpl(@NotNull ScrollEvent event) { + protected void scrollValueImpl(ScrollEvent event) { super.scrollValueImpl(event); var value = getValue(); diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java index 6cdf3359..8e3ef474 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/NumberTextField.java @@ -1,8 +1,7 @@ package javasabr.rlib.fx.control.input; import javasabr.rlib.fx.util.converter.LimitedNumberStringConverter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of a text field control to edit float values. @@ -16,13 +15,13 @@ public NumberTextField() { setScrollPower(30); } - public NumberTextField(@NotNull String text) { + public NumberTextField(String text) { super(text); setScrollPower(30); } @Override - protected @NotNull LimitedNumberStringConverter createValueConverter() { + protected LimitedNumberStringConverter createValueConverter() { throw new UnsupportedOperationException(); } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java index 341c5778..7573b9d5 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/ScrollableTypedTextField.java @@ -1,7 +1,6 @@ package javasabr.rlib.fx.control.input; import javafx.scene.input.ScrollEvent; -import org.jetbrains.annotations.NotNull; /** * The implementation of a typed text field control. @@ -19,7 +18,7 @@ public ScrollableTypedTextField() { setOnScroll(this::scrollValue); } - public ScrollableTypedTextField(@NotNull String text) { + public ScrollableTypedTextField(String text) { super(text); setOnScroll(this::scrollValue); } @@ -47,7 +46,7 @@ public float getScrollPower() { * * @param event the scroll event. */ - protected void scrollValue(@NotNull ScrollEvent event) { + protected void scrollValue(ScrollEvent event) { if (event.isControlDown()) { event.consume(); scrollValueImpl(event); @@ -59,6 +58,6 @@ protected void scrollValue(@NotNull ScrollEvent event) { * * @param event the scroll event. */ - protected void scrollValueImpl(@NotNull ScrollEvent event) { + protected void scrollValueImpl(ScrollEvent event) { } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java index e6e92d6a..9aa82eb2 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/TypedTextField.java @@ -7,8 +7,7 @@ import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.util.StringConverter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of a typed text field control. @@ -21,7 +20,7 @@ public TypedTextField() { setTextFormatter(new TextFormatter<>(createValueConverter())); } - public TypedTextField(@NotNull String text) { + public TypedTextField(String text) { super(text); setTextFormatter(new TextFormatter<>(createValueConverter())); } @@ -31,7 +30,7 @@ public TypedTextField(@NotNull String text) { * * @return the new value converter. */ - protected @NotNull StringConverter createValueConverter() { + protected StringConverter createValueConverter() { throw new UnsupportedOperationException(); } @@ -40,7 +39,7 @@ public TypedTextField(@NotNull String text) { * * @param listener the change listener. */ - public void addChangeListener(@NotNull ChangeListener listener) { + public void addChangeListener(ChangeListener listener) { getTypedTextFormatter() .valueProperty() .addListener(listener); @@ -51,7 +50,7 @@ public void addChangeListener(@NotNull ChangeListener listener) { * * @return the typed text formatter. */ - protected @NotNull TextFormatter getTypedTextFormatter() { + protected TextFormatter getTypedTextFormatter() { return unsafeCast(getTextFormatter()); } @@ -60,7 +59,7 @@ public void addChangeListener(@NotNull ChangeListener listener) { * * @return the value property. */ - public @NotNull ReadOnlyObjectProperty valueProperty() { + public ReadOnlyObjectProperty valueProperty() { return getTypedTextFormatter().valueProperty(); } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java index 42216cf3..5debad76 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/AbstractPopupDialog.java @@ -3,8 +3,7 @@ import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.stage.Popup; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of a dialog which is based on a popup. @@ -18,7 +17,6 @@ public abstract class AbstractPopupDialog extends Popup { /** * The dialog's root container. */ - @NotNull private final C container; /** @@ -42,7 +40,7 @@ public AbstractPopupDialog() { * * @return the root container of this dialog. */ - protected abstract @NotNull C createRoot(); + protected abstract C createRoot(); /** * Construct content of this dialog after constructor. @@ -65,7 +63,7 @@ public void postConstruct() { * @param container the root container. * @param size the size. */ - protected void configureSize(@NotNull C container, @NotNull Point2D size) { + protected void configureSize(C container, Point2D size) { } /** @@ -73,7 +71,7 @@ protected void configureSize(@NotNull C container, @NotNull Point2D size) { * * @param root the root. */ - protected void createControls(@NotNull C root) { + protected void createControls(C root) { } /** @@ -81,7 +79,7 @@ protected void createControls(@NotNull C root) { * * @return the content container. */ - protected @NotNull C getContainer() { + protected C getContainer() { return container; } @@ -108,7 +106,7 @@ protected void setOwnerDialog(@Nullable AbstractPopupDialog ownerDialog) { * * @return the dialog size. */ - protected @NotNull Point2D getSize() { + protected Point2D getSize() { return DEFAULT_DIALOG_SIZE; } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java index ee570b6f..6a6be88c 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/dialog/SimplePopupDialog.java @@ -9,17 +9,14 @@ import javasabr.rlib.fx.CssClasses; import javasabr.rlib.fx.handler.WindowDragHandler; import javasabr.rlib.fx.util.FxUtils; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr */ public class SimplePopupDialog extends AbstractPopupDialog { - @NotNull private final Label titleLabel; - @NotNull private final Button closeButton; public SimplePopupDialog() { @@ -32,20 +29,20 @@ public SimplePopupDialog() { } @Override - protected @NotNull VBox createRoot() { + protected VBox createRoot() { var root = new VBox(); FxUtils.addClass(root, CssClasses.SIMPLE_POPUP_DIALOG); return root; } @Override - protected void configureSize(@NotNull VBox container, @NotNull Point2D size) { + protected void configureSize(VBox container, Point2D size) { super.configureSize(container, size); FxUtils.setFixedSize(container, size); } @Override - protected void createControls(@NotNull VBox root) { + protected void createControls(VBox root) { super.createControls(root); var header = new GridPane(); @@ -66,11 +63,11 @@ protected void createControls(@NotNull VBox root) { FxUtils.addChild(root, header, content, actions); } - public void setTitle(@NotNull String title) { + public void setTitle(String title) { this.titleLabel.setText(title); } - protected void fillHeader(@NotNull GridPane container) { + protected void fillHeader(GridPane container) { titleLabel .prefWidthProperty() @@ -85,14 +82,14 @@ protected void fillHeader(@NotNull GridPane container) { container.add(closeButton, 1, 0); } - protected void fillContent(@NotNull GridPane container) { + protected void fillContent(GridPane container) { var textArea = new TextArea(); container.add(textArea, 0, 0); } - protected void fillActions(@NotNull GridPane container) { + protected void fillActions(GridPane container) { var buttonYes = new Button("Yes"); var buttonNo = new Button("No"); diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java index 5567f8ec..63e05838 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlDragHandler.java @@ -6,7 +6,6 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerLevel; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; /** * The implementation of a handler to process windows dragging. @@ -23,20 +22,18 @@ public class ControlDragHandler { * @param draggableNode the node which should be moved. * @param draggableControl the node which should be like a handle. */ - public static void install(@NotNull Node draggableNode, @NotNull Node draggableControl) { + public static void install(Node draggableNode, Node draggableControl) { new ControlDragHandler(draggableNode, draggableControl); } /** * The draggable node. */ - @NotNull private final Node draggableNode; /** * The draggable control. */ - @NotNull private final Node draggableControl; /** @@ -59,7 +56,7 @@ public static void install(@NotNull Node draggableNode, @NotNull Node draggableC */ private double startY; - public ControlDragHandler(@NotNull Node draggableNode, @NotNull Node draggableControl) { + public ControlDragHandler(Node draggableNode, Node draggableControl) { this.draggableNode = draggableNode; this.draggableControl = draggableControl; this.draggableControl.setOnMousePressed(this::processStartDrag); @@ -72,7 +69,7 @@ public ControlDragHandler(@NotNull Node draggableNode, @NotNull Node draggableCo * * @param event the mouse event */ - protected void processMove(@NotNull MouseEvent event) { + protected void processMove(MouseEvent event) { LOGGER.debug(event, ev -> "processMove -> " + ev); @@ -107,7 +104,7 @@ protected void processMove(@NotNull MouseEvent event) { * * @param event the mouse event. */ - protected void processStartDrag(@NotNull MouseEvent event) { + protected void processStartDrag(MouseEvent event) { LOGGER.debug(event, ev -> "processStartDrag -> " + ev); @@ -131,7 +128,7 @@ protected void processStartDrag(@NotNull MouseEvent event) { * * @param event the event */ - protected void processStopDrag(@NotNull MouseEvent event) { + protected void processStopDrag(MouseEvent event) { startX = 0; startY = 0; diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java index b2cbbc6b..c9b74b1f 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/ControlResizeHandler.java @@ -10,7 +10,6 @@ import javafx.scene.Cursor; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; -import org.jetbrains.annotations.NotNull; /** * The implementation of a control resize handler. @@ -24,7 +23,7 @@ public class ControlResizeHandler implements EventHandler { * * @param node the region. */ - public static void install(@NotNull Region node) { + public static void install(Region node) { install(node, 4); } @@ -34,7 +33,7 @@ public static void install(@NotNull Region node) { * @param node the region. * @param borderWidth the border width. */ - public static void install(@NotNull Region node, int borderWidth) { + public static void install(Region node, int borderWidth) { var handler = new ControlResizeHandler(node, borderWidth); @@ -45,10 +44,8 @@ public static void install(@NotNull Region node, int borderWidth) { node.addEventHandler(MOUSE_EXITED_TARGET, handler); } - @NotNull private final Region node; - @NotNull private Cursor cursor; private double startX; @@ -56,7 +53,7 @@ public static void install(@NotNull Region node, int borderWidth) { private int border; - public ControlResizeHandler(@NotNull Region node, int borderWidth) { + public ControlResizeHandler(Region node, int borderWidth) { this.node = node; this.border = borderWidth; this.startX = 0; @@ -65,7 +62,7 @@ public ControlResizeHandler(@NotNull Region node, int borderWidth) { } @Override - public void handle(@NotNull MouseEvent mouseEvent) { + public void handle(MouseEvent mouseEvent) { var eventType = mouseEvent.getEventType(); var eventX = mouseEvent.getX(); diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java index e1582ddb..325c7c74 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowDragHandler.java @@ -7,8 +7,7 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerLevel; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of a handler to process windows dragging. @@ -24,14 +23,13 @@ public class WindowDragHandler { * * @param node the node. */ - public static void install(@NotNull Node node) { + public static void install(Node node) { new WindowDragHandler(node); } /** * The node. */ - @NotNull private final Node node; /** @@ -50,7 +48,7 @@ public static void install(@NotNull Node node) { */ private double startY; - public WindowDragHandler(@NotNull Node node) { + public WindowDragHandler(Node node) { this.node = node; this.node.setOnMousePressed(this::processStartDrag); this.node.setOnMouseDragged(this::processMove); @@ -116,7 +114,7 @@ public void setStartY(double startY) { * * @return the handled node. */ - public @NotNull Node getNode() { + public Node getNode() { return node; } @@ -125,7 +123,7 @@ public void setStartY(double startY) { * * @param event the event */ - protected void processMove(@NotNull MouseEvent event) { + protected void processMove(MouseEvent event) { LOGGER.debug(event, ev -> "processMove -> " + ev); @@ -166,7 +164,7 @@ protected void processMove(@NotNull MouseEvent event) { * * @param event the event. */ - protected void processStartDrag(@NotNull MouseEvent event) { + protected void processStartDrag(MouseEvent event) { LOGGER.debug(event, ev -> "processStartDrag -> " + ev); @@ -191,7 +189,7 @@ protected void processStartDrag(@NotNull MouseEvent event) { * * @param event the event */ - protected void processStopDrag(@NotNull MouseEvent event) { + protected void processStopDrag(MouseEvent event) { LOGGER.debug(event, ev -> "processStopDrag -> " + ev); setStartX(0); setStartY(0); diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java index cb2b0807..4e98b54d 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/handler/WindowResizeHandler.java @@ -11,7 +11,6 @@ import javafx.scene.Node; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; -import org.jetbrains.annotations.NotNull; /** * The implementation of a windows resize handler. @@ -26,7 +25,7 @@ public class WindowResizeHandler implements EventHandler { * @param stage the stage. * @param nodes the nodes. */ - public static void install(@NotNull Stage stage, @NotNull Node... nodes) { + public static void install(Stage stage, Node... nodes) { var handler = new WindowResizeHandler(stage); var scene = stage.getScene(); @@ -43,7 +42,7 @@ public static void install(@NotNull Stage stage, @NotNull Node... nodes) { } } - private static void addHandler(@NotNull Node node, @NotNull EventHandler listener) { + private static void addHandler(Node node, EventHandler listener) { node.addEventHandler(MOUSE_MOVED, listener); node.addEventHandler(MOUSE_PRESSED, listener); node.addEventHandler(MOUSE_DRAGGED, listener); @@ -51,10 +50,8 @@ private static void addHandler(@NotNull Node node, @NotNull EventHandler children = parent.getChildren(); children.add(node); } @@ -397,7 +396,7 @@ public static void addToPane(@NotNull final Node node, @NotNull final Pane paren * @param second the second node. * @param parent the parent. */ - public static void addToPane(@NotNull final Node first, @NotNull final Node second, @NotNull final Pane parent) { + public static void addToPane(final Node first, final Node second, final Pane parent) { final ObservableList children = parent.getChildren(); children.add(first); children.add(second); @@ -412,10 +411,10 @@ public static void addToPane(@NotNull final Node first, @NotNull final Node seco * @param parent the parent. */ public static void addToPane( - @NotNull final Node first, - @NotNull final Node second, - @NotNull final Node third, - @NotNull final Pane parent) { + final Node first, + final Node second, + final Node third, + final Pane parent) { final ObservableList children = parent.getChildren(); children.add(first); children.add(second); @@ -432,11 +431,11 @@ public static void addToPane( * @param parent the parent. */ public static void addToPane( - @NotNull final Node first, - @NotNull final Node second, - @NotNull final Node third, - @NotNull final Node fourth, - @NotNull final Pane parent) { + final Node first, + final Node second, + final Node third, + final Node fourth, + final Pane parent) { final ObservableList children = parent.getChildren(); children.add(first); children.add(second); @@ -451,8 +450,8 @@ public static void addToPane( * @param heightProperty the height property. */ public static void bindFixedHeight( - @NotNull final Region region, - @NotNull final ReadOnlyProperty heightProperty) { + final Region region, + final ReadOnlyProperty heightProperty) { region .minHeightProperty() .bind(heightProperty); @@ -468,8 +467,8 @@ public static void bindFixedHeight( * @param height the height value. */ public static void bindFixedHeight( - @NotNull final Region region, - @NotNull final ObservableValue height) { + final Region region, + final ObservableValue height) { region .minHeightProperty() .bind(height); @@ -486,9 +485,9 @@ public static void bindFixedHeight( * @param heightProperty the height property. */ public static void bindFixedSize( - @NotNull final Region region, - @NotNull final ReadOnlyProperty widthProperty, - @NotNull final ReadOnlyProperty heightProperty) { + final Region region, + final ReadOnlyProperty widthProperty, + final ReadOnlyProperty heightProperty) { region .minWidthProperty() .bind(widthProperty); @@ -511,9 +510,9 @@ public static void bindFixedSize( * @param height the height value. */ public static void bindFixedSize( - @NotNull final Region region, - @NotNull final ObservableValue width, - @NotNull final ObservableValue height) { + final Region region, + final ObservableValue width, + final ObservableValue height) { region .minWidthProperty() .bind(width); @@ -535,8 +534,8 @@ public static void bindFixedSize( * @param widthProperty the height property. */ public static void bindFixedWidth( - @NotNull final Region region, - @NotNull final ReadOnlyProperty widthProperty) { + final Region region, + final ReadOnlyProperty widthProperty) { region .minWidthProperty() .bind(widthProperty); @@ -552,8 +551,8 @@ public static void bindFixedWidth( * @param width the height value. */ public static void bindFixedWidth( - @NotNull final Region region, - @NotNull final ObservableValue width) { + final Region region, + final ObservableValue width) { region .minWidthProperty() .bind(width); @@ -568,7 +567,7 @@ public static void bindFixedWidth( * @param node the node. * @param parent the parent. */ - public static void removeFromParent(@NotNull final Node node, @NotNull final Pane parent) { + public static void removeFromParent(final Node node, final Pane parent) { final ObservableList children = parent.getChildren(); children.remove(node); } @@ -579,7 +578,7 @@ public static void removeFromParent(@NotNull final Node node, @NotNull final Pan * @param region the region. * @param height the height. */ - public static void setFixedHeight(@NotNull final Region region, final double height) { + public static void setFixedHeight(final Region region, final double height) { region.setMaxHeight(height); region.setMinHeight(height); } @@ -591,7 +590,7 @@ public static void setFixedHeight(@NotNull final Region region, final double hei * @param width the width. * @param height the height. */ - public static void setFixedSize(@NotNull final Region region, final double width, final double height) { + public static void setFixedSize(final Region region, final double width, final double height) { region.setMaxHeight(height); region.setMinHeight(height); region.setMaxWidth(width); @@ -604,7 +603,7 @@ public static void setFixedSize(@NotNull final Region region, final double width * @param region the region. * @param size the size. */ - public static void setFixedSize(@NotNull final Region region, @NotNull final Point size) { + public static void setFixedSize(final Region region, final Point size) { region.setMaxHeight(size.getY()); region.setMinHeight(size.getY()); region.setMaxWidth(size.getX()); @@ -617,7 +616,7 @@ public static void setFixedSize(@NotNull final Region region, @NotNull final Poi * @param region the region. * @param width the width. */ - public static void setFixedWidth(@NotNull final Region region, final double width) { + public static void setFixedWidth(final Region region, final double width) { region.setMaxWidth(width); region.setMinWidth(width); } @@ -628,7 +627,7 @@ public static void setFixedWidth(@NotNull final Region region, final double widt * @param node the node. * @param handler the handler. */ - public static void applyToChildren(@NotNull final Parent node, @NotNull final Consumer handler) { + public static void applyToChildren(final Parent node, final Consumer handler) { node .getChildrenUnmodifiable() .forEach(handler); diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java index 0b5a58c6..0cd84ca1 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxControlUtils.java @@ -18,7 +18,6 @@ import javafx.scene.paint.Color; import javasabr.rlib.fx.control.input.TypedTextField; import javasabr.rlib.fx.util.ObservableUtils.ChangeEventAppender; -import org.jetbrains.annotations.NotNull; /** * The utility class. @@ -34,7 +33,7 @@ public class FxControlUtils { * @param handler the handler. * @return the change event appender. */ - public static ChangeEventAppender onTextChange(@NotNull TextInputControl control, @NotNull Runnable handler) { + public static ChangeEventAppender onTextChange(TextInputControl control, Runnable handler) { return ObservableUtils.onChange(control.textProperty(), handler); } @@ -46,8 +45,8 @@ public static ChangeEventAppender onTextChange(@NotNull TextInputControl * @return the change event appender. */ public static ChangeEventAppender onTextChange( - @NotNull TextInputControl control, - @NotNull Consumer handler) { + TextInputControl control, + Consumer handler) { return ObservableUtils.onChange(control.textProperty(), handler); } @@ -58,7 +57,7 @@ public static ChangeEventAppender onTextChange( * @param handler the handler. * @return the change event appender. */ - public static ChangeEventAppender onSelectedChange(@NotNull CheckBox control, @NotNull Runnable handler) { + public static ChangeEventAppender onSelectedChange(CheckBox control, Runnable handler) { return ObservableUtils.onChange(control.selectedProperty(), handler); } @@ -70,8 +69,8 @@ public static ChangeEventAppender onSelectedChange(@NotNull CheckBox co * @return the change event appender. */ public static ChangeEventAppender onSelectedChange( - @NotNull CheckBox control, - @NotNull Consumer handler) { + CheckBox control, + Consumer handler) { return ObservableUtils.onChange(control.selectedProperty(), handler); } @@ -83,8 +82,8 @@ public static ChangeEventAppender onSelectedChange( * @return the change event appender. */ public static ChangeEventAppender onSelectedChange( - @NotNull ToggleButton control, - @NotNull Runnable handler) { + ToggleButton control, + Runnable handler) { return ObservableUtils.onChange(control.selectedProperty(), handler); } @@ -96,8 +95,8 @@ public static ChangeEventAppender onSelectedChange( * @return the change event appender. */ public static ChangeEventAppender onSelectedChange( - @NotNull ToggleButton control, - @NotNull Consumer handler) { + ToggleButton control, + Consumer handler) { return ObservableUtils.onChange(control.selectedProperty(), handler); } @@ -109,8 +108,8 @@ public static ChangeEventAppender onSelectedChange( * @return the change event appender. */ public static ChangeEventAppender onColorChange( - @NotNull ColorPicker control, - @NotNull Consumer handler) { + ColorPicker control, + Consumer handler) { return ObservableUtils.onChange(control.valueProperty(), handler); } @@ -121,7 +120,7 @@ public static ChangeEventAppender onColorChange( * @param handler the handler. * @return the change event appender. */ - public static ChangeEventAppender onColorChange(@NotNull ColorPicker control, @NotNull Runnable handler) { + public static ChangeEventAppender onColorChange(ColorPicker control, Runnable handler) { return ObservableUtils.onChange(control.valueProperty(), handler); } @@ -134,8 +133,8 @@ public static ChangeEventAppender onColorChange(@NotNull ColorPicker cont * @return the change event appender. */ public static ChangeEventAppender onValueChange( - @NotNull TypedTextField control, - @NotNull Consumer handler) { + TypedTextField control, + Consumer handler) { return ObservableUtils.onChange(control.valueProperty(), handler); } @@ -148,8 +147,8 @@ public static ChangeEventAppender onValueChange( * @return the change event appender. */ public static ChangeEventAppender onValueChange( - @NotNull TypedTextField control, - @NotNull Runnable handler) { + TypedTextField control, + Runnable handler) { return ObservableUtils.onChange(control.valueProperty(), handler); } @@ -160,7 +159,7 @@ public static ChangeEventAppender onValueChange( * @param handler the handler. * @return the change event appender. */ - public static ChangeEventAppender onFocusChange(@NotNull Node control, @NotNull Consumer handler) { + public static ChangeEventAppender onFocusChange(Node control, Consumer handler) { return ObservableUtils.onChange(control.focusedProperty(), handler); } @@ -173,8 +172,8 @@ public static ChangeEventAppender onFocusChange(@NotNull Node control, * @return the change event appender. */ public static ChangeEventAppender onSelectedItemChange( - @NotNull ComboBox control, - @NotNull Runnable handler) { + ComboBox control, + Runnable handler) { return ObservableUtils.onChange(control.valueProperty(), handler); } @@ -187,8 +186,8 @@ public static ChangeEventAppender onSelectedItemChange( * @return the change event appender. */ public static ChangeEventAppender onSelectedItemChange( - @NotNull ComboBox control, - @NotNull Consumer handler) { + ComboBox control, + Consumer handler) { return ObservableUtils.onChange(control.valueProperty(), handler); } @@ -201,8 +200,8 @@ public static ChangeEventAppender onSelectedItemChange( * @return the change event appender. */ public static ChangeEventAppender onSelectedItemChange( - @NotNull ListView control, - @NotNull Consumer handler) { + ListView control, + Consumer handler) { var selectionModel = control.getSelectionModel(); return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); } @@ -216,8 +215,8 @@ public static ChangeEventAppender onSelectedItemChange( * @return the change event appender. */ public static ChangeEventAppender> onSelectedItemChange( - @NotNull TreeView control, - @NotNull Runnable handler) { + TreeView control, + Runnable handler) { var selectionModel = control.getSelectionModel(); return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); } @@ -231,8 +230,8 @@ public static ChangeEventAppender> onSelectedItemChange( * @return the change event appender. */ public static ChangeEventAppender> onSelectedItemChange( - @NotNull TreeView control, - @NotNull Consumer> handler) { + TreeView control, + Consumer> handler) { var selectionModel = control.getSelectionModel(); return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); } @@ -243,7 +242,7 @@ public static ChangeEventAppender> onSelectedItemChange( * @param control the button control. * @param handler the handler. */ - public static void onAction(@NotNull ButtonBase control, @NotNull Runnable handler) { + public static void onAction(ButtonBase control, Runnable handler) { control.addEventHandler(ActionEvent.ACTION, event -> handler.run()); } @@ -254,7 +253,7 @@ public static void onAction(@NotNull ButtonBase control, @NotNull Runnable handl * @param handler the handler. * @return the change event appender. */ - public static ChangeEventAppender onSelectedTabChange(@NotNull TabPane control, @NotNull Consumer handler) { + public static ChangeEventAppender onSelectedTabChange(TabPane control, Consumer handler) { var selectionModel = control.getSelectionModel(); return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); } @@ -267,8 +266,8 @@ public static ChangeEventAppender onSelectedTabChange(@NotNull TabPane cont * @return the change event appender. */ public static ChangeEventAppender onSelectedTabChange( - @NotNull TabPane control, - @NotNull BiConsumer handler) { + TabPane control, + BiConsumer handler) { var selectionModel = control.getSelectionModel(); return ObservableUtils.onChange(selectionModel.selectedItemProperty(), handler); } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java index 97752ea9..78a500ac 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/FxUtils.java @@ -9,7 +9,6 @@ import javafx.scene.Node; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; -import org.jetbrains.annotations.NotNull; /** * The utility class. @@ -27,7 +26,7 @@ public static class CssClassAppender { * @param className the css class. * @return the css class appender. */ - public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String className) { + public CssClassAppender addClass(Styleable styleable, String className) { styleable .getStyleClass() .add(className); @@ -42,10 +41,10 @@ public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String c * @param className the css class. * @return the css class appender. */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String className) { + public CssClassAppender addClass( + Styleable first, + Styleable second, + String className) { first .getStyleClass() .add(className); @@ -64,11 +63,11 @@ public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String c * @param className the css class. * @return the css class appender. */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String className) { + public CssClassAppender addClass( + Styleable first, + Styleable second, + Styleable third, + String className) { first .getStyleClass() .add(className); @@ -88,7 +87,7 @@ public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String c * @param classNames the css classes. * @return the css class appender. */ - public @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String... classNames) { + public CssClassAppender addClass(Styleable styleable, String... classNames) { styleable .getStyleClass() .addAll(classNames); @@ -103,10 +102,10 @@ public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String c * @param classNames the css classes. * @return the css class appender. */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String... classNames) { + public CssClassAppender addClass( + Styleable first, + Styleable second, + String... classNames) { first .getStyleClass() .addAll(classNames); @@ -125,11 +124,11 @@ public CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String c * @param classNames the css classes. * @return the css class appender. */ - public @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String... classNames) { + public CssClassAppender addClass( + Styleable first, + Styleable second, + Styleable third, + String... classNames) { first .getStyleClass() .addAll(classNames); @@ -152,7 +151,7 @@ public static class ChildrenAppender { * @param node the node. * @return the child appender. */ - public @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node node) { + public ChildrenAppender addChild(Pane parent, Node node) { parent .getChildren() .add(node); @@ -166,7 +165,7 @@ public static class ChildrenAppender { * @param node the node. * @return the child appender. */ - public @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node node) { + public ChildrenAppender addChild(Group parent, Node node) { parent .getChildren() .add(node); @@ -180,7 +179,7 @@ public static class ChildrenAppender { * @param nodes the nodes. * @return the child appender. */ - public @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node... nodes) { + public ChildrenAppender addChild(Pane parent, Node... nodes) { parent .getChildren() .addAll(nodes); @@ -194,7 +193,7 @@ public static class ChildrenAppender { * @param nodes the nodes. * @return the child appender. */ - public @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node... nodes) { + public ChildrenAppender addChild(Group parent, Node... nodes) { parent .getChildren() .addAll(nodes); @@ -211,7 +210,7 @@ public static class ChildrenRemover { * @param node the node. * @return the child appender. */ - public @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node node) { + public ChildrenRemover removeChild(Pane parent, Node node) { parent .getChildren() .remove(node); @@ -225,7 +224,7 @@ public static class ChildrenRemover { * @param node the node. * @return the child appender. */ - public @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node node) { + public ChildrenRemover removeChild(Group parent, Node node) { parent .getChildren() .remove(node); @@ -239,7 +238,7 @@ public static class ChildrenRemover { * @param nodes the nodes. * @return the child appender. */ - public @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node... nodes) { + public ChildrenRemover removeChild(Pane parent, Node... nodes) { parent .getChildren() .removeAll(nodes); @@ -253,7 +252,7 @@ public static class ChildrenRemover { * @param nodes the nodes. * @return the child appender. */ - public @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node... nodes) { + public ChildrenRemover removeChild(Group parent, Node... nodes) { parent .getChildren() .removeAll(nodes); @@ -272,7 +271,7 @@ public static class ChildrenRemover { * @param className the css class. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String className) { + public static CssClassAppender addClass(Styleable styleable, String className) { styleable .getStyleClass() .add(className); @@ -287,10 +286,10 @@ public static class ChildrenRemover { * @param className the css class. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String className) { + public static CssClassAppender addClass( + Styleable first, + Styleable second, + String className) { first .getStyleClass() .add(className); @@ -309,11 +308,11 @@ public static class ChildrenRemover { * @param className the css class. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String className) { + public static CssClassAppender addClass( + Styleable first, + Styleable second, + Styleable third, + String className) { first .getStyleClass() .add(className); @@ -333,7 +332,7 @@ public static class ChildrenRemover { * @param classNames the css classes. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass(@NotNull Styleable styleable, @NotNull String... classNames) { + public static CssClassAppender addClass(Styleable styleable, String... classNames) { styleable .getStyleClass() .addAll(classNames); @@ -348,10 +347,10 @@ public static class ChildrenRemover { * @param classNames the css classes. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull String... classNames) { + public static CssClassAppender addClass( + Styleable first, + Styleable second, + String... classNames) { first .getStyleClass() .addAll(classNames); @@ -370,11 +369,11 @@ public static class ChildrenRemover { * @param classNames the css classes. * @return the css class appender. */ - public static @NotNull CssClassAppender addClass( - @NotNull Styleable first, - @NotNull Styleable second, - @NotNull Styleable third, - @NotNull String... classNames) { + public static CssClassAppender addClass( + Styleable first, + Styleable second, + Styleable third, + String... classNames) { first .getStyleClass() .addAll(classNames); @@ -394,7 +393,7 @@ public static class ChildrenRemover { * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node node) { + public static ChildrenAppender addChild(Pane parent, Node node) { parent .getChildren() .add(node); @@ -408,7 +407,7 @@ public static class ChildrenRemover { * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node node) { + public static ChildrenAppender addChild(Group parent, Node node) { parent .getChildren() .add(node); @@ -422,7 +421,7 @@ public static class ChildrenRemover { * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Pane parent, @NotNull Node... nodes) { + public static ChildrenAppender addChild(Pane parent, Node... nodes) { parent .getChildren() .addAll(nodes); @@ -436,7 +435,7 @@ public static class ChildrenRemover { * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenAppender addChild(@NotNull Group parent, @NotNull Node... nodes) { + public static ChildrenAppender addChild(Group parent, Node... nodes) { parent .getChildren() .addAll(nodes); @@ -450,7 +449,7 @@ public static class ChildrenRemover { * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node node) { + public static ChildrenRemover removeChild(Pane parent, Node node) { parent .getChildren() .remove(node); @@ -464,7 +463,7 @@ public static class ChildrenRemover { * @param node the node. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node node) { + public static ChildrenRemover removeChild(Group parent, Node node) { parent .getChildren() .remove(node); @@ -478,7 +477,7 @@ public static class ChildrenRemover { * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Pane parent, @NotNull Node... nodes) { + public static ChildrenRemover removeChild(Pane parent, Node... nodes) { parent .getChildren() .removeAll(nodes); @@ -492,7 +491,7 @@ public static class ChildrenRemover { * @param nodes the nodes. * @return the child appender. */ - public static @NotNull ChildrenRemover removeChild(@NotNull Group parent, @NotNull Node... nodes) { + public static ChildrenRemover removeChild(Group parent, Node... nodes) { parent .getChildren() .removeAll(nodes); @@ -506,7 +505,7 @@ public static class ChildrenRemover { * @param the region's type. * @return the region. */ - public static T resetPrefWidth(@NotNull T region) { + public static T resetPrefWidth(T region) { region .prefWidthProperty() .unbind(); @@ -521,7 +520,7 @@ public static T resetPrefWidth(@NotNull T region) { * @param region the region. * @return the region. */ - public static T resetMinMaxWidth(@NotNull T region) { + public static T resetMinMaxWidth(T region) { region .maxWidthProperty() .unbind(); @@ -542,8 +541,8 @@ public static T resetMinMaxWidth(@NotNull T region) { * @return the region. */ public static T rebindPrefWidth( - @NotNull T region, - @NotNull ObservableValue value) { + T region, + ObservableValue value) { var width = region.prefWidthProperty(); @@ -561,7 +560,7 @@ public static T rebindPrefWidth( * * @param node the node. */ - public static void addDebugBackgroundColor(@NotNull Node node) { + public static void addDebugBackgroundColor(Node node) { var random = ThreadLocalRandom.current(); var color = "rgb(" + random.nextInt(255) + "," + random.nextInt(255) + ", " + random.nextInt(255) + ")"; @@ -574,7 +573,7 @@ public static void addDebugBackgroundColor(@NotNull Node node) { * * @param node the node. */ - public static void addDebugBorderTo(@NotNull Node node) { + public static void addDebugBorderTo(Node node) { node.setStyle("-fx-border-color: red; -fx-border-width: 3px;"); } @@ -585,7 +584,7 @@ public static void addDebugBorderTo(@NotNull Node node) { * @param width the width. * @param height the height. */ - public static void setFixedSize(@NotNull Region region, double width, double height) { + public static void setFixedSize(Region region, double width, double height) { region.setMaxHeight(height); region.setMinHeight(height); region.setMaxWidth(width); @@ -598,7 +597,7 @@ public static void setFixedSize(@NotNull Region region, double width, double hei * @param region the region. * @param size the size. */ - public static void setFixedSize(@NotNull Region region, @NotNull Point size) { + public static void setFixedSize(Region region, Point size) { setFixedSize(region, size.getX(), size.getY()); } @@ -608,7 +607,7 @@ public static void setFixedSize(@NotNull Region region, @NotNull Point size) { * @param region the region. * @param size the size. */ - public static void setFixedSize(@NotNull Region region, @NotNull Point2D size) { + public static void setFixedSize(Region region, Point2D size) { setFixedSize(region, size.getX(), size.getY()); } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java index 72c6962f..95646acc 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/ObservableUtils.java @@ -7,7 +7,6 @@ import java.util.function.Consumer; import java.util.function.Predicate; import javafx.beans.value.ObservableValue; -import org.jetbrains.annotations.NotNull; /** * The utility class. @@ -30,7 +29,7 @@ public void complete() { * @param action the action on changes. * @return the change event appender. */ - public ChangeEventAppender onChange(@NotNull Runnable action) { + public ChangeEventAppender onChange(Runnable action) { value.addListener((observable, oldValue, newValue) -> action.run()); return this; } @@ -42,7 +41,7 @@ public ChangeEventAppender onChange(@NotNull Runnable action) { * @param action the action on changes. * @return the change event appender. */ - public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNull Runnable action) { + public ChangeEventAppender onChangeIf(Predicate predicate, Runnable action) { value.addListener((observable, oldValue, newValue) -> { if (predicate.test(newValue)) { @@ -59,7 +58,7 @@ public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNu * @param consumer the consumer to handle new values. * @return the change event appender. */ - public ChangeEventAppender onChange(@NotNull Consumer consumer) { + public ChangeEventAppender onChange(Consumer consumer) { value.addListener((observable, oldValue, newValue) -> consumer.accept(newValue)); return this; } @@ -71,7 +70,7 @@ public ChangeEventAppender onChange(@NotNull Consumer consumer) { * @param consumer the consumer to handle new values. * @return the change event appender. */ - public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNull Consumer consumer) { + public ChangeEventAppender onChangeIf(Predicate predicate, Consumer consumer) { value.addListener((observable, oldValue, newValue) -> { if (predicate.test(newValue)) { @@ -88,7 +87,7 @@ public ChangeEventAppender onChangeIf(@NotNull Predicate predicate, @NotNu * @param consumer the consumer to handle new values. * @return the change event appender. */ - public ChangeEventAppender onChange(@NotNull BiConsumer consumer) { + public ChangeEventAppender onChange(BiConsumer consumer) { value.addListener((observable, oldValue, newValue) -> consumer.accept(oldValue, newValue)); return this; } @@ -100,7 +99,7 @@ public ChangeEventAppender onChange(@NotNull BiConsumer consumer) { * @param consumer the consumer to handle new values. * @return the change event appender. */ - public ChangeEventAppender onChangeIf(@NotNull BiPredicate predicate, @NotNull BiConsumer consumer) { + public ChangeEventAppender onChangeIf(BiPredicate predicate, BiConsumer consumer) { value.addListener((observable, oldValue, newValue) -> { if (predicate.test(oldValue, newValue)) { @@ -120,7 +119,7 @@ public void close() throws Exception { private static final ThreadLocal CHANGE_EVENT_APPENDER = ThreadLocal.withInitial( ChangeEventAppender::new); - private static @NotNull ChangeEventAppender getAppender(@NotNull ObservableValue value) { + private static ChangeEventAppender getAppender(ObservableValue value) { ChangeEventAppender appender = unsafeCast(CHANGE_EVENT_APPENDER.get()); appender.value = value; @@ -136,9 +135,9 @@ public void close() throws Exception { * @param the value type. * @return the change event appender. */ - public static @NotNull ChangeEventAppender onChange( - @NotNull ObservableValue value, - @NotNull Runnable action) { + public static ChangeEventAppender onChange( + ObservableValue value, + Runnable action) { value.addListener((observable, oldValue, newValue) -> action.run()); return getAppender(value); } @@ -153,9 +152,9 @@ public void close() throws Exception { * @return the change event appender. */ public static ChangeEventAppender onChangeIf( - @NotNull ObservableValue value, - @NotNull Predicate predicate, - @NotNull Runnable action) { + ObservableValue value, + Predicate predicate, + Runnable action) { value.addListener((observable, oldValue, newValue) -> { if (predicate.test(newValue)) { @@ -174,7 +173,7 @@ public static ChangeEventAppender onChangeIf( * @param the value type. * @return the change event appender. */ - public static ChangeEventAppender onChange(@NotNull ObservableValue value, @NotNull Consumer consumer) { + public static ChangeEventAppender onChange(ObservableValue value, Consumer consumer) { value.addListener((observable, oldValue, newValue) -> consumer.accept(newValue)); return getAppender(value); } @@ -189,9 +188,9 @@ public static ChangeEventAppender onChange(@NotNull ObservableValue va * @return the change event appender. */ public static ChangeEventAppender onChangeIf( - @NotNull ObservableValue value, - @NotNull Predicate predicate, - @NotNull Consumer consumer) { + ObservableValue value, + Predicate predicate, + Consumer consumer) { value.addListener((observable, oldValue, newValue) -> { if (predicate.test(newValue)) { @@ -209,7 +208,7 @@ public static ChangeEventAppender onChangeIf( * @param the value type. * @return the change event appender. */ - public static ChangeEventAppender onChanges(@NotNull ObservableValue value) { + public static ChangeEventAppender onChanges(ObservableValue value) { return getAppender(value); } @@ -222,8 +221,8 @@ public static ChangeEventAppender onChanges(@NotNull ObservableValue v * @return the change event appender. */ public static ChangeEventAppender onChange( - @NotNull ObservableValue value, - @NotNull BiConsumer consumer) { + ObservableValue value, + BiConsumer consumer) { value.addListener((observable, oldValue, newValue) -> consumer.accept(oldValue, newValue)); return getAppender(value); } @@ -238,9 +237,9 @@ public static ChangeEventAppender onChange( * @return the change event appender. */ public static ChangeEventAppender onChangeIf( - @NotNull ObservableValue value, - @NotNull BiPredicate predicate, - @NotNull BiConsumer consumer) { + ObservableValue value, + BiPredicate predicate, + BiConsumer consumer) { value.addListener((observable, oldValue, newValue) -> { if (predicate.test(oldValue, newValue)) { diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java index 16600baf..6f68b378 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/FloatArrayStringConverter.java @@ -3,7 +3,7 @@ import javafx.util.StringConverter; import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.StringUtils; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of limited float string converter. diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java index 76f9fbfb..1ad5710a 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/IntegerArrayStringConverter.java @@ -3,7 +3,7 @@ import javafx.util.StringConverter; import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.StringUtils; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of limited float string converter. diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java index c6807222..8da7d5b6 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedFloatStringConverter.java @@ -1,7 +1,7 @@ package javasabr.rlib.fx.util.converter; import javasabr.rlib.common.util.StringUtils; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of limited float string converter. diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java index 34e8081c..eab13e49 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedIntegerStringConverter.java @@ -1,7 +1,7 @@ package javasabr.rlib.fx.util.converter; import javasabr.rlib.common.util.StringUtils; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of limited integer string converter. diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java index 79458c71..abb50545 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/util/converter/LimitedNumberStringConverter.java @@ -2,8 +2,7 @@ import javafx.util.StringConverter; import javasabr.rlib.common.util.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The implementation of limited float string converter. @@ -29,7 +28,7 @@ public LimitedNumberStringConverter() { this.minValue = null; } - public LimitedNumberStringConverter(@NotNull T minValue, @NotNull T maxValue) { + public LimitedNumberStringConverter(T minValue, T maxValue) { this.maxValue = minValue; this.minValue = maxValue; } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java index ecc30c0b..739fbb09 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java @@ -6,7 +6,6 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; import javasabr.rlib.network.packet.Packet; -import org.jetbrains.annotations.NotNull; /** * The base implementation of {@link Packet}. diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java index ad82ba84..d2c9444d 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java @@ -2,7 +2,6 @@ import java.nio.ByteBuffer; import javasabr.rlib.network.packet.WritablePacket; -import org.jetbrains.annotations.NotNull; /** * The base implementation of the {@link WritablePacket}. diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java index 57297699..f989d60c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java @@ -1,7 +1,6 @@ package javasabr.rlib.network.packet.impl; import java.nio.ByteBuffer; -import org.jetbrains.annotations.NotNull; /** * Packet marker. diff --git a/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java b/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java index e28d082f..b2379455 100644 --- a/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java +++ b/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java @@ -7,7 +7,6 @@ import java.net.http.HttpResponse.BodySubscribers; import java.nio.charset.StandardCharsets; import lombok.Getter; -import org.jetbrains.annotations.NotNull; import org.testcontainers.containers.GenericContainer; public class FakeSMTPTestContainer extends GenericContainer { @@ -44,12 +43,12 @@ public int getSmtpPort() { return getMappedPort(SMTP_PORT); } - public @NotNull FakeSMTPTestContainer withSmtpUser(@NotNull String username) { + public FakeSMTPTestContainer withSmtpUser(String username) { this.smtpUser = username; return this; } - public @NotNull FakeSMTPTestContainer withSmtpPassword(@NotNull String password) { + public FakeSMTPTestContainer withSmtpPassword(String password) { this.smtpPassword = password; return this; } @@ -60,7 +59,7 @@ public int getSmtpPort() { * @param email the sender's email. * @return the emails count or -1 if the request was failed. */ - public long getEmailCountFrom(@NotNull String email) { + public long getEmailCountFrom(String email) { var request = HttpRequest .newBuilder(URI.create(getBaseUrl() + "/count/email/from/" + email)) @@ -105,7 +104,7 @@ public boolean deleteEmails() { } } - private @NotNull String getBaseUrl() { + private String getBaseUrl() { return "http://localhost:" + getMappedPort(HTTP_PORT); } diff --git a/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/package-info.java b/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/package-info.java new file mode 100644 index 00000000..bc90cfdb --- /dev/null +++ b/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.testcontainers; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file From b0993c9d340c654c9ab6afcd9d5b18456079dfd0 Mon Sep 17 00:00:00 2001 From: javasabr Date: Fri, 8 Aug 2025 21:25:15 +0200 Subject: [PATCH 6/8] finishe migrating to jspecify --- .../java/javasabr/rlib/common/BaseTest.java | 10 +-- .../rlib/common/util/IOUtilsTest.java | 3 +- .../rlib/fx/SimpleControlDialogTest.java | 11 ++- .../rlib/fx/SimplePopupDialogTest.java | 5 +- .../rlib/network/BaseNetworkTest.java | 75 +++++++++---------- .../rlib/network/DefaultNetworkTest.java | 23 +++--- .../rlib/network/StringNetworkTest.java | 7 +- .../rlib/network/StringSSLNetworkTest.java | 3 +- 8 files changed, 64 insertions(+), 73 deletions(-) diff --git a/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java b/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java index 3b18a6bf..ab03c8e1 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/BaseTest.java @@ -1,7 +1,5 @@ package javasabr.rlib.common; -import org.jetbrains.annotations.NotNull; - public class BaseTest { protected static class Type1 { @@ -12,18 +10,18 @@ protected static class Type2 { public static final Type2 EXAMPLE = new Type2(); } - public void assertType(@NotNull T object, @NotNull Class type) { + public void assertType(T object, Class type) { if (!type.isInstance(object)) { throw new ClassCastException(); } } - public void assertIntType(@NotNull Integer val) { + public void assertIntType(Integer val) { } - public void assertLongType(@NotNull Long val) { + public void assertLongType(Long val) { } - public void assertFloatType(@NotNull Float val) { + public void assertFloatType(Float val) { } } diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java index 0b098962..4c15dc1c 100644 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java +++ b/rlib-common/src/test/java/javasabr/rlib/common/util/IOUtilsTest.java @@ -7,7 +7,6 @@ import java.io.StringReader; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -84,7 +83,7 @@ void shouldThrownUncheckedIOExceptionDuringConvertingReaderToStrungUsingTLB() { Assertions.assertThrows( UncheckedIOException.class, () -> IOUtils.toStringUsingTLB(new Reader() { @Override - public int read(@NotNull char[] cbuf, int off, int len) throws IOException { + public int read(char[] cbuf, int off, int len) throws IOException { throw new IOException("test"); } diff --git a/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java b/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java index 42a2328d..caea448a 100644 --- a/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java +++ b/rlib-fx/src/test/java/javasabr/rlib/fx/SimpleControlDialogTest.java @@ -13,14 +13,13 @@ import javasabr.rlib.fx.control.dialog.ControlDialogSupport; import javasabr.rlib.fx.control.dialog.DefaultControlDialog; import javasabr.rlib.fx.util.FxUtils; -import org.jetbrains.annotations.NotNull; public class SimpleControlDialogTest extends Application { private static class TestDialog extends DefaultControlDialog { @Override - protected void fillContent(@NotNull GridPane content) { + protected void fillContent(GridPane content) { super.fillContent(content); var textArea = new TextArea("This is a text area."); @@ -35,7 +34,7 @@ protected void fillContent(@NotNull GridPane content) { } @Override - protected void fillActions(@NotNull GridPane actions) { + protected void fillActions(GridPane actions) { super.fillActions(actions); var okButton = new Button("Ok"); @@ -51,7 +50,7 @@ protected void fillActions(@NotNull GridPane actions) { } @Override - public void start(@NotNull Stage stage) { + public void start(Stage stage) { var root = new VBox(); root.setAlignment(Pos.CENTER); @@ -80,13 +79,13 @@ public void start(@NotNull Stage stage) { stage.show(); } - private void openInCenterDialog(@NotNull Scene scene) { + private void openInCenterDialog(Scene scene) { var dialog = new TestDialog(); dialog.applySize(200, 200); dialog.show(scene); } - private void openOverNode(@NotNull Node node) { + private void openOverNode(Node node) { var dialog = new TestDialog(); dialog.applySize(200, 200); dialog.show(node); diff --git a/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java b/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java index 482645ac..11a4c5a2 100644 --- a/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java +++ b/rlib-fx/src/test/java/javasabr/rlib/fx/SimplePopupDialogTest.java @@ -7,12 +7,11 @@ import javafx.stage.Stage; import javasabr.rlib.fx.dialog.SimplePopupDialog; import javasabr.rlib.fx.util.FxUtils; -import org.jetbrains.annotations.NotNull; public class SimplePopupDialogTest extends Application { @Override - public void start(@NotNull Stage stage) throws Exception { + public void start(Stage stage) throws Exception { var root = new StackPane(); var scene = new Scene(root); @@ -31,7 +30,7 @@ public void start(@NotNull Stage stage) throws Exception { stage.show(); } - private void openDialog(@NotNull Stage window) { + private void openDialog(Stage window) { SimplePopupDialog dialog = new SimplePopupDialog(); dialog.show(window); } diff --git a/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java index 36cbfcba..3ccfaaeb 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java @@ -11,7 +11,6 @@ import javasabr.rlib.network.server.ServerNetwork; import javax.net.ssl.SSLContext; import lombok.AllArgsConstructor; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -41,7 +40,7 @@ public void shutdown() { } } - protected @NotNull TestNetwork buildStringNetwork() { + protected TestNetwork buildStringNetwork() { return buildStringNetwork( ServerNetworkConfig.DEFAULT_SERVER, new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), @@ -49,9 +48,9 @@ public void shutdown() { new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT)); } - protected @NotNull TestNetwork buildStringSSLNetwork( - @NotNull SSLContext serverSSLContext, - @NotNull SSLContext clientSSLContext) { + protected TestNetwork buildStringSSLNetwork( + SSLContext serverSSLContext, + SSLContext clientSSLContext) { return buildStringSSLNetwork( ServerNetworkConfig.DEFAULT_SERVER, new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), @@ -61,9 +60,9 @@ public void shutdown() { clientSSLContext); } - protected @NotNull TestNetwork buildStringNetwork( - @NotNull BufferAllocator serverBufferAllocator, - @NotNull BufferAllocator clientBufferAllocator) { + protected TestNetwork buildStringNetwork( + BufferAllocator serverBufferAllocator, + BufferAllocator clientBufferAllocator) { return buildStringNetwork( ServerNetworkConfig.DEFAULT_SERVER, serverBufferAllocator, @@ -71,9 +70,9 @@ public void shutdown() { clientBufferAllocator); } - protected @NotNull TestNetwork buildStringNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator) { + protected TestNetwork buildStringNetwork( + ServerNetworkConfig serverNetworkConfig, + BufferAllocator serverBufferAllocator) { return buildStringNetwork( serverNetworkConfig, serverBufferAllocator, @@ -81,11 +80,11 @@ public void shutdown() { new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT)); } - protected @NotNull TestNetwork buildStringNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator, - @NotNull NetworkConfig clientNetworkConfig, - @NotNull BufferAllocator clientBufferAllocator) { + protected TestNetwork buildStringNetwork( + ServerNetworkConfig serverNetworkConfig, + BufferAllocator serverBufferAllocator, + NetworkConfig clientNetworkConfig, + BufferAllocator clientBufferAllocator) { var asyncClientToServer = new CompletableFuture(); var asyncServerToClient = new CompletableFuture(); @@ -109,13 +108,13 @@ public void shutdown() { clientNetwork); } - protected @NotNull TestNetwork buildStringSSLNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator, - @NotNull SSLContext serverSSLContext, - @NotNull NetworkConfig clientNetworkConfig, - @NotNull BufferAllocator clientBufferAllocator, - @NotNull SSLContext clientSSLContext) { + protected TestNetwork buildStringSSLNetwork( + ServerNetworkConfig serverNetworkConfig, + BufferAllocator serverBufferAllocator, + SSLContext serverSSLContext, + NetworkConfig clientNetworkConfig, + BufferAllocator clientBufferAllocator, + SSLContext clientSSLContext) { var asyncClientToServer = new CompletableFuture(); var asyncServerToClient = new CompletableFuture(); @@ -146,9 +145,9 @@ public void shutdown() { clientNetwork); } - protected @NotNull TestNetwork buildDefaultNetwork( - @NotNull ReadablePacketRegistry serverPacketRegistry, - @NotNull ReadablePacketRegistry clientPacketRegistry) { + protected TestNetwork buildDefaultNetwork( + ReadablePacketRegistry serverPacketRegistry, + ReadablePacketRegistry clientPacketRegistry) { return buildDefaultNetwork( ServerNetworkConfig.DEFAULT_SERVER, new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), @@ -158,11 +157,11 @@ public void shutdown() { clientPacketRegistry); } - protected @NotNull TestNetwork buildDefaultNetwork( - @NotNull BufferAllocator serverBufferAllocator, - @NotNull ReadablePacketRegistry serverPacketRegistry, - @NotNull BufferAllocator clientBufferAllocator, - @NotNull ReadablePacketRegistry clientPacketRegistry) { + protected TestNetwork buildDefaultNetwork( + BufferAllocator serverBufferAllocator, + ReadablePacketRegistry serverPacketRegistry, + BufferAllocator clientBufferAllocator, + ReadablePacketRegistry clientPacketRegistry) { return buildDefaultNetwork( ServerNetworkConfig.DEFAULT_SERVER, serverBufferAllocator, @@ -172,13 +171,13 @@ public void shutdown() { clientPacketRegistry); } - protected @NotNull TestNetwork buildDefaultNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator, - @NotNull ReadablePacketRegistry serverPacketRegistry, - @NotNull NetworkConfig clientNetworkConfig, - @NotNull BufferAllocator clientBufferAllocator, - @NotNull ReadablePacketRegistry clientPacketRegistry) { + protected TestNetwork buildDefaultNetwork( + ServerNetworkConfig serverNetworkConfig, + BufferAllocator serverBufferAllocator, + ReadablePacketRegistry serverPacketRegistry, + NetworkConfig clientNetworkConfig, + BufferAllocator clientBufferAllocator, + ReadablePacketRegistry clientPacketRegistry) { var asyncClientToServer = new CompletableFuture(); var asyncServerToClient = new CompletableFuture(); diff --git a/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java index 05a37d60..cca79717 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java @@ -28,7 +28,6 @@ import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.ToString; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -51,7 +50,7 @@ class RequestEchoMessage extends DefaultWritablePacket { private final String message; @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { + protected void writeImpl(ByteBuffer buffer) { super.writeImpl(buffer); writeString(buffer, message); } @@ -69,7 +68,7 @@ class ResponseEchoMessage extends DefaultReadablePacket { private volatile String message; @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + protected void readImpl(DefaultConnection connection, ByteBuffer buffer) { super.readImpl(connection, buffer); message = readString(buffer); } @@ -83,7 +82,7 @@ class ResponseServerTime extends DefaultReadablePacket { private volatile LocalDateTime localDateTime; @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + protected void readImpl(DefaultConnection connection, ByteBuffer buffer) { super.readImpl(connection, buffer); localDateTime = LocalDateTime.ofEpochSecond(readLong(buffer), 0, ZoneOffset.ofTotalSeconds(readInt(buffer))); } @@ -100,13 +99,13 @@ class RequestEchoMessage extends DefaultReadablePacket { private volatile String message; @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + protected void readImpl(DefaultConnection connection, ByteBuffer buffer) { super.readImpl(connection, buffer); message = readString(buffer); } @Override - protected void executeImpl(@NotNull DefaultConnection connection) { + protected void executeImpl(DefaultConnection connection) { super.executeImpl(connection); connection.send(new ResponseEchoMessage(message)); } @@ -117,12 +116,12 @@ protected void executeImpl(@NotNull DefaultConnection connection) { class RequestServerTime extends DefaultReadablePacket { @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + protected void readImpl(DefaultConnection connection, ByteBuffer buffer) { super.readImpl(connection, buffer); } @Override - protected void executeImpl(@NotNull DefaultConnection connection) { + protected void executeImpl(DefaultConnection connection) { super.executeImpl(connection); connection.send(new ResponseServerTime()); } @@ -135,7 +134,7 @@ class ResponseEchoMessage extends DefaultWritablePacket { private final String message; @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { + protected void writeImpl(ByteBuffer buffer) { super.writeImpl(buffer); writeString(buffer, "Echo: " + message); } @@ -145,7 +144,7 @@ protected void writeImpl(@NotNull ByteBuffer buffer) { class ResponseServerTime extends DefaultWritablePacket { @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { + protected void writeImpl(ByteBuffer buffer) { super.writeImpl(buffer); var dateTime = ZonedDateTime.now(); writeLong(buffer, dateTime.toEpochSecond()); @@ -219,7 +218,7 @@ void shouldNotUseMappedBuffers() { var serverAllocator = new DefaultBufferAllocator(DEFAULT_SERVER) { @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { + public ByteBuffer takeBuffer(int bufferSize) { throw new RuntimeException(); } }; @@ -227,7 +226,7 @@ void shouldNotUseMappedBuffers() { var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) { @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { + public ByteBuffer takeBuffer(int bufferSize) { throw new RuntimeException(); } }; diff --git a/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java index 261b3526..80758a2c 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java @@ -23,7 +23,6 @@ import javasabr.rlib.network.impl.DefaultBufferAllocator; import javasabr.rlib.network.packet.impl.StringWritablePacket; import lombok.SneakyThrows; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; @@ -80,7 +79,7 @@ void shouldNotUseTempBuffers() { var serverAllocator = new DefaultBufferAllocator(DEFAULT_SERVER) { @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { + public ByteBuffer takeBuffer(int bufferSize) { throw new RuntimeException(); } }; @@ -88,7 +87,7 @@ void shouldNotUseTempBuffers() { var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) { @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { + public ByteBuffer takeBuffer(int bufferSize) { throw new RuntimeException(); } }; @@ -399,7 +398,7 @@ void shouldGetAllPacketWithFeedback() { } } - private static @NotNull StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { + private static StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { return new StringWritablePacket(StringUtils.generate(minMessageLength, maxMessageLength)); } } diff --git a/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java index 2753e042..aace14f0 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java @@ -27,7 +27,6 @@ import javasabr.rlib.network.util.NetworkUtils; import javax.net.ssl.SSLSocket; import lombok.SneakyThrows; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -316,7 +315,7 @@ void shouldReceiveManyPacketsFromSmallToBigSize() { } } - private static @NotNull StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { + private static StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { return new StringWritablePacket(StringUtils.generate(minMessageLength, maxMessageLength)); } } From 1b4550c97bcf4914ad99fae4c157edb365aa7753 Mon Sep 17 00:00:00 2001 From: javasabr Date: Sat, 9 Aug 2025 16:55:31 +0200 Subject: [PATCH 7/8] resolve scan issues --- .../javasabr/rlib/common/util/FileUtils.java | 13 ++- .../rlib/common/util/crypt/SymmetryCrypt.java | 81 ++++++------------- .../rlib/common/util/crypt/package-info.java | 4 + .../rlib/common/util/package-info.java | 4 + 4 files changed, 41 insertions(+), 61 deletions(-) create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/util/crypt/package-info.java create mode 100644 rlib-common/src/main/java/javasabr/rlib/common/util/package-info.java diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java index 1bed088a..cceffbac 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java @@ -36,8 +36,8 @@ import javasabr.rlib.common.util.array.ArrayComparator; import javasabr.rlib.common.util.array.ArrayFactory; import javasabr.rlib.common.util.array.UnsafeArray; +import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; -import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** @@ -45,9 +45,10 @@ * * @author JavaSaBr */ -@NullMarked public class FileUtils { + private static final Logger LOGGER = LoggerManager.getLogger(FileUtils.class); + public static final ArrayComparator FILE_PATH_LENGTH_COMPARATOR = (first, second) -> { int firstLength = first.getNameCount(); @@ -612,7 +613,13 @@ public static void unzip(Path destination, Path zipFile) { try (var zin = new ZipInputStream(Files.newInputStream(zipFile))) { for (var entry = zin.getNextEntry(); entry != null; entry = zin.getNextEntry()) { - var file = destination.resolve(entry.getName()); + String entryName = entry.getName(); + if (entryName.startsWith("..")) { + LOGGER.warning(entryName, "Unexpected entry name:[%s]"::formatted); + continue; + } + + var file = destination.resolve(entryName); if (entry.isDirectory()) { Files.createDirectories(file); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java index 3c471efd..02cc7274 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java @@ -1,6 +1,8 @@ package javasabr.rlib.common.util.crypt; +import java.io.Serial; import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; @@ -9,55 +11,40 @@ import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; -import org.jspecify.annotations.NullMarked; +import lombok.AccessLevel; +import lombok.experimental.FieldDefaults; /** - * The symmetry crypt based on RC4. - * * @author JavaSaBr */ -@NullMarked +@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) public class SymmetryCrypt { - /** - * The crypter. - */ - private final Cipher ecipher; - - /** - * The encrypter. - */ - private final Cipher dcipher; - - /** - * THe secret key. - */ - private final SecretKey secretKey; - - /** - * Instantiates a new Symmetry crypt. - * - * @param key the key. - * @throws NoSuchAlgorithmException the no such algorithm exception - * @throws NoSuchPaddingException the no such padding exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws InvalidKeyException the invalid key exception - */ - public SymmetryCrypt(final String key) + public static final String ALG_RC_4 = "RC4"; + + Cipher ecipher; + Cipher dcipher; + + public SymmetryCrypt(String key) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException { + this(key, ALG_RC_4); + } - final Cipher ecipher = Cipher.getInstance("RC4"); - final Cipher dcipher = Cipher.getInstance("RC4"); + public SymmetryCrypt(String key, String algorithm) + throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException { - final byte[] bytes = key.getBytes("UTF-8"); + Cipher ecipher = Cipher.getInstance(algorithm); + Cipher dcipher = Cipher.getInstance(algorithm); - secretKey = new SecretKey() { + byte[] bytes = key.getBytes(StandardCharsets.UTF_8); + var secretKey = new SecretKey() { + @Serial private static final long serialVersionUID = -8907627571317506056L; @Override public String getAlgorithm() { - return "RC4"; + return algorithm; } @Override @@ -78,34 +65,12 @@ public String getFormat() { this.dcipher = dcipher; } - /** - * Decrypt data. - * - * @param in the encrypted data. - * @param offset the offset. - * @param length the length. - * @param out the buffer to store decrypted data. - * @throws ShortBufferException the short buffer exception - * @throws IllegalBlockSizeException the illegal block size exception - * @throws BadPaddingException the bad padding exception - */ - public void decrypt(final byte[] in, final int offset, final int length, final byte[] out) + public void decrypt(byte[] in, int offset, int length, byte[] out) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { dcipher.doFinal(in, offset, length, out, offset); } - /** - * Encrypt data. - * - * @param in the decrypted data. - * @param offset the offset. - * @param length the length. - * @param out the buffer to store encrypted data. - * @throws ShortBufferException the short buffer exception - * @throws IllegalBlockSizeException the illegal block size exception - * @throws BadPaddingException the bad padding exception - */ - public void encrypt(final byte[] in, final int offset, final int length, final byte[] out) + public void encrypt(byte[] in, int offset, int length, byte[] out) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { ecipher.doFinal(in, offset, length, out, offset); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/package-info.java new file mode 100644 index 00000000..c73e858e --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.util.crypt; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/util/package-info.java new file mode 100644 index 00000000..ea702ad1 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.common.util; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file From fee53d07edb55a3bacfe9d08cafdfaf988dda15c Mon Sep 17 00:00:00 2001 From: javasabr Date: Sat, 9 Aug 2025 17:08:01 +0200 Subject: [PATCH 8/8] resolve scan issues --- .../javasabr/rlib/common/util/FileUtils.java | 14 ++++++++------ .../rlib/fx/control/input/FloatTextField.java | 17 +++++++++-------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java index cceffbac..eaec478a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/FileUtils.java @@ -614,17 +614,19 @@ public static void unzip(Path destination, Path zipFile) { for (var entry = zin.getNextEntry(); entry != null; entry = zin.getNextEntry()) { String entryName = entry.getName(); - if (entryName.startsWith("..")) { - LOGGER.warning(entryName, "Unexpected entry name:[%s]"::formatted); + Path targetFile = destination + .resolve(entryName) + .normalize(); + + if (!targetFile.startsWith(destination)) { + LOGGER.warning(entryName, "Unexpected entry name:[%s] which is outside"::formatted); continue; } - var file = destination.resolve(entryName); - if (entry.isDirectory()) { - Files.createDirectories(file); + Files.createDirectories(targetFile); } else { - Files.copy(zin, file, StandardCopyOption.REPLACE_EXISTING); + Files.copy(zin, targetFile, StandardCopyOption.REPLACE_EXISTING); } } diff --git a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java index 092cbcae..44e8c421 100644 --- a/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java +++ b/rlib-fx/src/main/java/javasabr/rlib/fx/control/input/FloatTextField.java @@ -1,5 +1,6 @@ package javasabr.rlib.fx.control.input; +import java.util.Objects; import javafx.scene.input.ScrollEvent; import javasabr.rlib.fx.util.converter.LimitedFloatStringConverter; import javasabr.rlib.fx.util.converter.LimitedNumberStringConverter; @@ -11,8 +12,10 @@ */ public final class FloatTextField extends NumberTextField { + public static final Float DEFAULT_VALUE = 0F; + public FloatTextField() { - setValue(0F); + setValue(DEFAULT_VALUE); } @Override @@ -24,14 +27,12 @@ protected LimitedNumberStringConverter createValueConverter() { protected void scrollValueImpl(ScrollEvent event) { super.scrollValueImpl(event); - var value = getValue(); - - var longValue = (long) (value * 1000); - longValue += event.getDeltaY() * (getScrollPower() * (event.isShiftDown() ? 0.5F : 1F)); + double toAdd = event.getDeltaY() * (getScrollPower() * (event.isShiftDown() ? 0.5F : 1F)); + float value = Objects.requireNonNullElse(getValue(), DEFAULT_VALUE); + long longValue = ((long) (value * 1000L)) + (long) toAdd; + float resultValue = longValue / 1000F; - var resultValue = longValue / 1000F; var stringValue = String.valueOf(resultValue); - var textFormatter = getTextFormatter(); var valueConverter = textFormatter.getValueConverter(); try { @@ -52,6 +53,6 @@ protected void scrollValueImpl(ScrollEvent event) { public float getPrimitiveValue() { var textFormatter = getTypedTextFormatter(); var value = textFormatter.getValue(); - return value == null ? 0F : value; + return value == null ? DEFAULT_VALUE : value; } }

factory - ) { - - var description = cs.getAnnotation(PacketDescription.class); - - if (description == null) { - throw new IllegalArgumentException("Class " + cs + " doesn't have packet description annotation."); - } - - var id = description.id(); - - if (id < 0) { - throw new IllegalArgumentException("Class " + cs + " has wrong packet id: " + id); - } - - var idToPacket = getIdToPacket(); - - if (id < idToPacket.length) { - if (idToPacket[id] != null) { - throw new IllegalArgumentException("Class " + idToPacket[id].getClass() + - " is already has the same id: " + id); - } else { - idToPacket[id] = ClassUtils.newInstance(cs); - return this; - } - } - - idToPacket = Arrays.copyOf(getIdToPacket(), id + 1); - idToPacket[id] = factory.get(); - - setIdToPacket(idToPacket); + idToPacket = Arrays.copyOf(getIdToPacket(), id + 1); + idToPacket[id] = factory.get(); - return this; - } + setIdToPacket(idToPacket); - @Override - public @NotNull R findById(int id) { + return this; + } - R[] idToPacket = getIdToPacket(); + @Override + public @NotNull R findById(int id) { - if (id < 0 || id >= idToPacket.length) { - throw new IllegalArgumentException("Not found a packet for the id " + id); - } + R[] idToPacket = getIdToPacket(); - var packet = idToPacket[id]; + if (id < 0 || id >= idToPacket.length) { + throw new IllegalArgumentException("Not found a packet for the id " + id); + } - if (packet == null) { - throw new IllegalArgumentException("Not found a packet for the id " + id); - } + var packet = idToPacket[id]; - return packet; + if (packet == null) { + throw new IllegalArgumentException("Not found a packet for the id " + id); } + + return packet; + } } 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 b3a31de1..07561724 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 @@ -14,33 +14,33 @@ */ public interface ServerNetwork> extends Network { - /** - * Start a server using any available address. - * - * @return this server's address. - */ - @NotNull InetSocketAddress start(); + /** + * Start a server using any available address. + * + * @return this server's address. + */ + @NotNull InetSocketAddress start(); - /** - * Start a server by the address. - * - * @param serverAddress the sever address. - * @param the server network's type. - * @return this network. - */ - > @NotNull S start(@NotNull InetSocketAddress serverAddress); + /** + * Start a server by the address. + * + * @param serverAddress the sever address. + * @param the server network's type. + * @return this network. + */ + > @NotNull S start(@NotNull InetSocketAddress serverAddress); - /** - * Register a consumer of new connections. - * - * @param consumer the consumer of new connections. - */ - void onAccept(@NotNull Consumer consumer); + /** + * Register a consumer of new connections. + * + * @param consumer the consumer of new connections. + */ + void onAccept(@NotNull Consumer consumer); - /** - * Get a stream of new accepted connections. - * - * @return the stream of new accepted connections. - */ - @NotNull Flux accepted(); + /** + * Get a stream of new accepted connections. + * + * @return the stream of new accepted connections. + */ + @NotNull Flux accepted(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java index b22d0bd1..b6c033ad 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java @@ -42,153 +42,152 @@ public final class DefaultServerNetwork> extends AbstractNetwork implements ServerNetwork { - protected static final Logger LOGGER = LoggerManager.getLogger(DefaultServerNetwork.class); + protected static final Logger LOGGER = LoggerManager.getLogger(DefaultServerNetwork.class); - private interface ServerCompletionHandler> extends - CompletionHandler> {} + private interface ServerCompletionHandler> extends + CompletionHandler> {} - private final ServerCompletionHandler acceptHandler = new ServerCompletionHandler<>() { - - @Override - public void completed(@NotNull AsynchronousSocketChannel channel, @NotNull DefaultServerNetwork network) { - var connection = network.channelToConnection.apply(DefaultServerNetwork.this, channel); - LOGGER.debug(connection, conn -> "Accepted new connection: " + conn.getRemoteAddress()); - network.onAccept(connection); - network.acceptNext(); - } - - @Override - public void failed(@NotNull Throwable exc, @NotNull DefaultServerNetwork network) { - if (exc instanceof AsynchronousCloseException) { - LOGGER.warning("Server network was closed"); - } else { - LOGGER.error("Got exception during accepting new connection:"); - LOGGER.error(exc); - - if (channel.isOpen()) { - network.acceptNext(); - } - } - } - }; - - protected final AsynchronousChannelGroup group; - protected final AsynchronousServerSocketChannel channel; - protected final Array> subscribers; - - public DefaultServerNetwork( - @NotNull ServerNetworkConfig config, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection - ) { - - super(config, channelToConnection); - - var threadFactory = new GroupThreadFactory( - config.getThreadGroupName(), - config.getThreadConstructor(), - config.getThreadPriority(), - false - ); - - var executor = config.getThreadGroupMinSize() < config.getThreadGroupMaxSize() ? new ThreadPoolExecutor( - config.getThreadGroupMinSize(), - config.getThreadGroupMaxSize(), - 120, - TimeUnit.SECONDS, - new SynchronousQueue<>(), - threadFactory, - new ThreadPoolExecutor.CallerRunsPolicy() - ) : Executors.newFixedThreadPool(config.getThreadGroupMinSize(), threadFactory); - - // activate the executor - executor.submit(() -> {}); - - LOGGER.info(config, conf -> "Server network configuration: {\n" + - " minThreads: " + conf.getThreadGroupMinSize() + ",\n" + - " maxThreads: " + conf.getThreadGroupMaxSize() + ",\n" + - " priority: " + conf.getThreadPriority() + ",\n" + - " groupName: \"" + conf.getThreadGroupName() + "\",\n" + - " readBufferSize: " + conf.getReadBufferSize() + ",\n" + - " pendingBufferSize: " + conf.getPendingBufferSize() + ",\n" + - " writeBufferSize: " + conf.getWriteBufferSize() + "\n" + - "}"); - - this.group = uncheckedGet(executor, AsynchronousChannelGroup::withThreadPool); - this.channel = uncheckedGet(group, AsynchronousServerSocketChannel::open); - this.subscribers = ArrayFactory.newCopyOnModifyArray(Consumer.class); - } + private final ServerCompletionHandler acceptHandler = new ServerCompletionHandler<>() { @Override - public @NotNull InetSocketAddress start() { - - InetSocketAddress address = null; - - while (address == null) { - - address = new InetSocketAddress(NetworkUtils.getAvailablePort(1500)); - try { - channel.bind(address); - } catch (IOException e) { - address = null; - } - } - - LOGGER.info(address, adr -> "Started server socket on address: " + adr); - - if (!subscribers.isEmpty()) { - acceptNext(); - } - - return address; + public void completed(@NotNull AsynchronousSocketChannel channel, @NotNull DefaultServerNetwork network) { + var connection = network.channelToConnection.apply(DefaultServerNetwork.this, channel); + LOGGER.debug(connection, conn -> "Accepted new connection: " + conn.getRemoteAddress()); + network.onAccept(connection); + network.acceptNext(); } @Override - public > @NotNull S start(@NotNull InetSocketAddress serverAddress) { - Utils.unchecked(channel, serverAddress, AsynchronousServerSocketChannel::bind); + public void failed(@NotNull Throwable exc, @NotNull DefaultServerNetwork network) { + if (exc instanceof AsynchronousCloseException) { + LOGGER.warning("Server network was closed"); + } else { + LOGGER.error("Got exception during accepting new connection:"); + LOGGER.error(exc); - LOGGER.info(serverAddress, addr -> "Started server socket on address: " + addr); - - if (!subscribers.isEmpty()) { - acceptNext(); - } - - return ClassUtils.unsafeNNCast(this); - } - - protected void acceptNext() { if (channel.isOpen()) { - try { channel.accept(this, acceptHandler); } - catch (AcceptPendingException ignored) {} - } else { - LOGGER.warning("Cannot accept a next connection because server channel is already closed"); + network.acceptNext(); } + } } - - protected void onAccept(@NotNull C connection) { - connection.onConnected(); - subscribers.forEachR(connection, Consumer::accept); + }; + + protected final AsynchronousChannelGroup group; + protected final AsynchronousServerSocketChannel channel; + protected final Array> subscribers; + + public DefaultServerNetwork( + @NotNull ServerNetworkConfig config, + @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + + super(config, channelToConnection); + + var threadFactory = new GroupThreadFactory( + config.getThreadGroupName(), + config.getThreadConstructor(), + config.getThreadPriority(), + false); + + var executor = config.getThreadGroupMinSize() < config.getThreadGroupMaxSize() + ? new ThreadPoolExecutor( + config.getThreadGroupMinSize(), + config.getThreadGroupMaxSize(), + 120, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + threadFactory, + new ThreadPoolExecutor.CallerRunsPolicy()) + : Executors.newFixedThreadPool(config.getThreadGroupMinSize(), threadFactory); + + // activate the executor + executor.submit(() -> {}); + + LOGGER.info( + config, + conf -> "Server network configuration: {\n" + " minThreads: " + conf.getThreadGroupMinSize() + ",\n" + + " maxThreads: " + conf.getThreadGroupMaxSize() + ",\n" + " priority: " + conf.getThreadPriority() + + ",\n" + " groupName: \"" + conf.getThreadGroupName() + "\",\n" + " readBufferSize: " + + conf.getReadBufferSize() + ",\n" + " pendingBufferSize: " + conf.getPendingBufferSize() + ",\n" + + " writeBufferSize: " + conf.getWriteBufferSize() + "\n" + "}"); + + this.group = uncheckedGet(executor, AsynchronousChannelGroup::withThreadPool); + this.channel = uncheckedGet(group, AsynchronousServerSocketChannel::open); + this.subscribers = ArrayFactory.newCopyOnModifyArray(Consumer.class); + } + + @Override + public @NotNull InetSocketAddress start() { + + InetSocketAddress address = null; + + while (address == null) { + + address = new InetSocketAddress(NetworkUtils.getAvailablePort(1500)); + try { + channel.bind(address); + } catch (IOException e) { + address = null; + } } - @Override - public void onAccept(@NotNull Consumer consumer) { - subscribers.add(consumer); - acceptNext(); - } + LOGGER.info(address, adr -> "Started server socket on address: " + adr); - @Override - public @NotNull Flux accepted() { - return Flux.create(this::registerFluxOnAccepted); + if (!subscribers.isEmpty()) { + acceptNext(); } - protected void registerFluxOnAccepted(@NotNull FluxSink sink) { - Consumer listener = sink::next; - onAccept(listener); - sink.onDispose(() -> subscribers.remove(listener)); + return address; + } + + @Override + public > @NotNull S start(@NotNull InetSocketAddress serverAddress) { + Utils.unchecked(channel, serverAddress, AsynchronousServerSocketChannel::bind); + + LOGGER.info(serverAddress, addr -> "Started server socket on address: " + addr); + + if (!subscribers.isEmpty()) { + acceptNext(); } - @Override - public void shutdown() { - Utils.unchecked(channel, AsynchronousChannel::close); - group.shutdown(); + return ClassUtils.unsafeNNCast(this); + } + + protected void acceptNext() { + if (channel.isOpen()) { + try { + channel.accept(this, acceptHandler); + } catch (AcceptPendingException ignored) { + } + } else { + LOGGER.warning("Cannot accept a next connection because server channel is already closed"); } + } + + protected void onAccept(@NotNull C connection) { + connection.onConnected(); + subscribers.forEachR(connection, Consumer::accept); + } + + @Override + public void onAccept(@NotNull Consumer consumer) { + subscribers.add(consumer); + acceptNext(); + } + + @Override + public @NotNull Flux accepted() { + return Flux.create(this::registerFluxOnAccepted); + } + + protected void registerFluxOnAccepted(@NotNull FluxSink sink) { + Consumer listener = sink::next; + onAccept(listener); + sink.onDispose(() -> subscribers.remove(listener)); + } + + @Override + public void shutdown() { + Utils.unchecked(channel, AsynchronousChannel::close); + group.shutdown(); + } } 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 48f43acd..2933049e 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 @@ -29,327 +29,325 @@ */ public class NetworkUtils { - public static final @NotNull ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); + public static final @NotNull ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); - public static class AllTrustManager implements X509TrustManager { + public static class AllTrustManager implements X509TrustManager { - public static final @NotNull X509Certificate[] EMPTY_CERTS = new X509Certificate[0]; + public static final @NotNull X509Certificate[] EMPTY_CERTS = new X509Certificate[0]; - public @NotNull X509Certificate[] getAcceptedIssuers() { - return EMPTY_CERTS; - } - - public void checkClientTrusted(@NotNull X509Certificate[] certificates, @NotNull String arg1) { } - public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull String arg1) { } + public @NotNull X509Certificate[] getAcceptedIssuers() { + return EMPTY_CERTS; } - public static @NotNull SocketAddress getRemoteAddress(@NotNull AsynchronousSocketChannel socketChannel) { - return Utils.uncheckedGet(socketChannel, AsynchronousSocketChannel::getRemoteAddress); + public void checkClientTrusted(@NotNull X509Certificate[] certificates, @NotNull String arg1) { } - public static @NotNull SSLContext createSslContext( - @NotNull InputStream keyStoreData, - @NotNull String keyStorePassword - ) { - return createSslContext( - "PKCS12", - keyStoreData, - keyStorePassword, - null, - null, - null - ); + public void checkServerTrusted(@NotNull X509Certificate[] certificates, @NotNull String arg1) { } + } - public static @NotNull SSLContext createSslContext( - @NotNull String keyStoreType, - @NotNull InputStream keyStoreData, - @NotNull String keyStorePassword, - @Nullable String trustStoreType, - @Nullable InputStream trustStoreData, - @Nullable String trustStorePassword - ) { + public static @NotNull SocketAddress getRemoteAddress(@NotNull AsynchronousSocketChannel socketChannel) { + return Utils.uncheckedGet(socketChannel, AsynchronousSocketChannel::getRemoteAddress); + } - try { + public static @NotNull SSLContext createSslContext( + @NotNull InputStream keyStoreData, + @NotNull String keyStorePassword) { + return createSslContext("PKCS12", keyStoreData, keyStorePassword, null, null, null); + } - var keyStore = KeyStore.getInstance(keyStoreType); - keyStore.load(keyStoreData, keyStorePassword.toCharArray()); + public static @NotNull SSLContext createSslContext( + @NotNull String keyStoreType, + @NotNull InputStream keyStoreData, + @NotNull String keyStorePassword, + @Nullable String trustStoreType, + @Nullable InputStream trustStoreData, + @Nullable String trustStorePassword) { - var kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kmf.init(keyStore, keyStorePassword.toCharArray()); + try { - var keyManagers = kmf.getKeyManagers(); + var keyStore = KeyStore.getInstance(keyStoreType); + keyStore.load(keyStoreData, keyStorePassword.toCharArray()); - TrustManager[] trustManagers = null; + var kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, keyStorePassword.toCharArray()); - if (trustStoreType != null && trustStoreData != null) { + var keyManagers = kmf.getKeyManagers(); - var trustStore = KeyStore.getInstance(trustStoreType); - trustStore.load(trustStoreData, trustStorePassword == null ? null : trustStorePassword.toCharArray()); + TrustManager[] trustManagers = null; - var tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(trustStore); + if (trustStoreType != null && trustStoreData != null) { - trustManagers = tmf.getTrustManagers(); - } + var trustStore = KeyStore.getInstance(trustStoreType); + trustStore.load(trustStoreData, trustStorePassword == null ? null : trustStorePassword.toCharArray()); - var sslContext = SSLContext.getInstance("TLSv1.2"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); + var tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(trustStore); - return sslContext; + trustManagers = tmf.getTrustManagers(); + } - } catch (Exception e) { - throw new RuntimeException(e); - } + var sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + + return sslContext; + + } catch (Exception e) { + throw new RuntimeException(e); } + } - public static @NotNull SSLContext createAllTrustedClientSslContext() { + public static @NotNull SSLContext createAllTrustedClientSslContext() { - try { + try { - var sslContext = SSLContext.getInstance("TLSv1.2"); - sslContext.init(null, ArrayFactory.toArray(new AllTrustManager()), new SecureRandom()); + var sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, ArrayFactory.toArray(new AllTrustManager()), new SecureRandom()); - return sslContext; + return sslContext; - } catch (Exception e) { - throw new RuntimeException(e); - } + } catch (Exception e) { + throw new RuntimeException(e); } - - /** - * Prepare a string like 'HEX DUMP' by passed byte buffer. - * - * @param buffer the byte buffer. - * @return the hex dump string. - * @since 9.9.0 - */ - public static @NotNull String hexDump(@NotNull ByteBuffer buffer) { - if (!buffer.hasRemaining()) { - return ""; - } else { - return hexDump(buffer.array(), buffer.position(), buffer.limit()); - } + } + + /** + * Prepare a string like 'HEX DUMP' by passed byte buffer. + * + * @param buffer the byte buffer. + * @return the hex dump string. + * @since 9.9.0 + */ + public static @NotNull String hexDump(@NotNull ByteBuffer buffer) { + if (!buffer.hasRemaining()) { + return ""; + } else { + return hexDump(buffer.array(), buffer.position(), buffer.limit()); } - - /** - * Prepare a string like 'HEX DUMP' by passed 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 - */ - public static @NotNull String hexDump(@NotNull ByteBuffer buffer, @NotNull SSLEngineResult result) { - if (result.bytesProduced() < 1) { - return ""; - } else { - return hexDump(buffer.array(), 0, result.bytesProduced()); - } + } + + /** + * Prepare a string like 'HEX DUMP' by passed 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 + */ + public static @NotNull String hexDump(@NotNull ByteBuffer buffer, @NotNull SSLEngineResult result) { + if (result.bytesProduced() < 1) { + return ""; + } else { + return hexDump(buffer.array(), 0, result.bytesProduced()); } - - /** - * Prepare a string like 'HEX DUMP' by passed array. - * - * @param array the bytes array. - * @param length the length. - * @return the hex dump string. - */ - public static @NotNull String hexDump(@NotNull byte[] array, int length) { - return hexDump(array, 0, length); + } + + /** + * Prepare a string like 'HEX DUMP' by passed array. + * + * @param array the bytes array. + * @param length the length. + * @return the hex dump string. + */ + public static @NotNull String hexDump(@NotNull byte[] array, int length) { + return hexDump(array, 0, length); + } + + /** + * Prepare a string like 'HEX DUMP' by passed array. + * + * @param array the byte array. + * @param offset the offset. + * @param length the length. + * @return the hex dump string. + */ + public static @NotNull String hexDump(@NotNull byte[] array, int offset, int length) { + + var builder = new StringBuilder(); + var count = 0; + var end = length - 1; + var chars = new char[16]; + + for (int g = 0; g < 16; g++) { + chars[g] = '.'; } - /** - * Prepare a string like 'HEX DUMP' by passed array. - * - * @param array the byte array. - * @param offset the offset. - * @param length the length. - * @return the hex dump string. - */ - public static @NotNull String hexDump(@NotNull byte[] array, int offset, int length) { - - var builder = new StringBuilder(); - var count = 0; - var end = length - 1; - var chars = new char[16]; + hexDigit(builder, (byte) ((offset >>> 8) & 0xFF)); + hexDigit(builder, (byte) (offset & 0xFF)); + builder.append(": "); - for (int g = 0; g < 16; g++) { - chars[g] = '.'; - } - - hexDigit(builder, (byte) ((offset >>> 8) & 0xFF)); - hexDigit(builder, (byte) (offset & 0xFF)); - builder.append(": "); + for (int i = offset; i < length; i++) { - for (int i = offset; i < length; i++) { + byte val = array[i]; - byte val = array[i]; + char ch; - char ch; + if (val < ' ' || val > 'z') { + ch = '.'; + } else { + ch = (char) val; + } - if (val < ' ' || val > 'z') { - ch = '.'; - } else { - ch = (char) val; - } + if (i == end) { - if (i == end) { + chars[count] = ch; - chars[count] = ch; + hexDigit(builder, val) + .append(" ".repeat(15 - count)) + .append(" "); - hexDigit(builder, val) - .append(" ".repeat(15 - count)) - .append(" "); - - if (count < 9) { - builder.append(" "); - } + if (count < 9) { + builder.append(" "); + } - builder.append(chars); + builder.append(chars); - } else if (count < 15) { + } else if (count < 15) { - chars[count++] = ch; - hexDigit(builder, val).append(' '); + chars[count++] = ch; + hexDigit(builder, val).append(' '); - if (count == 8) { - builder.append(" "); - } + if (count == 8) { + builder.append(" "); + } - } else { + } else { - chars[15] = ch; + chars[15] = ch; - hexDigit(builder, val) - .append(" ") - .append(chars) - .append('\n'); + hexDigit(builder, val) + .append(" ") + .append(chars) + .append('\n'); - var nextPos = i + 1; + var nextPos = i + 1; - hexDigit(builder, (byte) ((nextPos >>> 8) & 0xFF)); - hexDigit(builder, (byte) (nextPos & 0xFF)); - builder.append(": "); + hexDigit(builder, (byte) ((nextPos >>> 8) & 0xFF)); + hexDigit(builder, (byte) (nextPos & 0xFF)); + builder.append(": "); - count = 0; + count = 0; - for (int g = 0; g < 16; g++) { - chars[g] = '.'; - } - } + for (int g = 0; g < 16; g++) { + chars[g] = '.'; } - - return builder.toString(); + } } - private static @NotNull StringBuilder hexDigit(@NotNull StringBuilder builder, byte value) { - - char ch = (char) ((value >> 4) & 0xF); - - if (ch > 9) { - ch = (char) ((ch - 10) + 'A'); - } else { - ch = (char) (ch + '0'); - } - - builder.append(ch); - - ch = (char) (value & 0xF); + return builder.toString(); + } - if (ch > 9) { - ch = (char) ((ch - 10) + 'A'); - } else { - ch = (char) (ch + '0'); - } + private static @NotNull StringBuilder hexDigit(@NotNull StringBuilder builder, byte value) { - builder.append(ch); + char ch = (char) ((value >> 4) & 0xF); - return builder; + if (ch > 9) { + ch = (char) ((ch - 10) + 'A'); + } else { + ch = (char) (ch + '0'); } - /** - * Check a network port to know is available it or not to open a new socket. - * - * @param port the port. - * @return true if the port is available. - */ - public static boolean isPortAvailable(int port) { - return isPortAvailable("*", port); - } + builder.append(ch); - /** - * Check a network port to know is available it or not to open a new socket. - * - * @param host the host. - * @param port the port. - * @return true if the port is available. - */ - public static boolean isPortAvailable(@NotNull String host, int port) { - try (var ignored = "*".equals(host) ? new ServerSocket(port) : - new ServerSocket(port, 50, InetAddress.getByName(host))) { - return true; - } catch (IOException e) { - return false; - } - } + ch = (char) (value & 0xF); - /** - * Get a nearest available network port from a start port. - * - * @param port the start port. - * @return the nearest available network port or -1. - */ - public static int getAvailablePort(int port) { - return IntStream.range(port, Short.MAX_VALUE * 2) - .filter(NetworkUtils::isPortAvailable) - .findFirst() - .orElse(-1); + if (ch > 9) { + ch = (char) ((ch - 10) + 'A'); + } else { + ch = (char) (ch + '0'); } - public static @NotNull ByteBuffer enlargePacketBuffer( - @NotNull BufferAllocator allocator, - @NotNull SSLEngine engine - ) { - return allocator.takeBuffer(engine.getSession().getPacketBufferSize()); + builder.append(ch); + + return builder; + } + + /** + * Check a network port to know is available it or not to open a new socket. + * + * @param port the port. + * @return true if the port is available. + */ + 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. + * + * @param host the host. + * @param port the port. + * @return true if the port is available. + */ + public static boolean isPortAvailable(@NotNull String host, int port) { + try (var ignored = "*".equals(host) + ? new ServerSocket(port) + : new ServerSocket(port, 50, InetAddress.getByName(host))) { + return true; + } catch (IOException e) { + return false; } - - public static @NotNull ByteBuffer increaseApplicationBuffer( - @NotNull ByteBuffer current, - @NotNull BufferAllocator allocator, - @NotNull SSLEngine engine - ) { - - var newBuffer = allocator.takeBuffer(engine.getSession().getApplicationBufferSize()); - newBuffer.put(current); - - if (current.capacity() > 0) { - allocator.putBuffer(current); - } - - return newBuffer; + } + + /** + * Get a nearest available network port from a start port. + * + * @param port the start port. + * @return the nearest available network port or -1. + */ + public static int getAvailablePort(int port) { + return IntStream + .range(port, Short.MAX_VALUE * 2) + .filter(NetworkUtils::isPortAvailable) + .findFirst() + .orElse(-1); + } + + public static @NotNull ByteBuffer enlargePacketBuffer(@NotNull BufferAllocator allocator, @NotNull SSLEngine engine) { + return allocator.takeBuffer(engine + .getSession() + .getPacketBufferSize()); + } + + public static @NotNull ByteBuffer increaseApplicationBuffer( + @NotNull ByteBuffer current, + @NotNull BufferAllocator allocator, + @NotNull SSLEngine engine) { + + var newBuffer = allocator.takeBuffer(engine + .getSession() + .getApplicationBufferSize()); + newBuffer.put(current); + + if (current.capacity() > 0) { + allocator.putBuffer(current); } - public static @NotNull ByteBuffer increasePacketBuffer( - @NotNull ByteBuffer current, - @NotNull BufferAllocator allocator, - @NotNull SSLEngine engine - ) { + return newBuffer; + } - var newBuffer = allocator.takeBuffer(engine.getSession().getPacketBufferSize()); - newBuffer.put(current); + public static @NotNull ByteBuffer increasePacketBuffer( + @NotNull ByteBuffer current, + @NotNull BufferAllocator allocator, + @NotNull SSLEngine engine) { - if (current.capacity() > 0) { - allocator.putBuffer(current); - } + var newBuffer = allocator.takeBuffer(engine + .getSession() + .getPacketBufferSize()); + newBuffer.put(current); - return newBuffer; + if (current.capacity() > 0) { + allocator.putBuffer(current); } - public static @NotNull ByteBuffer enlargeApplicationBuffer( - @NotNull BufferAllocator allocator, - @NotNull SSLEngine engine - ) { - return allocator.takeBuffer(engine.getSession().getApplicationBufferSize()); - } + return newBuffer; + } + + public static @NotNull ByteBuffer enlargeApplicationBuffer( + @NotNull BufferAllocator allocator, + @NotNull SSLEngine engine) { + return allocator.takeBuffer(engine + .getSession() + .getApplicationBufferSize()); + } } diff --git a/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java index 2cb1afce..36cbfcba 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/BaseNetworkTest.java @@ -18,211 +18,193 @@ */ public class BaseNetworkTest { - @AllArgsConstructor - public static class TestNetwork> implements AutoCloseable { + @AllArgsConstructor + public static class TestNetwork> implements AutoCloseable { - public final ServerNetworkConfig serverNetworkConfig; - public final NetworkConfig clientNetworkConfig; + public final ServerNetworkConfig serverNetworkConfig; + public final NetworkConfig clientNetworkConfig; - public final C clientToServer; - public final C serverToClient; + public final C clientToServer; + public final C serverToClient; - private final ServerNetwork serverNetwork; - private final ClientNetwork clientNetwork; + private final ServerNetwork serverNetwork; + private final ClientNetwork clientNetwork; - @Override - public void close() { - shutdown(); - } - - public void shutdown() { - serverNetwork.shutdown(); - clientNetwork.shutdown(); - } - } - - protected @NotNull TestNetwork buildStringNetwork() { - return buildStringNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), - NetworkConfig.DEFAULT_CLIENT, - new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) - ); - } - - protected @NotNull TestNetwork buildStringSSLNetwork( - @NotNull SSLContext serverSSLContext, - @NotNull SSLContext clientSSLContext - ) { - return buildStringSSLNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), - serverSSLContext, - NetworkConfig.DEFAULT_CLIENT, - new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), - clientSSLContext - ); - } - - protected @NotNull TestNetwork buildStringNetwork( - @NotNull BufferAllocator serverBufferAllocator, - @NotNull BufferAllocator clientBufferAllocator - ) { - return buildStringNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - serverBufferAllocator, - NetworkConfig.DEFAULT_CLIENT, - clientBufferAllocator - ); - } - - protected @NotNull TestNetwork buildStringNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator - ) { - return buildStringNetwork( - serverNetworkConfig, - serverBufferAllocator, - NetworkConfig.DEFAULT_CLIENT, - new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) - ); - } - - protected @NotNull TestNetwork buildStringNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator, - @NotNull NetworkConfig clientNetworkConfig, - @NotNull BufferAllocator clientBufferAllocator - ) { - - var asyncClientToServer = new CompletableFuture(); - var asyncServerToClient = new CompletableFuture(); - - var serverNetwork = NetworkFactory.newStringDataServerNetwork(serverNetworkConfig, serverBufferAllocator); - var serverAddress = serverNetwork.start(); - - serverNetwork.onAccept(asyncServerToClient::complete); - - var clientNetwork = NetworkFactory.newStringDataClientNetwork(clientNetworkConfig, clientBufferAllocator); - clientNetwork.connect(serverAddress) - .thenApply(asyncClientToServer::complete); - - return new TestNetwork<>( - serverNetworkConfig, - clientNetworkConfig, - asyncClientToServer.join(), - asyncServerToClient.join(), - serverNetwork, - clientNetwork - ); - } - - protected @NotNull TestNetwork buildStringSSLNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator, - @NotNull SSLContext serverSSLContext, - @NotNull NetworkConfig clientNetworkConfig, - @NotNull BufferAllocator clientBufferAllocator, - @NotNull SSLContext clientSSLContext - ) { - - var asyncClientToServer = new CompletableFuture(); - var asyncServerToClient = new CompletableFuture(); - - var serverNetwork = NetworkFactory.newStringDataSSLServerNetwork( - serverNetworkConfig, - serverBufferAllocator, - serverSSLContext - ); - - var serverAddress = serverNetwork.start(); - serverNetwork.onAccept(asyncServerToClient::complete); - - var clientNetwork = NetworkFactory.newStringDataSSLClientNetwork( - clientNetworkConfig, - clientBufferAllocator, - clientSSLContext - ); - - clientNetwork.connect(serverAddress) - .thenApply(asyncClientToServer::complete); - - return new TestNetwork<>( - serverNetworkConfig, - clientNetworkConfig, - asyncClientToServer.join(), - asyncServerToClient.join(), - serverNetwork, - clientNetwork - ); - } - - protected @NotNull TestNetwork buildDefaultNetwork( - @NotNull ReadablePacketRegistry serverPacketRegistry, - @NotNull ReadablePacketRegistry clientPacketRegistry - ) { - return buildDefaultNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), - serverPacketRegistry, - NetworkConfig.DEFAULT_CLIENT, - new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), - clientPacketRegistry - ); - } - - protected @NotNull TestNetwork buildDefaultNetwork( - @NotNull BufferAllocator serverBufferAllocator, - @NotNull ReadablePacketRegistry serverPacketRegistry, - @NotNull BufferAllocator clientBufferAllocator, - @NotNull ReadablePacketRegistry clientPacketRegistry - ) { - return buildDefaultNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - serverBufferAllocator, - serverPacketRegistry, - NetworkConfig.DEFAULT_CLIENT, - clientBufferAllocator, - clientPacketRegistry - ); + @Override + public void close() { + shutdown(); } - protected @NotNull TestNetwork buildDefaultNetwork( - @NotNull ServerNetworkConfig serverNetworkConfig, - @NotNull BufferAllocator serverBufferAllocator, - @NotNull ReadablePacketRegistry serverPacketRegistry, - @NotNull NetworkConfig clientNetworkConfig, - @NotNull BufferAllocator clientBufferAllocator, - @NotNull ReadablePacketRegistry clientPacketRegistry - ) { - - var asyncClientToServer = new CompletableFuture(); - var asyncServerToClient = new CompletableFuture(); - - var serverNetwork = NetworkFactory.newDefaultServerNetwork( - serverNetworkConfig, - serverBufferAllocator, - serverPacketRegistry - ); - var serverAddress = serverNetwork.start(); - - serverNetwork.onAccept(asyncServerToClient::complete); - - var clientNetwork = NetworkFactory.newDefaultClientNetwork( - clientNetworkConfig, - clientBufferAllocator, - clientPacketRegistry - ); - clientNetwork.connect(serverAddress) - .thenApply(asyncClientToServer::complete); - - return new TestNetwork<>( - serverNetworkConfig, - clientNetworkConfig, - asyncClientToServer.join(), - asyncServerToClient.join(), - serverNetwork, - clientNetwork - ); + public void shutdown() { + serverNetwork.shutdown(); + clientNetwork.shutdown(); } + } + + protected @NotNull TestNetwork buildStringNetwork() { + return buildStringNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), + NetworkConfig.DEFAULT_CLIENT, + new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT)); + } + + protected @NotNull TestNetwork buildStringSSLNetwork( + @NotNull SSLContext serverSSLContext, + @NotNull SSLContext clientSSLContext) { + return buildStringSSLNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), + serverSSLContext, + NetworkConfig.DEFAULT_CLIENT, + new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), + clientSSLContext); + } + + protected @NotNull TestNetwork buildStringNetwork( + @NotNull BufferAllocator serverBufferAllocator, + @NotNull BufferAllocator clientBufferAllocator) { + return buildStringNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + serverBufferAllocator, + NetworkConfig.DEFAULT_CLIENT, + clientBufferAllocator); + } + + protected @NotNull TestNetwork buildStringNetwork( + @NotNull ServerNetworkConfig serverNetworkConfig, + @NotNull BufferAllocator serverBufferAllocator) { + return buildStringNetwork( + serverNetworkConfig, + serverBufferAllocator, + NetworkConfig.DEFAULT_CLIENT, + new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT)); + } + + protected @NotNull TestNetwork buildStringNetwork( + @NotNull ServerNetworkConfig serverNetworkConfig, + @NotNull BufferAllocator serverBufferAllocator, + @NotNull NetworkConfig clientNetworkConfig, + @NotNull BufferAllocator clientBufferAllocator) { + + var asyncClientToServer = new CompletableFuture(); + var asyncServerToClient = new CompletableFuture(); + + var serverNetwork = NetworkFactory.newStringDataServerNetwork(serverNetworkConfig, serverBufferAllocator); + var serverAddress = serverNetwork.start(); + + serverNetwork.onAccept(asyncServerToClient::complete); + + var clientNetwork = NetworkFactory.newStringDataClientNetwork(clientNetworkConfig, clientBufferAllocator); + clientNetwork + .connect(serverAddress) + .thenApply(asyncClientToServer::complete); + + return new TestNetwork<>( + serverNetworkConfig, + clientNetworkConfig, + asyncClientToServer.join(), + asyncServerToClient.join(), + serverNetwork, + clientNetwork); + } + + protected @NotNull TestNetwork buildStringSSLNetwork( + @NotNull ServerNetworkConfig serverNetworkConfig, + @NotNull BufferAllocator serverBufferAllocator, + @NotNull SSLContext serverSSLContext, + @NotNull NetworkConfig clientNetworkConfig, + @NotNull BufferAllocator clientBufferAllocator, + @NotNull SSLContext clientSSLContext) { + + var asyncClientToServer = new CompletableFuture(); + var asyncServerToClient = new CompletableFuture(); + + var serverNetwork = NetworkFactory.newStringDataSSLServerNetwork( + serverNetworkConfig, + serverBufferAllocator, + serverSSLContext); + + var serverAddress = serverNetwork.start(); + serverNetwork.onAccept(asyncServerToClient::complete); + + var clientNetwork = NetworkFactory.newStringDataSSLClientNetwork( + clientNetworkConfig, + clientBufferAllocator, + clientSSLContext); + + clientNetwork + .connect(serverAddress) + .thenApply(asyncClientToServer::complete); + + return new TestNetwork<>( + serverNetworkConfig, + clientNetworkConfig, + asyncClientToServer.join(), + asyncServerToClient.join(), + serverNetwork, + clientNetwork); + } + + protected @NotNull TestNetwork buildDefaultNetwork( + @NotNull ReadablePacketRegistry serverPacketRegistry, + @NotNull ReadablePacketRegistry clientPacketRegistry) { + return buildDefaultNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), + serverPacketRegistry, + NetworkConfig.DEFAULT_CLIENT, + new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), + clientPacketRegistry); + } + + protected @NotNull TestNetwork buildDefaultNetwork( + @NotNull BufferAllocator serverBufferAllocator, + @NotNull ReadablePacketRegistry serverPacketRegistry, + @NotNull BufferAllocator clientBufferAllocator, + @NotNull ReadablePacketRegistry clientPacketRegistry) { + return buildDefaultNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + serverBufferAllocator, + serverPacketRegistry, + NetworkConfig.DEFAULT_CLIENT, + clientBufferAllocator, + clientPacketRegistry); + } + + protected @NotNull TestNetwork buildDefaultNetwork( + @NotNull ServerNetworkConfig serverNetworkConfig, + @NotNull BufferAllocator serverBufferAllocator, + @NotNull ReadablePacketRegistry serverPacketRegistry, + @NotNull NetworkConfig clientNetworkConfig, + @NotNull BufferAllocator clientBufferAllocator, + @NotNull ReadablePacketRegistry clientPacketRegistry) { + + var asyncClientToServer = new CompletableFuture(); + var asyncServerToClient = new CompletableFuture(); + + var serverNetwork = NetworkFactory.newDefaultServerNetwork( + serverNetworkConfig, + serverBufferAllocator, + serverPacketRegistry); + var serverAddress = serverNetwork.start(); + + serverNetwork.onAccept(asyncServerToClient::complete); + + var clientNetwork = NetworkFactory.newDefaultClientNetwork( + clientNetworkConfig, + clientBufferAllocator, + clientPacketRegistry); + clientNetwork + .connect(serverAddress) + .thenApply(asyncClientToServer::complete); + + return new TestNetwork<>( + serverNetworkConfig, + clientNetworkConfig, + asyncClientToServer.join(), + asyncServerToClient.join(), + serverNetwork, + clientNetwork); + } } diff --git a/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java index 765d4403..05a37d60 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/DefaultNetworkTest.java @@ -39,237 +39,239 @@ */ public class DefaultNetworkTest extends BaseNetworkTest { - private static final Logger LOGGER = LoggerManager.getLogger(DefaultNetworkTest.class); - - // client packets - interface ClientPackets { - - @RequiredArgsConstructor - @PacketDescription(id = 1) - class RequestEchoMessage extends DefaultWritablePacket { - - private final String message; - - @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { - super.writeImpl(buffer); - writeString(buffer, message); - } - } - - @PacketDescription(id = 2) - class RequestServerTime extends DefaultWritablePacket { - } - - @ToString - @RequiredArgsConstructor - @PacketDescription(id = 3) - class ResponseEchoMessage extends DefaultReadablePacket { - - @Getter - private volatile String message; - - @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { - super.readImpl(connection, buffer); - message = readString(buffer); - } - } - - @ToString - @PacketDescription(id = 4) - class ResponseServerTime extends DefaultReadablePacket { - - @Getter - private volatile LocalDateTime localDateTime; - - @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { - super.readImpl(connection, buffer); - localDateTime = LocalDateTime.ofEpochSecond( - readLong(buffer), - 0, - ZoneOffset.ofTotalSeconds(readInt(buffer)) - ); - } - } - } + private static final Logger LOGGER = LoggerManager.getLogger(DefaultNetworkTest.class); - // server packets - interface ServerPackets { - - @ToString - @PacketDescription(id = 1) - class RequestEchoMessage extends DefaultReadablePacket { - - private volatile String message; - - @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { - super.readImpl(connection, buffer); - message = readString(buffer); - } - - @Override - protected void executeImpl(@NotNull DefaultConnection connection) { - super.executeImpl(connection); - connection.send(new ResponseEchoMessage(message)); - } - } - - @ToString - @PacketDescription(id = 2) - class RequestServerTime extends DefaultReadablePacket { - - @Override - protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { - super.readImpl(connection, buffer); - } - - @Override - protected void executeImpl(@NotNull DefaultConnection connection) { - super.executeImpl(connection); - connection.send(new ResponseServerTime()); - } - } - - @RequiredArgsConstructor - @PacketDescription(id = 3) - class ResponseEchoMessage extends DefaultWritablePacket { - - private final String message; - - @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { - super.writeImpl(buffer); - writeString(buffer, "Echo: " + message); - } - } - - @PacketDescription(id = 4) - class ResponseServerTime extends DefaultWritablePacket { - - @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { - super.writeImpl(buffer); - var dateTime = ZonedDateTime.now(); - writeLong(buffer, dateTime.toEpochSecond()); - writeInt(buffer, dateTime.getOffset().getTotalSeconds()); - } - } - } + // client packets + interface ClientPackets { + + @RequiredArgsConstructor + @PacketDescription(id = 1) + class RequestEchoMessage extends DefaultWritablePacket { - @Test - @SneakyThrows - void echoNetworkTest() { - - var serverNetwork = newDefaultServerNetwork(ReadablePacketRegistry.of(DefaultReadablePacket.class, - ServerPackets.RequestEchoMessage.class, - ServerPackets.RequestServerTime.class - )); - var serverAddress = serverNetwork.start(); - var counter = new CountDownLatch(90); - - serverNetwork.accepted() - .flatMap(Connection::receivedEvents) - .doOnNext(event -> event.packet.execute(event.connection)) - .subscribe(event -> LOGGER.info("Received from client: " + event.packet)); - - var clientNetwork = newDefaultClientNetwork(ReadablePacketRegistry.of(DefaultReadablePacket.class, - ClientPackets.ResponseEchoMessage.class, - ClientPackets.ResponseServerTime.class - )); - clientNetwork.connected(serverAddress) - .doOnNext(connection -> IntStream.range(10, 100) - .forEach(length -> { - if(length % 2 == 0) { - connection.send(new ClientPackets.RequestServerTime()); - } else { - connection.send(new ClientPackets.RequestEchoMessage(StringUtils.generate(length))); - } - })) - .flatMapMany(Connection::receivedEvents) - .subscribe(event -> { - LOGGER.info("Received from server: " + event.packet); - counter.countDown(); - }); - - Assertions.assertTrue( - counter.await(10000, TimeUnit.MILLISECONDS), - "Still wait for " + counter.getCount() + " packets..." - ); - - clientNetwork.shutdown(); - serverNetwork.shutdown(); + private final String message; + + @Override + protected void writeImpl(@NotNull ByteBuffer buffer) { + super.writeImpl(buffer); + writeString(buffer, message); + } } - @Test - void shouldNotUseMappedBuffers() { + @PacketDescription(id = 2) + class RequestServerTime extends DefaultWritablePacket {} + + @ToString + @RequiredArgsConstructor + @PacketDescription(id = 3) + class ResponseEchoMessage extends DefaultReadablePacket { + + @Getter + private volatile String message; - var serverPacketRegistry = ReadablePacketRegistry.of(DefaultReadablePacket.class, - ServerPackets.RequestEchoMessage.class, - ServerPackets.RequestServerTime.class - ); - var clientPacketRegistry = ReadablePacketRegistry.of( - DefaultReadablePacket.class, - ClientPackets.ResponseEchoMessage.class, - ClientPackets.ResponseServerTime.class - ); + @Override + protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + super.readImpl(connection, buffer); + message = readString(buffer); + } + } - var serverAllocator = new DefaultBufferAllocator(DEFAULT_SERVER) { + @ToString + @PacketDescription(id = 4) + class ResponseServerTime extends DefaultReadablePacket { - @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { - throw new RuntimeException(); - } - }; + @Getter + private volatile LocalDateTime localDateTime; - var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) { + @Override + protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + super.readImpl(connection, buffer); + localDateTime = LocalDateTime.ofEpochSecond(readLong(buffer), 0, ZoneOffset.ofTotalSeconds(readInt(buffer))); + } + } + } - @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { - throw new RuntimeException(); - } - }; + // server packets + interface ServerPackets { - int packetCount = 200; + @ToString + @PacketDescription(id = 1) + class RequestEchoMessage extends DefaultReadablePacket { - try (var testNetwork = buildDefaultNetwork( - serverAllocator, - serverPacketRegistry, - clientAllocator, - clientPacketRegistry - )) { + private volatile String message; - var bufferSize = testNetwork.serverNetworkConfig - .getReadBufferSize() / 3; + @Override + protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + super.readImpl(connection, buffer); + message = readString(buffer); + } - var random = ThreadLocalRandom.current(); + @Override + protected void executeImpl(@NotNull DefaultConnection connection) { + super.executeImpl(connection); + connection.send(new ResponseEchoMessage(message)); + } + } - var clientToServer = testNetwork.clientToServer; - var serverToClient = testNetwork.serverToClient; + @ToString + @PacketDescription(id = 2) + class RequestServerTime extends DefaultReadablePacket { - var pendingPacketsOnServer = serverToClient.receivedPackets() - .buffer(packetCount); + @Override + protected void readImpl(@NotNull DefaultConnection connection, @NotNull ByteBuffer buffer) { + super.readImpl(connection, buffer); + } - var messages = IntStream.range(0, packetCount) - .mapToObj(value -> StringUtils.generate(random.nextInt(0, bufferSize))) - .peek(message -> clientToServer.send(new ClientPackets.RequestEchoMessage(message))) - .collect(toList()); + @Override + protected void executeImpl(@NotNull DefaultConnection connection) { + super.executeImpl(connection); + connection.send(new ResponseServerTime()); + } + } - var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); + @RequiredArgsConstructor + @PacketDescription(id = 3) + class ResponseEchoMessage extends DefaultWritablePacket { - Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); + private final String message; - var wrongPacket = receivedPackets.stream() - .filter(ClientPackets.ResponseEchoMessage.class::isInstance) - .map(ClientPackets.ResponseEchoMessage.class::cast) - .filter(packet -> messages.stream() - .noneMatch(message -> message.equals(packet.getMessage()))) - .findFirst() - .orElse(null); + @Override + protected void writeImpl(@NotNull ByteBuffer buffer) { + super.writeImpl(buffer); + writeString(buffer, "Echo: " + message); + } + } - Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); - } + @PacketDescription(id = 4) + class ResponseServerTime extends DefaultWritablePacket { + + @Override + protected void writeImpl(@NotNull ByteBuffer buffer) { + super.writeImpl(buffer); + var dateTime = ZonedDateTime.now(); + writeLong(buffer, dateTime.toEpochSecond()); + writeInt( + buffer, + dateTime + .getOffset() + .getTotalSeconds()); + } + } + } + + @Test + @SneakyThrows + void echoNetworkTest() { + + var serverNetwork = newDefaultServerNetwork(ReadablePacketRegistry.of( + DefaultReadablePacket.class, + ServerPackets.RequestEchoMessage.class, + ServerPackets.RequestServerTime.class)); + var serverAddress = serverNetwork.start(); + var counter = new CountDownLatch(90); + + serverNetwork + .accepted() + .flatMap(Connection::receivedEvents) + .doOnNext(event -> event.packet.execute(event.connection)) + .subscribe(event -> LOGGER.info("Received from client: " + event.packet)); + + var clientNetwork = newDefaultClientNetwork(ReadablePacketRegistry.of( + DefaultReadablePacket.class, + ClientPackets.ResponseEchoMessage.class, + ClientPackets.ResponseServerTime.class)); + clientNetwork + .connected(serverAddress) + .doOnNext(connection -> IntStream + .range(10, 100) + .forEach(length -> { + if (length % 2 == 0) { + connection.send(new ClientPackets.RequestServerTime()); + } else { + connection.send(new ClientPackets.RequestEchoMessage(StringUtils.generate(length))); + } + })) + .flatMapMany(Connection::receivedEvents) + .subscribe(event -> { + LOGGER.info("Received from server: " + event.packet); + counter.countDown(); + }); + + Assertions.assertTrue( + counter.await(10000, TimeUnit.MILLISECONDS), + "Still wait for " + counter.getCount() + " packets..."); + + clientNetwork.shutdown(); + serverNetwork.shutdown(); + } + + @Test + void shouldNotUseMappedBuffers() { + + var serverPacketRegistry = ReadablePacketRegistry.of( + DefaultReadablePacket.class, + ServerPackets.RequestEchoMessage.class, + ServerPackets.RequestServerTime.class); + var clientPacketRegistry = ReadablePacketRegistry.of( + DefaultReadablePacket.class, + ClientPackets.ResponseEchoMessage.class, + ClientPackets.ResponseServerTime.class); + + var serverAllocator = new DefaultBufferAllocator(DEFAULT_SERVER) { + + @Override + public @NotNull ByteBuffer takeBuffer(int bufferSize) { + throw new RuntimeException(); + } + }; + + var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) { + + @Override + public @NotNull ByteBuffer takeBuffer(int bufferSize) { + throw new RuntimeException(); + } + }; + + int packetCount = 200; + + try (var testNetwork = buildDefaultNetwork( + serverAllocator, + serverPacketRegistry, + clientAllocator, + clientPacketRegistry)) { + + var bufferSize = testNetwork.serverNetworkConfig.getReadBufferSize() / 3; + + var random = ThreadLocalRandom.current(); + + var clientToServer = testNetwork.clientToServer; + var serverToClient = testNetwork.serverToClient; + + var pendingPacketsOnServer = serverToClient + .receivedPackets() + .buffer(packetCount); + + var messages = IntStream + .range(0, packetCount) + .mapToObj(value -> StringUtils.generate(random.nextInt(0, bufferSize))) + .peek(message -> clientToServer.send(new ClientPackets.RequestEchoMessage(message))) + .collect(toList()); + + var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); + + Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); + + var wrongPacket = receivedPackets + .stream() + .filter(ClientPackets.ResponseEchoMessage.class::isInstance) + .map(ClientPackets.ResponseEchoMessage.class::cast) + .filter(packet -> messages + .stream() + .noneMatch(message -> message.equals(packet.getMessage()))) + .findFirst() + .orElse(null); + + Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); } + } } diff --git a/rlib-network/src/test/java/javasabr/rlib/network/IdBasedReadablePacketRegistryTest.java b/rlib-network/src/test/java/javasabr/rlib/network/IdBasedReadablePacketRegistryTest.java index 70aa3d4b..601ebc9f 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/IdBasedReadablePacketRegistryTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/IdBasedReadablePacketRegistryTest.java @@ -18,115 +18,106 @@ */ public class IdBasedReadablePacketRegistryTest { - @NoArgsConstructor - @PacketDescription(id = 1) - public static class Impl1 extends DefaultReadablePacket { - } - - @NoArgsConstructor - @PacketDescription(id = 2) - public static class Impl2 extends DefaultReadablePacket { - } - - @NoArgsConstructor - @PacketDescription(id = 3) - public static class Impl3 extends DefaultReadablePacket { - } - - @NoArgsConstructor - private static class PrivateBase extends AbstractIdBasedReadablePacket { - } - - @NoArgsConstructor - @PacketDescription(id = 1) - private static class PrivateImpl1 extends PrivateBase { - } - - @NoArgsConstructor - @PacketDescription(id = 10) - private static class PrivateImpl2 extends PrivateBase { - } - - @NoArgsConstructor - public static class PublicBase extends AbstractIdBasedReadablePacket { - } - - @NoArgsConstructor - @PacketDescription(id = 1) - public static class PublicImpl1 extends PublicBase { - } - - @NoArgsConstructor - @PacketDescription(id = 5) - public static class PublicImpl2 extends PublicBase { - } - - @Test - Object shouldBeCreated() { - return new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class); - } - - @Test - void shouldRegister3PacketsByArray() { - - var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class) - .register(ArrayFactory.asArray(Impl1.class, Impl2.class, Impl3.class)); - - Assertions.assertTrue(registry.findById(1) instanceof Impl1); - Assertions.assertTrue(registry.findById(2) instanceof Impl2); - Assertions.assertTrue(registry.findById(3) instanceof Impl3); - } - - @Test - void shouldRegister3PacketsByVarargs() { - - var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class) - .register(Impl1.class, Impl2.class, Impl3.class); - - Assertions.assertTrue(registry.findById(1) instanceof Impl1); - Assertions.assertTrue(registry.findById(2) instanceof Impl2); - Assertions.assertTrue(registry.findById(3) instanceof Impl3); - } - - @Test - void shouldRegister3PacketsBySingle() { - - var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class) - .register(Impl1.class) - .register(Impl2.class) - .register(Impl3.class); - - Assertions.assertTrue(registry.findById(1) instanceof Impl1); - Assertions.assertTrue(registry.findById(2) instanceof Impl2); - Assertions.assertTrue(registry.findById(3) instanceof Impl3); - } - - @Test - void shouldRegister2PrivatePacketsBySingle() { - - var registry = new IdBasedReadablePacketRegistry<>(PrivateBase.class) - .register(PrivateImpl1.class, PrivateImpl1::new) - .register(PrivateImpl2.class, PrivateImpl2::new); - - Assertions.assertTrue(registry.findById(1) instanceof PrivateImpl1); - Assertions.assertTrue(registry.findById(10) instanceof PrivateImpl2); - } - - @Test - void shouldNotAcceptWrongTypes() { - - var array = ArrayFactory.asArray( - PrivateImpl1.class, - PrivateImpl2.class, - PublicImpl1.class, - PublicImpl2.class - ); - - var registry = new IdBasedReadablePacketRegistry<>(PublicBase.class) - .register(ClassUtils.>>unsafeNNCast(array)); - - Assertions.assertTrue(registry.findById(1) instanceof PublicImpl1); - Assertions.assertThrows(IllegalArgumentException.class, () -> registry.findById(2)); - Assertions.assertTrue(registry.findById(5) instanceof PublicImpl2); - } + @NoArgsConstructor + @PacketDescription(id = 1) + public static class Impl1 extends DefaultReadablePacket {} + + @NoArgsConstructor + @PacketDescription(id = 2) + public static class Impl2 extends DefaultReadablePacket {} + + @NoArgsConstructor + @PacketDescription(id = 3) + public static class Impl3 extends DefaultReadablePacket {} + + @NoArgsConstructor + private static class PrivateBase extends AbstractIdBasedReadablePacket {} + + @NoArgsConstructor + @PacketDescription(id = 1) + private static class PrivateImpl1 extends PrivateBase {} + + @NoArgsConstructor + @PacketDescription(id = 10) + private static class PrivateImpl2 extends PrivateBase {} + + @NoArgsConstructor + public static class PublicBase extends AbstractIdBasedReadablePacket {} + + @NoArgsConstructor + @PacketDescription(id = 1) + public static class PublicImpl1 extends PublicBase {} + + @NoArgsConstructor + @PacketDescription(id = 5) + public static class PublicImpl2 extends PublicBase {} + + @Test + Object shouldBeCreated() { + return new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class); + } + + @Test + void shouldRegister3PacketsByArray() { + + var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class).register(ArrayFactory.asArray( + Impl1.class, + Impl2.class, + Impl3.class)); + + Assertions.assertTrue(registry.findById(1) instanceof Impl1); + Assertions.assertTrue(registry.findById(2) instanceof Impl2); + Assertions.assertTrue(registry.findById(3) instanceof Impl3); + } + + @Test + void shouldRegister3PacketsByVarargs() { + + var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class).register( + Impl1.class, + Impl2.class, + Impl3.class); + + Assertions.assertTrue(registry.findById(1) instanceof Impl1); + Assertions.assertTrue(registry.findById(2) instanceof Impl2); + Assertions.assertTrue(registry.findById(3) instanceof Impl3); + } + + @Test + void shouldRegister3PacketsBySingle() { + + var registry = new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class) + .register(Impl1.class) + .register(Impl2.class) + .register(Impl3.class); + + Assertions.assertTrue(registry.findById(1) instanceof Impl1); + Assertions.assertTrue(registry.findById(2) instanceof Impl2); + Assertions.assertTrue(registry.findById(3) instanceof Impl3); + } + + @Test + void shouldRegister2PrivatePacketsBySingle() { + + var registry = new IdBasedReadablePacketRegistry<>(PrivateBase.class) + .register(PrivateImpl1.class, PrivateImpl1::new) + .register(PrivateImpl2.class, PrivateImpl2::new); + + Assertions.assertTrue(registry.findById(1) instanceof PrivateImpl1); + Assertions.assertTrue(registry.findById(10) instanceof PrivateImpl2); + } + + @Test + void shouldNotAcceptWrongTypes() { + + var array = ArrayFactory.asArray(PrivateImpl1.class, PrivateImpl2.class, PublicImpl1.class, PublicImpl2.class); + + var registry = new IdBasedReadablePacketRegistry<>(PublicBase.class).register(ClassUtils.>>unsafeNNCast( + array)); + + Assertions.assertTrue(registry.findById(1) instanceof PublicImpl1); + Assertions.assertThrows(IllegalArgumentException.class, () -> registry.findById(2)); + Assertions.assertTrue(registry.findById(5) instanceof PublicImpl2); + } } diff --git a/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java index 15ad4277..261b3526 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/StringNetworkTest.java @@ -13,7 +13,7 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; -import javasabr.rlib.common.concurrent.atomic.AtomicInteger; +import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ObjectUtils; import javasabr.rlib.common.util.StringUtils; import javasabr.rlib.logger.api.Logger; @@ -35,355 +35,371 @@ */ public class StringNetworkTest extends BaseNetworkTest { - private static final Logger LOGGER = LoggerManager.getLogger(StringNetworkTest.class); - - @Test - @SneakyThrows - void echoNetworkTest() { - - var serverNetwork = newStringDataServerNetwork(); - var serverAddress = serverNetwork.start(); - var counter = new CountDownLatch(90); - - serverNetwork.accepted() - .flatMap(Connection::receivedEvents) - .subscribe(event -> { - var message = event.packet.getData(); - LOGGER.info("Received from client: " + message); - event.connection.send(new StringWritablePacket("Echo: " + message)); - }); - - var clientNetwork = newStringDataClientNetwork(); - clientNetwork.connected(serverAddress) - .doOnNext(connection -> IntStream.range(10, 100) - .forEach(length -> connection.send(new StringWritablePacket(StringUtils.generate(length))))) - .flatMapMany(Connection::receivedEvents) - .subscribe(event -> { - LOGGER.info("Received from server: " + event.packet.getData()); - counter.countDown(); - }); - - Assertions.assertTrue( - counter.await(10000, TimeUnit.MILLISECONDS), - "Still wait for " + counter.getCount() + " packets..." - ); - - clientNetwork.shutdown(); - serverNetwork.shutdown(); - } - - @Test - void shouldNotUseTempBuffers() { - - var serverAllocator = new DefaultBufferAllocator(DEFAULT_SERVER) { - - @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { - throw new RuntimeException(); - } - }; - - var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) { - - @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { - throw new RuntimeException(); - } - }; - - int packetCount = 200; + private static final Logger LOGGER = LoggerManager.getLogger(StringNetworkTest.class); - try(var testNetwork = buildStringNetwork(serverAllocator, clientAllocator)) { + @Test + @SneakyThrows + void echoNetworkTest() { - var bufferSize = testNetwork.serverNetworkConfig - .getReadBufferSize() / 3; + var serverNetwork = newStringDataServerNetwork(); + var serverAddress = serverNetwork.start(); + var counter = new CountDownLatch(90); - var random = ThreadLocalRandom.current(); - - var clientToServer = testNetwork.clientToServer; - var serverToClient = testNetwork.serverToClient; + serverNetwork + .accepted() + .flatMap(Connection::receivedEvents) + .subscribe(event -> { + var message = event.packet.getData(); + LOGGER.info("Received from client: " + message); + event.connection.send(new StringWritablePacket("Echo: " + message)); + }); - var pendingPacketsOnServer = serverToClient.receivedPackets() - .buffer(packetCount); + var clientNetwork = newStringDataClientNetwork(); + clientNetwork + .connected(serverAddress) + .doOnNext(connection -> IntStream + .range(10, 100) + .forEach(length -> connection.send(new StringWritablePacket(StringUtils.generate(length))))) + .flatMapMany(Connection::receivedEvents) + .subscribe(event -> { + LOGGER.info("Received from server: " + event.packet.getData()); + counter.countDown(); + }); - var messages = IntStream.range(0, packetCount) - .mapToObj(value -> StringUtils.generate(random.nextInt(0, bufferSize))) - .peek(message -> { - LOGGER.info("Send " + message.length() + " symbols to server"); - clientToServer.send(new StringWritablePacket(message)); - }) - .collect(toList()); + Assertions.assertTrue( + counter.await(10000, TimeUnit.MILLISECONDS), + "Still wait for " + counter.getCount() + " packets..."); - var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); + clientNetwork.shutdown(); + serverNetwork.shutdown(); + } - LOGGER.info("Received " + receivedPackets.size() + " packets from client"); + @Test + void shouldNotUseTempBuffers() { - Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); + var serverAllocator = new DefaultBufferAllocator(DEFAULT_SERVER) { - var wrongPacket = receivedPackets.stream() - .filter(packet -> messages.stream() - .noneMatch(message -> message.equals(packet.getData()))) - .findFirst() - .orElse(null); + @Override + public @NotNull ByteBuffer takeBuffer(int bufferSize) { + throw new RuntimeException(); + } + }; - Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); - } - } + var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT) { - @Test - void shouldReceiveManyPacketsFromSmallToBigSize() { + @Override + public @NotNull ByteBuffer takeBuffer(int bufferSize) { + throw new RuntimeException(); + } + }; - int packetCount = 200; + int packetCount = 200; - try(var testNetwork = buildStringNetwork()) { + try (var testNetwork = buildStringNetwork(serverAllocator, clientAllocator)) { - var bufferSize = testNetwork.serverNetworkConfig - .getReadBufferSize(); + var bufferSize = testNetwork.serverNetworkConfig.getReadBufferSize() / 3; - var random = ThreadLocalRandom.current(); + var random = ThreadLocalRandom.current(); - var clientToServer = testNetwork.clientToServer; - var serverToClient = testNetwork.serverToClient; + var clientToServer = testNetwork.clientToServer; + var serverToClient = testNetwork.serverToClient; - var pendingPacketsOnServer = serverToClient.receivedPackets() - .buffer(packetCount); + var pendingPacketsOnServer = serverToClient + .receivedPackets() + .buffer(packetCount); - var messages = IntStream.range(0, packetCount) - .mapToObj(value -> { - var length = value % 3 == 0 ? bufferSize : random.nextInt(0, bufferSize / 2 - 1); - return StringUtils.generate(length); - }) - .peek(message -> { - LOGGER.info("Send " + message.length() + " symbols to server"); - clientToServer.send(new StringWritablePacket(message)); - }) - .collect(toList()); + var messages = IntStream + .range(0, packetCount) + .mapToObj(value -> StringUtils.generate(random.nextInt(0, bufferSize))) + .peek(message -> { + LOGGER.info("Send " + message.length() + " symbols to server"); + clientToServer.send(new StringWritablePacket(message)); + }) + .collect(toList()); - var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); + var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); - LOGGER.info("Received " + receivedPackets.size() + " packets from client"); + LOGGER.info("Received " + receivedPackets.size() + " packets from client"); - Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); + Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); - var wrongPacket = receivedPackets.stream() - .filter(packet -> messages.stream() - .noneMatch(message -> message.equals(packet.getData()))) - .findFirst() - .orElse(null); + var wrongPacket = receivedPackets + .stream() + .filter(packet -> messages + .stream() + .noneMatch(message -> message.equals(packet.getData()))) + .findFirst() + .orElse(null); - Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); - } + Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); } + } - @Test - void shouldSendBiggerPacketThanWriteBuffer() { - - int packetCount = 10_000; - - try(var testNetwork = buildStringNetwork()) { - - var bufferSize = testNetwork.clientNetworkConfig - .getWriteBufferSize(); + @Test + void shouldReceiveManyPacketsFromSmallToBigSize() { - var random = ThreadLocalRandom.current(); + int packetCount = 200; - var clientToServer = testNetwork.clientToServer; - var serverToClient = testNetwork.serverToClient; + try (var testNetwork = buildStringNetwork()) { - var pendingPacketsOnServer = serverToClient.receivedPackets() - .buffer(packetCount); + var bufferSize = testNetwork.serverNetworkConfig.getReadBufferSize(); - var messages = IntStream.range(0, packetCount) - .mapToObj(value -> { + var random = ThreadLocalRandom.current(); - var length = random.nextBoolean() ? - random.nextInt(bufferSize, bufferSize * 10) : - random.nextInt(0, 200); + var clientToServer = testNetwork.clientToServer; + var serverToClient = testNetwork.serverToClient; - return StringUtils.generate(length); - }) - .peek(message -> { - LOGGER.info("Send " + message.length() + " symbols to server"); - clientToServer.send(new StringWritablePacket(message)); - }) - .collect(toList()); + var pendingPacketsOnServer = serverToClient + .receivedPackets() + .buffer(packetCount); - var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); + var messages = IntStream + .range(0, packetCount) + .mapToObj(value -> { + var length = value % 3 == 0 ? bufferSize : random.nextInt(0, bufferSize / 2 - 1); + return StringUtils.generate(length); + }) + .peek(message -> { + LOGGER.info("Send " + message.length() + " symbols to server"); + clientToServer.send(new StringWritablePacket(message)); + }) + .collect(toList()); - LOGGER.info("Received " + receivedPackets.size() + " packets from client"); + var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); - Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); + LOGGER.info("Received " + receivedPackets.size() + " packets from client"); - var wrongPacket = receivedPackets.stream() - .filter(packet -> messages.stream() - .noneMatch(message -> message.equals(packet.getData()))) - .findFirst() - .orElse(null); + Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); - Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); - } - } - - @Test - @SneakyThrows - void testServerWithMultiplyClients() { - - //LoggerManager.enable(AbstractPacketWriter.class, LoggerLevel.DEBUG); - - var serverConfig = SimpleServerNetworkConfig.builder() - .threadGroupSize(10) - .build(); - - var serverAllocator = new DefaultBufferAllocator(serverConfig); - var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT); - - var clientCount = 100; - var packetsPerClient = 100; - var counter = new CountDownLatch(clientCount * packetsPerClient); - var minMessageLength = 10; - var maxMessageLength = (int) (DEFAULT_SERVER.getReadBufferSize() * 1.5); - var sentPacketsToServer = new AtomicInteger(); - var receivedPacketsOnServer = new AtomicInteger(); - var receivedPacketsOnClients = new AtomicInteger(); - - var serverNetwork = newStringDataServerNetwork(serverConfig, serverAllocator); - var serverAddress = serverNetwork.start(); + var wrongPacket = receivedPackets + .stream() + .filter(packet -> messages + .stream() + .noneMatch(message -> message.equals(packet.getData()))) + .findFirst() + .orElse(null); - serverNetwork.accepted() - .flatMap(Connection::receivedEvents) - .doOnNext(event -> receivedPacketsOnServer.incrementAndGet()) - .subscribe(event -> event.connection.send(newMessage(minMessageLength, maxMessageLength))); - - Flux.fromStream(IntStream.range(0, clientCount) - .mapToObj(value -> newStringDataClientNetwork(NetworkConfig.DEFAULT_CLIENT, clientAllocator))) - .doOnDiscard(ClientNetwork.class, Network::shutdown) - .flatMap(client -> client.connected(serverAddress)) - .flatMap(connection -> { - - var receivedEvents = connection.receivedEvents(); - - for (int i = 0; i < packetsPerClient; i++) { - connection.send(newMessage(minMessageLength, maxMessageLength)); - sentPacketsToServer.incrementAndGet(); - } - - return receivedEvents; - }) - .subscribe(event -> { - receivedPacketsOnClients.incrementAndGet(); - counter.countDown(); - }); - - Assertions.assertTrue( - counter.await(10000, TimeUnit.MILLISECONDS), - "Still wait for " + counter.getCount() + " packets... " + - "Sent packets to server: " + sentPacketsToServer + ", " + - "Received packets on server: " + receivedPacketsOnServer + ", " + - "Received packets on clients: " + receivedPacketsOnClients - ); - - serverNetwork.shutdown(); + Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); } + } - @Test - @SneakyThrows - void testServerWithMultiplyClientsUsingOldApi() { - - var serverNetwork = newStringDataServerNetwork(SimpleServerNetworkConfig.builder() - .threadGroupSize(10) - .build()); - - var serverAddress = serverNetwork.start(); - var clientCount = 100; - var packetsPerClient = 1000; - var counter = new CountDownLatch(clientCount * packetsPerClient); - var minMessageLength = 10; - var maxMessageLength = (int) (DEFAULT_SERVER.getReadBufferSize() * 1.5); - var sentPacketsToServer = new AtomicInteger(); - var receivedPacketsOnServer = new AtomicInteger(); - var receivedPacketsOnClients = new AtomicInteger(); - var connectedClients = new CountDownLatch(clientCount); - - serverNetwork.onAccept(connection -> { - connection.onReceive((con, packet) -> { - receivedPacketsOnServer.incrementAndGet(); - con.send(newMessage(minMessageLength, maxMessageLength)); - }); - connectedClients.countDown(); - }); + @Test + void shouldSendBiggerPacketThanWriteBuffer() { - var clients = IntStream.range(0, clientCount) - .mapToObj(value -> newStringDataClientNetwork()) - .peek(client -> client.connect(serverAddress)) - .collect(toList()); - - connectedClients.await(); - - clients.stream() - .map(ClientNetwork::getCurrentConnection) - .filter(Objects::nonNull) - .peek(connection -> connection.onReceive((con, packet) -> { - receivedPacketsOnClients.incrementAndGet(); - counter.countDown(); - })) - .forEach(connection -> IntStream.range(0, packetsPerClient) - .peek(value -> connection.send(newMessage(minMessageLength, maxMessageLength))) - .forEach(val -> sentPacketsToServer.incrementAndGet()) - ); - - Assertions.assertTrue( - counter.await(5, TimeUnit.SECONDS), - "Still wait for " + counter.getCount() + " packets... " + - "Sent packets to server: " + sentPacketsToServer + ", " + - "Received packets on server: " + receivedPacketsOnServer + ", " + - "Received packets on clients: " + receivedPacketsOnClients - ); - - clients.forEach(Network::shutdown); - serverNetwork.shutdown(); - } + int packetCount = 10_000; - @Test - void shouldGetAllPacketWithFeedback() { + try (var testNetwork = buildStringNetwork()) { - int packetCount = 200; + var bufferSize = testNetwork.clientNetworkConfig.getWriteBufferSize(); - try(var testNetwork = buildStringNetwork()) { + var random = ThreadLocalRandom.current(); - var bufferSize = testNetwork.serverNetworkConfig - .getReadBufferSize() / 3; + var clientToServer = testNetwork.clientToServer; + var serverToClient = testNetwork.serverToClient; - var random = ThreadLocalRandom.current(); + var pendingPacketsOnServer = serverToClient + .receivedPackets() + .buffer(packetCount); - var clientToServer = testNetwork.clientToServer; - var serverToClient = testNetwork.serverToClient; + var messages = IntStream + .range(0, packetCount) + .mapToObj(value -> { - var pendingPacketsOnServer = serverToClient.receivedPackets() - .buffer(packetCount); + var length = random.nextBoolean() ? random.nextInt(bufferSize, bufferSize * 10) : random.nextInt(0, 200); - var asyncResults = IntStream.range(0, packetCount) - .mapToObj(value -> StringUtils.generate(random.nextInt(0, bufferSize))) - .map(message -> clientToServer.sendWithFeedback(new StringWritablePacket(message))) - .collect(toList()); + return StringUtils.generate(length); + }) + .peek(message -> { + LOGGER.info("Send " + message.length() + " symbols to server"); + clientToServer.send(new StringWritablePacket(message)); + }) + .collect(toList()); - CompletableFuture.allOf(asyncResults.toArray(CompletableFuture[]::new)).join(); + var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5))); - var notSentPacket = asyncResults.stream() - .map(CompletableFuture::join) - .filter(sent -> !sent) - .findFirst() - .orElse(null); + LOGGER.info("Received " + receivedPackets.size() + " packets from client"); - Assertions.assertNull(notSentPacket, "Found not sent packets..."); + Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); - // so all packets are already sent, we should not wait for long time to get result - var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofMillis(100))); + var wrongPacket = receivedPackets + .stream() + .filter(packet -> messages + .stream() + .noneMatch(message -> message.equals(packet.getData()))) + .findFirst() + .orElse(null); - Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); - } + Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); } + } + + @Test + @SneakyThrows + void testServerWithMultiplyClients() { + + //LoggerManager.enable(AbstractPacketWriter.class, LoggerLevel.DEBUG); + + var serverConfig = SimpleServerNetworkConfig + .builder() + .threadGroupSize(10) + .build(); + + var serverAllocator = new DefaultBufferAllocator(serverConfig); + var clientAllocator = new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT); + + var clientCount = 100; + var packetsPerClient = 100; + var counter = new CountDownLatch(clientCount * packetsPerClient); + var minMessageLength = 10; + var maxMessageLength = (int) (DEFAULT_SERVER.getReadBufferSize() * 1.5); + var sentPacketsToServer = new ReusableAtomicInteger(); + var receivedPacketsOnServer = new ReusableAtomicInteger(); + var receivedPacketsOnClients = new ReusableAtomicInteger(); + + var serverNetwork = newStringDataServerNetwork(serverConfig, serverAllocator); + var serverAddress = serverNetwork.start(); + + serverNetwork + .accepted() + .flatMap(Connection::receivedEvents) + .doOnNext(event -> receivedPacketsOnServer.incrementAndGet()) + .subscribe(event -> event.connection.send(newMessage(minMessageLength, maxMessageLength))); + + Flux + .fromStream(IntStream + .range(0, clientCount) + .mapToObj(value -> newStringDataClientNetwork(NetworkConfig.DEFAULT_CLIENT, clientAllocator))) + .doOnDiscard(ClientNetwork.class, Network::shutdown) + .flatMap(client -> client.connected(serverAddress)) + .flatMap(connection -> { + + var receivedEvents = connection.receivedEvents(); + + for (int i = 0; i < packetsPerClient; i++) { + connection.send(newMessage(minMessageLength, maxMessageLength)); + sentPacketsToServer.incrementAndGet(); + } + + return receivedEvents; + }) + .subscribe(event -> { + receivedPacketsOnClients.incrementAndGet(); + counter.countDown(); + }); - private static @NotNull StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { - return new StringWritablePacket(StringUtils.generate(minMessageLength, maxMessageLength)); + Assertions.assertTrue( + counter.await(10000, TimeUnit.MILLISECONDS), + "Still wait for " + counter.getCount() + " packets... " + "Sent packets to server: " + sentPacketsToServer + + ", " + "Received packets on server: " + receivedPacketsOnServer + ", " + "Received packets on clients: " + + receivedPacketsOnClients); + + serverNetwork.shutdown(); + } + + @Test + @SneakyThrows + void testServerWithMultiplyClientsUsingOldApi() { + + var serverNetwork = newStringDataServerNetwork(SimpleServerNetworkConfig + .builder() + .threadGroupSize(10) + .build()); + + var serverAddress = serverNetwork.start(); + var clientCount = 100; + var packetsPerClient = 1000; + var counter = new CountDownLatch(clientCount * packetsPerClient); + var minMessageLength = 10; + var maxMessageLength = (int) (DEFAULT_SERVER.getReadBufferSize() * 1.5); + var sentPacketsToServer = new ReusableAtomicInteger(); + var receivedPacketsOnServer = new ReusableAtomicInteger(); + var receivedPacketsOnClients = new ReusableAtomicInteger(); + var connectedClients = new CountDownLatch(clientCount); + + serverNetwork.onAccept(connection -> { + connection.onReceive((con, packet) -> { + receivedPacketsOnServer.incrementAndGet(); + con.send(newMessage(minMessageLength, maxMessageLength)); + }); + connectedClients.countDown(); + }); + + var clients = IntStream + .range(0, clientCount) + .mapToObj(value -> newStringDataClientNetwork()) + .peek(client -> client.connect(serverAddress)) + .collect(toList()); + + connectedClients.await(); + + clients + .stream() + .map(ClientNetwork::getCurrentConnection) + .filter(Objects::nonNull) + .peek(connection -> connection.onReceive((con, packet) -> { + receivedPacketsOnClients.incrementAndGet(); + counter.countDown(); + })) + .forEach(connection -> IntStream + .range(0, packetsPerClient) + .peek(value -> connection.send(newMessage(minMessageLength, maxMessageLength))) + .forEach(val -> sentPacketsToServer.incrementAndGet())); + + Assertions.assertTrue( + counter.await(5, TimeUnit.SECONDS), + "Still wait for " + counter.getCount() + " packets... " + "Sent packets to server: " + sentPacketsToServer + + ", " + "Received packets on server: " + receivedPacketsOnServer + ", " + "Received packets on clients: " + + receivedPacketsOnClients); + + clients.forEach(Network::shutdown); + serverNetwork.shutdown(); + } + + @Test + void shouldGetAllPacketWithFeedback() { + + int packetCount = 200; + + try (var testNetwork = buildStringNetwork()) { + + var bufferSize = testNetwork.serverNetworkConfig.getReadBufferSize() / 3; + + var random = ThreadLocalRandom.current(); + + var clientToServer = testNetwork.clientToServer; + var serverToClient = testNetwork.serverToClient; + + var pendingPacketsOnServer = serverToClient + .receivedPackets() + .buffer(packetCount); + + var asyncResults = IntStream + .range(0, packetCount) + .mapToObj(value -> StringUtils.generate(random.nextInt(0, bufferSize))) + .map(message -> clientToServer.sendWithFeedback(new StringWritablePacket(message))) + .collect(toList()); + + CompletableFuture + .allOf(asyncResults.toArray(CompletableFuture[]::new)) + .join(); + + var notSentPacket = asyncResults + .stream() + .map(CompletableFuture::join) + .filter(sent -> !sent) + .findFirst() + .orElse(null); + + Assertions.assertNull(notSentPacket, "Found not sent packets..."); + + // so all packets are already sent, we should not wait for long time to get result + var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofMillis(100))); + + Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); } + } + + private static @NotNull StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { + return new StringWritablePacket(StringUtils.generate(minMessageLength, maxMessageLength)); + } } diff --git a/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java b/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java index 4aba06dc..2753e042 100644 --- a/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java +++ b/rlib-network/src/test/java/javasabr/rlib/network/StringSSLNetworkTest.java @@ -38,279 +38,285 @@ */ public class StringSSLNetworkTest extends BaseNetworkTest { - private static final Logger LOGGER = LoggerManager.getLogger(StringSSLNetworkTest.class); + private static final Logger LOGGER = LoggerManager.getLogger(StringSSLNetworkTest.class); - @Test - @SneakyThrows - void certificatesTest() { + @Test + @SneakyThrows + void certificatesTest() { - var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); - var sslContext = NetworkUtils.createSslContext(keystoreFile, "test"); - var clientSSLContext = NetworkUtils.createAllTrustedClientSslContext(); + var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); + var sslContext = NetworkUtils.createSslContext(keystoreFile, "test"); + var clientSSLContext = NetworkUtils.createAllTrustedClientSslContext(); - var serverPort = NetworkUtils.getAvailablePort(10000); + var serverPort = NetworkUtils.getAvailablePort(10000); - var serverSocketFactory = sslContext.getServerSocketFactory(); - var serverSocket = serverSocketFactory.createServerSocket(serverPort); + var serverSocketFactory = sslContext.getServerSocketFactory(); + var serverSocket = serverSocketFactory.createServerSocket(serverPort); - var clientSocketFactory = clientSSLContext.getSocketFactory(); - var clientSocket = (SSLSocket) clientSocketFactory.createSocket("localhost", serverPort); + var clientSocketFactory = clientSSLContext.getSocketFactory(); + var clientSocket = (SSLSocket) clientSocketFactory.createSocket("localhost", serverPort); - var clientSocketOnServer = serverSocket.accept(); + var clientSocketOnServer = serverSocket.accept(); - new Thread(() -> Utils.unchecked(() -> { - var clientOutStream = new PrintWriter(clientSocket.getOutputStream()); - clientOutStream.println("Hello SSL"); - clientOutStream.flush(); - })).start(); + new Thread(() -> Utils.unchecked(() -> { + var clientOutStream = new PrintWriter(clientSocket.getOutputStream()); + clientOutStream.println("Hello SSL"); + clientOutStream.flush(); + })).start(); - var serverIn = new Scanner(clientSocketOnServer.getInputStream()); - var receivedOnServer = serverIn.next() + " " + serverIn.next(); + var serverIn = new Scanner(clientSocketOnServer.getInputStream()); + var receivedOnServer = serverIn.next() + " " + serverIn.next(); - Assertions.assertEquals("Hello SSL", receivedOnServer); - } + Assertions.assertEquals("Hello SSL", receivedOnServer); + } - @Test - @SneakyThrows - void serverSSLNetworkTest() { + @Test + @SneakyThrows + void serverSSLNetworkTest() { - var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); - var sslContext = NetworkUtils.createSslContext(keystoreFile, "test"); + var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); + var sslContext = NetworkUtils.createSslContext(keystoreFile, "test"); - var serverNetwork = newStringDataSSLServerNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_CLIENT), - sslContext - ); + var serverNetwork = newStringDataSSLServerNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_CLIENT), + sslContext); - var serverAddress = serverNetwork.start(); + var serverAddress = serverNetwork.start(); - serverNetwork.accepted() - .flatMap(Connection::receivedEvents) - .subscribe(event -> { - var message = event.packet.getData(); - LOGGER.info("Received from client: " + message); - event.connection.send(new StringWritablePacket("Echo: " + message)); - }); + serverNetwork + .accepted() + .flatMap(Connection::receivedEvents) + .subscribe(event -> { + var message = event.packet.getData(); + LOGGER.info("Received from client: " + message); + event.connection.send(new StringWritablePacket("Echo: " + message)); + }); - var clientSslContext = NetworkUtils.createAllTrustedClientSslContext(); - var sslSocketFactory = clientSslContext.getSocketFactory(); - var sslSocket = (SSLSocket) sslSocketFactory.createSocket(serverAddress.getHostName(), serverAddress.getPort()); + var clientSslContext = NetworkUtils.createAllTrustedClientSslContext(); + var sslSocketFactory = clientSslContext.getSocketFactory(); + var sslSocket = (SSLSocket) sslSocketFactory.createSocket(serverAddress.getHostName(), serverAddress.getPort()); - var buffer = ByteBuffer.allocate(1024); - buffer.position(2); + var buffer = ByteBuffer.allocate(1024); + buffer.position(2); - new StringWritablePacket("Hello SSL").write(buffer); + new StringWritablePacket("Hello SSL").write(buffer); - buffer.putShort(0, (short) buffer.position()); - buffer.flip(); + buffer.putShort(0, (short) buffer.position()); + buffer.flip(); - var out = sslSocket.getOutputStream(); - out.write(buffer.array(), 0, buffer.limit()); - out.flush(); + var out = sslSocket.getOutputStream(); + out.write(buffer.array(), 0, buffer.limit()); + out.flush(); - buffer.clear(); + buffer.clear(); - var in = sslSocket.getInputStream(); - var readBytes = in.read(buffer.array()); + var in = sslSocket.getInputStream(); + var readBytes = in.read(buffer.array()); - buffer.position(readBytes).flip(); - var packetLength = buffer.getShort(); + buffer + .position(readBytes) + .flip(); + var packetLength = buffer.getShort(); - var response = new StringReadablePacket(); - response.read(null, buffer, packetLength - 2); + var response = new StringReadablePacket(); + response.read(null, buffer, packetLength - 2); - LOGGER.info("Response: " + response.getData()); + LOGGER.info("Response: " + response.getData()); - serverNetwork.shutdown(); - } + serverNetwork.shutdown(); + } - @Test - @SneakyThrows - void clientSSLNetworkTest() { + @Test + @SneakyThrows + void clientSSLNetworkTest() { - System.setProperty("javax.net.debug", "all"); - //LoggerManager.enable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); - //LoggerManager.enable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); + System.setProperty("javax.net.debug", "all"); + //LoggerManager.enable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); + //LoggerManager.enable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); - var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); - var sslContext = NetworkUtils.createSslContext(keystoreFile, "test"); + var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); + var sslContext = NetworkUtils.createSslContext(keystoreFile, "test"); - var serverPort = NetworkUtils.getAvailablePort(1000); + var serverPort = NetworkUtils.getAvailablePort(1000); - var serverSocketFactory = sslContext.getServerSocketFactory(); - var serverSocket = serverSocketFactory.createServerSocket(serverPort); - var counter = new CountDownLatch(1); + var serverSocketFactory = sslContext.getServerSocketFactory(); + var serverSocket = serverSocketFactory.createServerSocket(serverPort); + var counter = new CountDownLatch(1); - var clientSslContext = NetworkUtils.createAllTrustedClientSslContext(); - var clientNetwork = newStringDataSSLClientNetwork( - NetworkConfig.DEFAULT_CLIENT, - new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), - clientSslContext - ); + var clientSslContext = NetworkUtils.createAllTrustedClientSslContext(); + var clientNetwork = newStringDataSSLClientNetwork( + NetworkConfig.DEFAULT_CLIENT, + new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), + clientSslContext); - clientNetwork.connected(new InetSocketAddress("localhost", serverPort)) - .doOnNext(connection -> connection.send(new StringWritablePacket("Hello SSL"))) - .doOnError(Throwable::printStackTrace) - .flatMapMany(Connection::receivedEvents) - .subscribe(event -> { - LOGGER.info("Received from server: " + event.packet.getData()); - counter.countDown(); - }); + clientNetwork + .connected(new InetSocketAddress("localhost", serverPort)) + .doOnNext(connection -> connection.send(new StringWritablePacket("Hello SSL"))) + .doOnError(Throwable::printStackTrace) + .flatMapMany(Connection::receivedEvents) + .subscribe(event -> { + LOGGER.info("Received from server: " + event.packet.getData()); + counter.countDown(); + }); - var acceptedClientSocket = serverSocket.accept(); + var acceptedClientSocket = serverSocket.accept(); - var buffer = ByteBuffer.allocate(512); + var buffer = ByteBuffer.allocate(512); - var clientIn = acceptedClientSocket.getInputStream(); - var readBytes = clientIn.read(buffer.array()); + var clientIn = acceptedClientSocket.getInputStream(); + var readBytes = clientIn.read(buffer.array()); - buffer.position(readBytes).flip(); + buffer + .position(readBytes) + .flip(); - var dataLength = buffer.getShort(); + var dataLength = buffer.getShort(); - var receivedPacket = new StringReadablePacket(); - receivedPacket.read(null, buffer, dataLength); + var receivedPacket = new StringReadablePacket(); + receivedPacket.read(null, buffer, dataLength); - Assertions.assertEquals("Hello SSL", receivedPacket.getData()); + Assertions.assertEquals("Hello SSL", receivedPacket.getData()); - LOGGER.info("Received from client: " + receivedPacket.getData()); + LOGGER.info("Received from client: " + receivedPacket.getData()); - buffer.clear(); - buffer.position(2); + buffer.clear(); + buffer.position(2); - new StringWritablePacket("Echo: Hello SSL").write(buffer); + new StringWritablePacket("Echo: Hello SSL").write(buffer); - buffer.putShort(0, (short) buffer.position()); - buffer.flip(); + buffer.putShort(0, (short) buffer.position()); + buffer.flip(); - var out = acceptedClientSocket.getOutputStream(); - out.write(buffer.array(), 0, buffer.limit()); - out.flush(); + var out = acceptedClientSocket.getOutputStream(); + out.write(buffer.array(), 0, buffer.limit()); + out.flush(); - buffer.clear(); + buffer.clear(); - Assertions.assertTrue( - counter.await(100_000, TimeUnit.MILLISECONDS), - "Still wait for " + counter.getCount() + " packets..." - ); + Assertions.assertTrue( + counter.await(100_000, TimeUnit.MILLISECONDS), + "Still wait for " + counter.getCount() + " packets..."); - clientNetwork.shutdown(); - serverSocket.close(); - } + clientNetwork.shutdown(); + serverSocket.close(); + } - @Test - @SneakyThrows - void echoNetworkTest() { - - //System.setProperty("javax.net.debug", "all"); - //LoggerManager.enable(AbstractPacketWriter.class, LoggerLevel.DEBUG); - //LoggerManager.enable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); - //LoggerManager.enable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); - - var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); - var serverSSLContext = NetworkUtils.createSslContext(keystoreFile, "test"); - - var serverNetwork = newStringDataSSLServerNetwork( - ServerNetworkConfig.DEFAULT_SERVER, - new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_CLIENT), - serverSSLContext - ); - - var expectedReceivedPackets = 90; - var serverAddress = serverNetwork.start(); - var counter = new CountDownLatch(expectedReceivedPackets); - - serverNetwork.accepted() - .flatMap(Connection::receivedEvents) - .subscribe(event -> { - var message = event.packet.getData(); - LOGGER.info("Received from client: " + message); - event.connection.send(new StringWritablePacket("Echo: " + message)); - }); - - var clientSslContext = NetworkUtils.createAllTrustedClientSslContext(); - var clientNetwork = newStringDataSSLClientNetwork( - NetworkConfig.DEFAULT_CLIENT, - new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), - clientSslContext - ); - - clientNetwork.connected(serverAddress) - .doOnNext(connection -> IntStream.range(10, expectedReceivedPackets + 10) - .forEach(length -> connection.send(newMessage(9, length)))) - .doOnError(Throwable::printStackTrace) - .flatMapMany(Connection::receivedEvents) - .subscribe(event -> { - LOGGER.info("Received from server: " + event.packet.getData()); - counter.countDown(); - }); - - Assertions.assertTrue( - counter.await(1000, TimeUnit.MILLISECONDS), - "Still wait for " + counter.getCount() + " packets..." - ); - - serverNetwork.shutdown(); - clientNetwork.shutdown(); - - //LoggerManager.disable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); - //LoggerManager.disable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); - //LoggerManager.disable(AbstractPacketWriter.class, LoggerLevel.DEBUG); - } + @Test + @SneakyThrows + void echoNetworkTest() { - @Test - void shouldReceiveManyPacketsFromSmallToBigSize() { + //System.setProperty("javax.net.debug", "all"); + //LoggerManager.enable(AbstractPacketWriter.class, LoggerLevel.DEBUG); + //LoggerManager.enable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); + //LoggerManager.enable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); - //System.setProperty("javax.net.debug", "all"); - //LoggerManager.enable(AbstractPacketReader.class, LoggerLevel.DEBUG); - //LoggerManager.enable(AbstractPacketWriter.class, LoggerLevel.DEBUG); - LoggerManager.enable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); - LoggerManager.enable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); + var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); + var serverSSLContext = NetworkUtils.createSslContext(keystoreFile, "test"); - var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); - var serverSSLContext = NetworkUtils.createSslContext(keystoreFile, "test"); - var clientSSLContext = NetworkUtils.createAllTrustedClientSslContext(); + var serverNetwork = newStringDataSSLServerNetwork( + ServerNetworkConfig.DEFAULT_SERVER, + new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_CLIENT), + serverSSLContext); - int packetCount = 10; + var expectedReceivedPackets = 90; + var serverAddress = serverNetwork.start(); + var counter = new CountDownLatch(expectedReceivedPackets); - try(var testNetwork = buildStringSSLNetwork(serverSSLContext, clientSSLContext)) { + serverNetwork + .accepted() + .flatMap(Connection::receivedEvents) + .subscribe(event -> { + var message = event.packet.getData(); + LOGGER.info("Received from client: " + message); + event.connection.send(new StringWritablePacket("Echo: " + message)); + }); - var bufferSize = testNetwork.serverNetworkConfig - .getReadBufferSize(); + var clientSslContext = NetworkUtils.createAllTrustedClientSslContext(); + var clientNetwork = newStringDataSSLClientNetwork( + NetworkConfig.DEFAULT_CLIENT, + new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), + clientSslContext); - var random = ThreadLocalRandom.current(); + clientNetwork + .connected(serverAddress) + .doOnNext(connection -> IntStream + .range(10, expectedReceivedPackets + 10) + .forEach(length -> connection.send(newMessage(9, length)))) + .doOnError(Throwable::printStackTrace) + .flatMapMany(Connection::receivedEvents) + .subscribe(event -> { + LOGGER.info("Received from server: " + event.packet.getData()); + counter.countDown(); + }); - var clientToServer = testNetwork.clientToServer; - var serverToClient = testNetwork.serverToClient; + Assertions.assertTrue( + counter.await(1000, TimeUnit.MILLISECONDS), + "Still wait for " + counter.getCount() + " packets..."); - var pendingPacketsOnServer = serverToClient.receivedPackets() - .doOnNext(packet -> LOGGER.info("Received from client: " + packet.getData())) - .buffer(packetCount); + serverNetwork.shutdown(); + clientNetwork.shutdown(); - var messages = IntStream.range(0, packetCount) - .mapToObj(value -> { - var length = value % 3 == 0 ? bufferSize : random.nextInt(0, bufferSize / 2 - 1); - return StringUtils.generate(length); - }) - .peek(message -> clientToServer.send(new StringWritablePacket(message))) - .collect(toList()); + //LoggerManager.disable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); + //LoggerManager.disable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); + //LoggerManager.disable(AbstractPacketWriter.class, LoggerLevel.DEBUG); + } - var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5000))); + @Test + void shouldReceiveManyPacketsFromSmallToBigSize() { - Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); + //System.setProperty("javax.net.debug", "all"); + //LoggerManager.enable(AbstractPacketReader.class, LoggerLevel.DEBUG); + //LoggerManager.enable(AbstractPacketWriter.class, LoggerLevel.DEBUG); + LoggerManager.enable(AbstractSSLPacketWriter.class, LoggerLevel.DEBUG); + LoggerManager.enable(AbstractSSLPacketReader.class, LoggerLevel.DEBUG); - var wrongPacket = receivedPackets.stream() - .filter(packet -> messages.stream() - .noneMatch(message -> message.equals(packet.getData()))) - .findFirst() - .orElse(null); + var keystoreFile = StringSSLNetworkTest.class.getResourceAsStream("/ssl/rlib_test_cert.p12"); + var serverSSLContext = NetworkUtils.createSslContext(keystoreFile, "test"); + var clientSSLContext = NetworkUtils.createAllTrustedClientSslContext(); - Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); - } + int packetCount = 10; + + try (var testNetwork = buildStringSSLNetwork(serverSSLContext, clientSSLContext)) { + + var bufferSize = testNetwork.serverNetworkConfig.getReadBufferSize(); + + var random = ThreadLocalRandom.current(); + + var clientToServer = testNetwork.clientToServer; + var serverToClient = testNetwork.serverToClient; + + var pendingPacketsOnServer = serverToClient + .receivedPackets() + .doOnNext(packet -> LOGGER.info("Received from client: " + packet.getData())) + .buffer(packetCount); + + var messages = IntStream + .range(0, packetCount) + .mapToObj(value -> { + var length = value % 3 == 0 ? bufferSize : random.nextInt(0, bufferSize / 2 - 1); + return StringUtils.generate(length); + }) + .peek(message -> clientToServer.send(new StringWritablePacket(message))) + .collect(toList()); + + var receivedPackets = ObjectUtils.notNull(pendingPacketsOnServer.blockFirst(Duration.ofSeconds(5000))); + + Assertions.assertEquals(receivedPackets.size(), packetCount, "Didn't receive all packets"); + + var wrongPacket = receivedPackets + .stream() + .filter(packet -> messages + .stream() + .noneMatch(message -> message.equals(packet.getData()))) + .findFirst() + .orElse(null); + + Assertions.assertNull(wrongPacket, () -> "Wrong received packet: " + wrongPacket); } + } - private static @NotNull StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { - return new StringWritablePacket(StringUtils.generate(minMessageLength, maxMessageLength)); - } + private static @NotNull StringWritablePacket newMessage(int minMessageLength, int maxMessageLength) { + return new StringWritablePacket(StringUtils.generate(minMessageLength, maxMessageLength)); + } } diff --git a/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java b/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java index aad222bd..e28d082f 100644 --- a/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java +++ b/rlib-testcontainers/src/main/java/javasabr/rlib/testcontainers/FakeSMTPTestContainer.java @@ -12,114 +12,110 @@ public class FakeSMTPTestContainer extends GenericContainer { - public static final String IMAGE = "javasabr/fake-smtp-server"; - public static final String TAG = "latest"; + public static final String IMAGE = "javasabr/fake-smtp-server"; + public static final String TAG = "latest"; - private static final int SMTP_PORT = 5025; - private static final int HTTP_PORT = 5080; + private static final int SMTP_PORT = 5025; + private static final int HTTP_PORT = 5080; - private final HttpClient httpClient; + private final HttpClient httpClient; - @Getter - private String smtpUser; + @Getter + private String smtpUser; - @Getter - private String smtpPassword; + @Getter + private String smtpPassword; - public FakeSMTPTestContainer() { - super(IMAGE + ":" + TAG); - this.smtpUser = "test"; - this.smtpPassword = "test"; - this.httpClient = HttpClient.newHttpClient(); - } + public FakeSMTPTestContainer() { + super(IMAGE + ":" + TAG); + this.smtpUser = "test"; + this.smtpPassword = "test"; + this.httpClient = HttpClient.newHttpClient(); + } - @Override - protected void configure() { - addExposedPorts(SMTP_PORT, HTTP_PORT); - addEnv("SMTP_USER", smtpUser); - addEnv("SMTP_PASSWORD", smtpPassword); - } + @Override + protected void configure() { + addExposedPorts(SMTP_PORT, HTTP_PORT); + addEnv("SMTP_USER", smtpUser); + addEnv("SMTP_PASSWORD", smtpPassword); + } - public int getSmtpPort() { - return getMappedPort(SMTP_PORT); - } + public int getSmtpPort() { + return getMappedPort(SMTP_PORT); + } - public @NotNull FakeSMTPTestContainer withSmtpUser(@NotNull String username) { - this.smtpUser = username; - return this; - } + public @NotNull FakeSMTPTestContainer withSmtpUser(@NotNull String username) { + this.smtpUser = username; + return this; + } - public @NotNull FakeSMTPTestContainer withSmtpPassword(@NotNull String password) { - this.smtpPassword = password; - return this; - } + public @NotNull FakeSMTPTestContainer withSmtpPassword(@NotNull String password) { + this.smtpPassword = password; + return this; + } - /** - * Gets count of received emails from the sender. - * - * @param email the sender's email. - * @return the emails count or -1 if the request was failed. - */ - public long getEmailCountFrom(@NotNull String email) { + /** + * Gets count of received emails from the sender. + * + * @param email the sender's email. + * @return the emails count or -1 if the request was failed. + */ + public long getEmailCountFrom(@NotNull String email) { - var request = HttpRequest.newBuilder(URI.create(getBaseUrl() + "/count/email/from/" + email)) - .GET() - .build(); + var request = HttpRequest + .newBuilder(URI.create(getBaseUrl() + "/count/email/from/" + email)) + .GET() + .build(); - try { + try { - var response = httpClient.send( - request, - responseInfo -> BodySubscribers.ofString(StandardCharsets.UTF_8) - ); + var response = httpClient.send(request, responseInfo -> BodySubscribers.ofString(StandardCharsets.UTF_8)); - if (response.statusCode() != 200) { - return -1; - } + if (response.statusCode() != 200) { + return -1; + } - return Long.parseLong(response.body()); + return Long.parseLong(response.body()); - } catch (IOException | InterruptedException e) { - throw new RuntimeException(e); - } + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); } + } - /** - * Delete all email from this server. - * - * @return true if it was successful. - */ - public boolean deleteEmails() { - - var request = HttpRequest.newBuilder(URI.create(getBaseUrl() + "/emails")) - .DELETE() - .build(); + /** + * Delete all email from this server. + * + * @return true if it was successful. + */ + public boolean deleteEmails() { - try { + var request = HttpRequest + .newBuilder(URI.create(getBaseUrl() + "/emails")) + .DELETE() + .build(); - var response = httpClient.send( - request, - responseInfo -> BodySubscribers.discarding() - ); + try { - return response.statusCode() == 200; + var response = httpClient.send(request, responseInfo -> BodySubscribers.discarding()); - } catch (IOException | InterruptedException e) { - throw new RuntimeException(e); - } - } + return response.statusCode() == 200; - private @NotNull String getBaseUrl() { - return "http://localhost:" + getMappedPort(HTTP_PORT); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); } - - public void waitForReadyState() { - while (!isRunning()) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } + } + + private @NotNull String getBaseUrl() { + return "http://localhost:" + getMappedPort(HTTP_PORT); + } + + public void waitForReadyState() { + while (!isRunning()) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } + } } diff --git a/rlib-testcontainers/src/test/java/javasabr/rlib/testcontainers/FakeSMTPTestContainerTest.java b/rlib-testcontainers/src/test/java/javasabr/rlib/testcontainers/FakeSMTPTestContainerTest.java index 17df6cb0..2b2fa194 100644 --- a/rlib-testcontainers/src/test/java/javasabr/rlib/testcontainers/FakeSMTPTestContainerTest.java +++ b/rlib-testcontainers/src/test/java/javasabr/rlib/testcontainers/FakeSMTPTestContainerTest.java @@ -9,45 +9,46 @@ public class FakeSMTPTestContainerTest { - private static final FakeSMTPTestContainer FAKE_SMTP_TEST_CONTAINER = new FakeSMTPTestContainer(); + private static final FakeSMTPTestContainer FAKE_SMTP_TEST_CONTAINER = new FakeSMTPTestContainer(); - @BeforeAll - static void startContainer() { - FAKE_SMTP_TEST_CONTAINER.start(); - FAKE_SMTP_TEST_CONTAINER.waitForReadyState(); - } + @BeforeAll + static void startContainer() { + FAKE_SMTP_TEST_CONTAINER.start(); + FAKE_SMTP_TEST_CONTAINER.waitForReadyState(); + } - @AfterAll - static void stopContainer() { - FAKE_SMTP_TEST_CONTAINER.stop(); - } + @AfterAll + static void stopContainer() { + FAKE_SMTP_TEST_CONTAINER.stop(); + } - @Test - void shouldStartTestContainerAndCheckApi() { + @Test + void shouldStartTestContainerAndCheckApi() { - Assertions.assertEquals(0, FAKE_SMTP_TEST_CONTAINER.getEmailCountFrom("from@test.com")); + Assertions.assertEquals(0, FAKE_SMTP_TEST_CONTAINER.getEmailCountFrom("from@test.com")); - var smtpServer = FAKE_SMTP_TEST_CONTAINER; - var smtpPort = smtpServer.getSmtpPort(); - var smtpUser = smtpServer.getSmtpUser(); - var smtpPassword = smtpServer.getSmtpPassword(); + var smtpServer = FAKE_SMTP_TEST_CONTAINER; + var smtpPort = smtpServer.getSmtpPort(); + var smtpUser = smtpServer.getSmtpUser(); + var smtpPassword = smtpServer.getSmtpPassword(); - var config = MailSenderConfig.builder() - .from("from@test.com") - .host("localhost") - .port(smtpPort) - .password(smtpPassword) - .username(smtpUser) - .useAuth(true) - .build(); + var config = MailSenderConfig + .builder() + .from("from@test.com") + .host("localhost") + .port(smtpPort) + .password(smtpPassword) + .username(smtpUser) + .useAuth(true) + .build(); - var sender = new JavaxMailSender(config); - sender.send("to@test.com", "Test Subject", "Content"); + var sender = new JavaxMailSender(config); + sender.send("to@test.com", "Test Subject", "Content"); - Assertions.assertEquals(1, FAKE_SMTP_TEST_CONTAINER.getEmailCountFrom("from@test.com")); + Assertions.assertEquals(1, FAKE_SMTP_TEST_CONTAINER.getEmailCountFrom("from@test.com")); - FAKE_SMTP_TEST_CONTAINER.deleteEmails(); + FAKE_SMTP_TEST_CONTAINER.deleteEmails(); - Assertions.assertEquals(0, FAKE_SMTP_TEST_CONTAINER.getEmailCountFrom("from@test.com")); - } + Assertions.assertEquals(0, FAKE_SMTP_TEST_CONTAINER.getEmailCountFrom("from@test.com")); + } } From 897accce2023bbb30ec58e57f0fde51b889fbb4c Mon Sep 17 00:00:00 2001 From: javasabr Date: Fri, 8 Aug 2025 20:50:04 +0200 Subject: [PATCH 2/8] continue global refactoring --- .../rlib/common/util/array/Array.java | 221 +++++++++--------- .../common/util/array/ArrayCollectors.java | 29 +-- .../common/util/array/ArrayComparator.java | 7 +- .../rlib/common/util/array/ArrayFactory.java | 55 ++--- .../common/util/array/ConcurrentArray.java | 169 +++++++------- .../util/array/ConcurrentIntegerArray.java | 12 +- .../rlib/common/util/array/IntegerArray.java | 31 +-- .../rlib/common/util/array/LongArray.java | 2 + .../util/array/MutableIntegerArray.java | 19 +- .../rlib/common/util/array/ReadOnlyArray.java | 29 +-- .../rlib/common/util/array/UnsafeArray.java | 11 +- .../common/util/array/impl/AbstractArray.java | 19 +- .../array/impl/AbstractConcurrentArray.java | 49 ++-- .../impl/ConcurrentAtomicARSWLockArray.java | 9 +- .../ConcurrentAtomicARSWLockArraySet.java | 13 +- .../impl/ConcurrentReentrantRWLockArray.java | 11 +- .../ConcurrentReentrantRWLockArraySet.java | 13 +- .../impl/ConcurrentStampedLockArray.java | 9 +- .../impl/ConcurrentStampedLockArraySet.java | 13 +- .../util/array/impl/CopyOnModifyArray.java | 39 ++-- .../util/array/impl/DefaultArrayIterator.java | 11 +- .../util/array/impl/DefaultIntegerArray.java | 25 +- .../common/util/array/impl/FastArray.java | 47 ++-- .../common/util/array/impl/FastArraySet.java | 13 +- .../common/util/array/impl/FastLongArray.java | 2 + .../util/array/impl/ReadOnlyFastArray.java | 41 ++-- .../util/array/impl/ReadOnlyIntegerArray.java | 13 +- .../util/array/impl/SortedFastArray.java | 15 +- .../util/array/impl/SynchronizedArray.java | 32 ++- .../rlib/common/util/crypt/SymmetryCrypt.java | 12 +- .../AbstractConcurrentIntegerDictionary.java | 11 +- .../AbstractConcurrentLongDictionary.java | 11 +- .../AbstractConcurrentObjectDictionary.java | 11 +- .../util/dictionary/AbstractDictionary.java | 19 +- .../dictionary/AbstractIntegerDictionary.java | 29 +-- .../dictionary/AbstractLongDictionary.java | 27 +-- .../dictionary/AbstractObjectDictionary.java | 41 ++-- ...urrentAtomicARSWLockIntegerDictionary.java | 4 +- ...oncurrentAtomicARSWLockLongDictionary.java | 4 +- ...currentAtomicARSWLockObjectDictionary.java | 4 +- .../util/dictionary/ConcurrentDictionary.java | 3 + .../ConcurrentIntegerDictionary.java | 5 +- .../dictionary/ConcurrentLongDictionary.java | 5 +- .../ConcurrentObjectDictionary.java | 59 ++--- ...ConcurrentStampedLockObjectDictionary.java | 5 +- .../common/util/dictionary/Dictionary.java | 15 +- .../util/dictionary/DictionaryCollectors.java | 41 ++-- .../util/dictionary/DictionaryFactory.java | 35 +-- .../rlib/common/util/dictionary/Entry.java | 12 +- .../dictionary/FastIntegerDictionary.java | 9 +- .../util/dictionary/FastLongDictionary.java | 9 +- .../util/dictionary/FastObjectDictionary.java | 9 +- .../util/dictionary/IntegerDictionary.java | 31 +-- .../dictionary/IntegerDictionaryIterator.java | 22 +- .../common/util/dictionary/IntegerEntry.java | 15 +- .../util/dictionary/LongDictionary.java | 31 +-- .../dictionary/LongDictionaryIterator.java | 22 +- .../common/util/dictionary/LongEntry.java | 15 +- .../util/dictionary/ObjectDictionary.java | 67 +++--- .../dictionary/ObjectDictionaryIterator.java | 21 +- .../common/util/dictionary/ObjectEntry.java | 24 +- .../ReadOnlyFastLongDictionary.java | 7 +- .../ReadOnlyFastObjectDictionary.java | 15 +- .../dictionary/UnsafeIntegerDictionary.java | 10 +- .../util/dictionary/UnsafeLongDictionary.java | 10 +- .../dictionary/UnsafeObjectDictionary.java | 9 +- .../common/util/linkedlist/impl/Node.java | 28 +-- .../linkedlist/impl/SortedLinkedList.java | 18 +- 68 files changed, 864 insertions(+), 820 deletions(-) diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java index 827c80f2..c7d72aea 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java @@ -32,8 +32,8 @@ import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.array.impl.DefaultArrayIterator; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * Interface to implement dynamic arrays. @@ -42,6 +42,7 @@ * @param the element's type. * @author JavaSaBr */ +@NullMarked public interface Array extends Collection, Serializable, Reusable, Cloneable, RandomAccess { /** @@ -50,7 +51,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * @param the result element's type. * @return the empty array. */ - static @NotNull ReadOnlyArray empty() { + static ReadOnlyArray empty() { return unsafeNNCast(ArrayFactory.EMPTY_ARRAY); } @@ -61,7 +62,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * @param the element's type. * @return the new array. */ - static @NotNull Array ofType(@NotNull Class type) { + static Array ofType(Class type) { return ArrayFactory.newArray(type); } @@ -73,7 +74,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * @param the element's type. * @return the new array. */ - static @NotNull Array ofType(@NotNull Class type, int capacity) { + static Array ofType(Class type, int capacity) { return ArrayFactory.newArray(type, capacity); } @@ -84,7 +85,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * @param the element's type. * @return the new read only array. */ - static @NotNull ReadOnlyArray of(@NotNull Array another) { + static ReadOnlyArray of(Array another) { return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOfRange(another.array(), 0, another.size())); } @@ -95,7 +96,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * @param the element's type. * @return the read only array. */ - static @NotNull ReadOnlyArray of(@NotNull T element) { + static ReadOnlyArray of(T element) { T[] newArray = ArrayUtils.create(element.getClass(), 1); newArray[0] = element; @@ -104,12 +105,12 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab } @SafeVarargs - static @NotNull ReadOnlyArray of(@NotNull T... elements) { + static ReadOnlyArray of(T... elements) { return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOf(elements)); } @SafeVarargs - static @NotNull ReadOnlyArray optionals(@NotNull Class type, @NotNull Optional... elements) { + static ReadOnlyArray optionals(Class type, Optional... elements) { return ArrayFactory.newReadOnlyArray(Arrays .stream(elements) .filter(Optional::isPresent) @@ -117,12 +118,12 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab .toArray(value -> ArrayUtils.create(type, value))); } - static > @NotNull A append(@NotNull A first, @NotNull A second) { + static > A append(A first, A second) { first.addAll(second); return first; } - static @NotNull ReadOnlyArray combine(@NotNull Array first, @NotNull Array second) { + static ReadOnlyArray combine(Array first, Array second) { var componentType = ClassUtils.>unsafeNNCast(first .array() @@ -141,7 +142,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * @param the element's type. * @return the supplier. */ - static @NotNull NotNullSupplier> supplier(@NotNull Class type) { + static NotNullSupplier> supplier(Class type) { return () -> ArrayFactory.newConcurrentStampedLockArray(type); } @@ -152,7 +153,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * @param the element's type. * @return the supplier. */ - static @NotNull NotNullFunction, Array> function(@NotNull Class type) { + static NotNullFunction, Array> function(Class type) { return ArrayFactory::newConcurrentStampedLockArray; } @@ -161,7 +162,7 @@ public interface Array extends Collection, Serializable, Reusable, Cloneab * * @param target the target array. */ - default void copyTo(@NotNull Array target) { + default void copyTo(Array target) { target.addAll(this); } @@ -171,7 +172,7 @@ default void copyTo(@NotNull Array target) { * @param array the array with new elements. * @return true if this array was changed. */ - boolean addAll(@NotNull Array array); + boolean addAll(Array array); /** * Adds all elements from the array to this array. @@ -179,14 +180,14 @@ default void copyTo(@NotNull Array target) { * @param array the array with new elements. * @return true if this array was changed. */ - boolean addAll(@NotNull E[] array); + boolean addAll(E[] array); /** * Applies this function to each element of this array with replacing to result element from thia function. * * @param function the function. */ - default void apply(@NotNull Function function) { + default void apply(Function function) { E[] array = array(); @@ -200,20 +201,20 @@ default void apply(@NotNull Function function) { * * @return the wrapped array. */ - E @NotNull [] array(); + E [] array(); @Override - default @NotNull Stream stream() { + default Stream stream() { return Arrays.stream(array(), 0, size()); } @Override - default @NotNull Stream parallelStream() { + default Stream parallelStream() { return stream().parallel(); } @Override - default boolean contains(@NotNull Object object) { + default boolean contains(Object object) { for (E element : array()) { if (element == null) { @@ -232,7 +233,7 @@ default boolean contains(@NotNull Object object) { * @param array the array to be checked for containment in this array * @return true if this array contains all of the elements in the specified array. */ - default boolean containsAll(@NotNull Array array) { + default boolean containsAll(Array array) { if (array.isEmpty()) { return false; @@ -250,7 +251,7 @@ default boolean containsAll(@NotNull Array array) { } @Override - default boolean containsAll(@NotNull Collection array) { + default boolean containsAll(Collection array) { if (array.isEmpty()) { return false; @@ -273,7 +274,7 @@ default boolean containsAll(@NotNull Collection array) { * @param array the array to be checked for containment in this array * @return true if this array contains all of the elements in the specified array. */ - default boolean containsAll(@NotNull Object[] array) { + default boolean containsAll(Object[] array) { if (array.length < 1) { return false; @@ -299,7 +300,7 @@ default void free() { * @param index the index of removing the element. * @return the removed element. */ - @NotNull E fastRemove(int index); + E fastRemove(int index); /** * Removes an element without saving original ordering of other elements. @@ -307,7 +308,7 @@ default void free() { * @param object the element to remove. * @return true if the element was removed. */ - default boolean fastRemove(@NotNull Object object) { + default boolean fastRemove(Object object) { int index = indexOf(object); @@ -324,7 +325,7 @@ default boolean fastRemove(@NotNull Object object) { * @param array the array with elements to remove. * @return count of removed elements. */ - default int fastRemoveAll(@NotNull E[] array) { + default int fastRemoveAll(E[] array) { int count = 0; @@ -352,7 +353,7 @@ default int fastRemoveAll(@NotNull E[] array) { * @param index the index of the element. * @return the element. */ - @NotNull E get(int index); + E get(int index); /** * Find an index of the object in this array. @@ -360,7 +361,7 @@ default int fastRemoveAll(@NotNull E[] array) { * @param object the object to find. * @return the index of the object or -1. */ - default int indexOf(@NotNull Object object) { + default int indexOf(Object object) { int index = 0; @@ -379,7 +380,7 @@ default int indexOf(@NotNull Object object) { } @Override - default @NotNull ArrayIterator iterator() { + default ArrayIterator iterator() { return new DefaultArrayIterator<>(this); } @@ -405,7 +406,7 @@ default int indexOf(@NotNull Object object) { * @param object the object. * @return the last index or -1. */ - default int lastIndexOf(@NotNull Object object) { + default int lastIndexOf(Object object) { E[] array = array(); @@ -447,7 +448,7 @@ default int lastIndexOf(@NotNull Object object) { * @param target array containing elements to be removed from this array. * @return true if this array changed as a result of the call. */ - default boolean removeAll(@NotNull Array target) { + default boolean removeAll(Array target) { if (target.isEmpty()) { return false; @@ -473,7 +474,7 @@ default boolean removeAll(@NotNull Array target) { * @param target array containing elements to be removed from this array. * @return true if this array changed as a result of the call. */ - default boolean fastRemoveAll(@NotNull Array target) { + default boolean fastRemoveAll(Array target) { if (target.isEmpty()) { return false; @@ -500,7 +501,7 @@ default boolean fastRemoveAll(@NotNull Array target) { } @Override - default boolean removeAll(@NotNull Collection target) { + default boolean removeAll(Collection target) { if (target.isEmpty()) { return false; @@ -524,7 +525,7 @@ default boolean removeAll(@NotNull Collection target) { * @param target array containing elements to be retained in this array. * @return true if this array changed as a result of the call. */ - default boolean retainAll(@NotNull Array target) { + default boolean retainAll(Array target) { E[] array = array(); @@ -539,7 +540,7 @@ default boolean retainAll(@NotNull Array target) { } @Override - default boolean retainAll(@NotNull Collection target) { + default boolean retainAll(Collection target) { E[] array = array(); @@ -559,7 +560,7 @@ default boolean retainAll(@NotNull Collection target) { * @param index the element's index. * @param element the new element. */ - void replace(int index, @NotNull E element); + void replace(int index, E element); /** * Removes the element at index. @@ -567,10 +568,10 @@ default boolean retainAll(@NotNull Collection target) { * @param index the index of removing the element. * @return the removed element. */ - @NotNull E remove(int index); + E remove(int index); @Override - default boolean remove(@NotNull Object object) { + default boolean remove(Object object) { var index = indexOf(object); @@ -587,13 +588,13 @@ default boolean remove(@NotNull Object object) { * @param comparator the comparator. * @return the array */ - default @NotNull Array sort(@NotNull ArrayComparator comparator) { + default Array sort(ArrayComparator comparator) { ArrayUtils.sort(array(), 0, size(), comparator); return this; } @Override - default @NotNull T[] toArray(@NotNull T[] newArray) { + default T[] toArray(T[] newArray) { E[] array = array(); @@ -622,7 +623,7 @@ default boolean remove(@NotNull Object object) { * @param componentType the type of the new array. * @return the copied array. */ - default @NotNull T[] toArray(@NotNull Class componentType) { + default T[] toArray(Class componentType) { T[] newArray = ArrayUtils.create(componentType, size()); E[] array = array(); @@ -637,7 +638,7 @@ default boolean remove(@NotNull Object object) { * * @return the unsafe interface of this array. */ - default @NotNull UnsafeArray asUnsafe() { + default UnsafeArray asUnsafe() { if (this instanceof UnsafeArray) { return (UnsafeArray) this; } else { @@ -651,15 +652,15 @@ default boolean isEmpty() { } @Override - default @NotNull E[] toArray() { + default E[] toArray() { var array = array(); return Arrays.copyOf(array, size(), (Class) array.getClass()); } - @NotNull String toString(@NotNull Function toString); + String toString(Function toString); @Override - default boolean removeIf(@NotNull Predicate<@NotNull ? super E> filter) { + default boolean removeIf(Predicate filter) { var array = array(); var removed = 0; @@ -687,7 +688,7 @@ default boolean removeIf(@NotNull Predicate<@NotNull ? super E> filter) { * @param the argument's type. * @return {@code true} if any elements were removed. */ - default boolean removeIf(@NotNull A argument, @NotNull NotNullBiPredicate filter) { + default boolean removeIf(A argument, NotNullBiPredicate filter) { var array = array(); var removed = 0; @@ -718,9 +719,9 @@ default boolean removeIf(@NotNull A argument, @NotNull NotNullBiPredicate boolean removeIf( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + A argument, + NotNullFunction converter, + NotNullBiPredicate filter) { var array = array(); var removed = 0; @@ -752,9 +753,9 @@ default boolean removeIf( * @since 9.6.0 */ default boolean removeIfConverted( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + A argument, + NotNullFunction converter, + NotNullBiPredicate filter) { var array = array(); var removed = 0; @@ -782,7 +783,7 @@ default boolean removeIfConverted( * @param the argument's type. * @return true if there is at least an element for the condition. */ - default boolean anyMatch(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default boolean anyMatch(T argument, NotNullBiPredicate filter) { return findAny(argument, filter) != null; } @@ -798,9 +799,9 @@ default boolean anyMatch(@NotNull T argument, @NotNull NotNullBiPredicate boolean anyMatchConverted( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + T argument, + NotNullFunction converter, + NotNullBiPredicate filter) { return findAnyConverted(argument, converter, filter) != null; } @@ -811,7 +812,7 @@ default boolean anyMatchConverted( * @param filter the condition. * @return true if there is at least an element for the condition. */ - default boolean anyMatch(int argument, @NotNull NotNullIntObjectPredicate filter) { + default boolean anyMatch(int argument, NotNullIntObjectPredicate filter) { return findAny(argument, filter) != null; } @@ -823,7 +824,7 @@ default boolean anyMatch(int argument, @NotNull NotNullIntObjectPredicate boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default boolean anyMatchR(T argument, NotNullBiPredicate filter) { return findAnyR(argument, filter) != null; } @@ -833,7 +834,7 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default @Nullable E findAny(NotNullPredicate filter) { if (isEmpty()) { return null; @@ -861,7 +862,7 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate the argument's type. * @return the found element or null. */ - default @Nullable E findAny(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default @Nullable E findAny(T argument, NotNullBiPredicate filter) { if (isEmpty()) { return null; @@ -893,9 +894,9 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate @Nullable E findAnyConverted( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + T argument, + NotNullFunction converter, + NotNullBiPredicate filter) { if (isEmpty()) { return null; @@ -923,7 +924,7 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate @Nullable E findAnyR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default @Nullable E findAnyR(T argument, NotNullBiPredicate filter) { if (isEmpty()) { return null; @@ -950,7 +951,7 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default @Nullable E findAny(int argument, NotNullIntObjectPredicate filter) { if (isEmpty()) { return null; @@ -977,7 +978,7 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default @Nullable E findAnyL(long argument, NotNullLongObjectPredicate filter) { if (isEmpty()) { return null; @@ -1008,9 +1009,9 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate @Nullable E findAny( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTriplePredicate filter) { + F first, + S second, + NotNullTriplePredicate filter) { if (isEmpty()) { return null; @@ -1041,8 +1042,8 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate converter, - @NotNull BiIntPredicate filter) { + NotNullFunctionInt converter, + BiIntPredicate filter) { if (isEmpty()) { return null; @@ -1075,9 +1076,9 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate @Nullable E findAnyConvertedToInt( int argument, - @NotNull NotNullFunction firstConverter, - @NotNull NotNullFunctionInt secondConverter, - @NotNull BiIntPredicate filter) { + NotNullFunction firstConverter, + NotNullFunctionInt secondConverter, + BiIntPredicate filter) { if (isEmpty()) { return null; @@ -1104,7 +1105,7 @@ default boolean anyMatchR(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default int count(NotNullPredicate filter) { var array = array(); var count = 0; @@ -1129,7 +1130,7 @@ default int count(@NotNull NotNullPredicate filter) { * @param the argument's type. * @return the count of matched elements. */ - default int count(@NotNull F arg, @NotNull NotNullBiPredicate filter) { + default int count(F arg, NotNullBiPredicate filter) { var array = array(); var count = 0; @@ -1154,7 +1155,7 @@ default int count(@NotNull F arg, @NotNull NotNullBiPredicate filter) * @param filter the condition. * @return the count of matched elements. */ - default int countR(@NotNull F arg, @NotNull NotNullBiPredicate filter) { + default int countR(F arg, NotNullBiPredicate filter) { var array = array(); var count = 0; @@ -1172,7 +1173,7 @@ default int countR(@NotNull F arg, @NotNull NotNullBiPredicate filter) } @Override - default void forEach(@NotNull Consumer consumer) { + default void forEach(Consumer consumer) { var array = array(); @@ -1187,7 +1188,7 @@ default void forEach(@NotNull Consumer consumer) { * @param filter the condition. * @param consumer the function. */ - default void forEachFiltered(@NotNull NotNullPredicate filter, @NotNull NotNullConsumer consumer) { + default void forEachFiltered(NotNullPredicate filter, NotNullConsumer consumer) { var array = array(); @@ -1208,7 +1209,7 @@ default void forEachFiltered(@NotNull NotNullPredicate filter, @NotNull NotNu * @param consumer the function. * @param the type of an argument. */ - default void forEach(@NotNull T argument, @NotNull NotNullBiConsumer consumer) { + default void forEach(T argument, NotNullBiConsumer consumer) { var array = array(); @@ -1224,7 +1225,7 @@ default void forEach(@NotNull T argument, @NotNull NotNullBiConsumer the argument's type. */ - default void forEachR(@NotNull T argument, @NotNull NotNullBiConsumer consumer) { + default void forEachR(T argument, NotNullBiConsumer consumer) { var array = array(); @@ -1243,9 +1244,9 @@ default void forEachR(@NotNull T argument, @NotNull NotNullBiConsumer the converted type. */ default void forEachConverted( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer consumer) { + T argument, + NotNullFunction converter, + NotNullBiConsumer consumer) { var array = array(); @@ -1266,10 +1267,10 @@ default void forEachConverted( * @param the converted type. */ default void forEachConverted( - @NotNull F first, - @NotNull S second, - @NotNull NotNullFunction converter, - @NotNull NotNullTripleConsumer consumer) { + F first, + S second, + NotNullFunction converter, + NotNullTripleConsumer consumer) { var array = array(); @@ -1289,9 +1290,9 @@ default void forEachConverted( * @since 9.8.0 */ default void forEach( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer consumer) { + T argument, + NotNullFunction converter, + NotNullBiConsumer consumer) { var array = array(); @@ -1309,9 +1310,9 @@ default void forEach( * @param consumer the function. */ default void forEachFiltered( - @NotNull T argument, - @NotNull NotNullBiPredicate filter, - @NotNull NotNullBiConsumer consumer) { + T argument, + NotNullBiPredicate filter, + NotNullBiConsumer consumer) { var array = array(); @@ -1335,9 +1336,9 @@ default void forEachFiltered( * @param the second argument's type. */ default void forEach( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer consumer) { + F first, + S second, + NotNullTripleConsumer consumer) { var array = array(); @@ -1354,7 +1355,7 @@ default void forEach( * @param consumer the function. * @param the second argument's type. */ - default void forEach(int first, @NotNull A second, @NotNull NotNullIntBiObjectConsumer consumer) { + default void forEach(int first, A second, NotNullIntBiObjectConsumer consumer) { var array = array(); @@ -1373,9 +1374,9 @@ default void forEach(int first, @NotNull A second, @NotNull NotNullIntBiObje * @param the second argument type. */ default void forEachR( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer consumer) { + F first, + S second, + NotNullTripleConsumer consumer) { var array = array(); @@ -1395,10 +1396,10 @@ default void forEachR( * @param the second argument's type. */ default void forEachFiltered( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTriplePredicate filter, - @NotNull NotNullTripleConsumer consumer) { + F first, + S second, + NotNullTriplePredicate filter, + NotNullTripleConsumer consumer) { var array = array(); @@ -1422,8 +1423,8 @@ default void forEachFiltered( */ default void forEachL( long first, - @NotNull F second, - @NotNull NotNullLongBiObjectConsumer consumer) { + F second, + NotNullLongBiObjectConsumer consumer) { var array = array(); @@ -1442,8 +1443,8 @@ default void forEachL( */ default void forEachF( float first, - @NotNull F second, - @NotNull NotNullFloatBiObjectConsumer consumer) { + F second, + NotNullFloatBiObjectConsumer consumer) { var array = array(); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java index 57c15b0e..98ef7a87 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java @@ -10,19 +10,20 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The array collectors factory. * * @author JavaSaBr */ +@NullMarked public class ArrayCollectors { - private static @NotNull Set CH_ID = + private static Set CH_ID = unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); - private static @NotNull Set CH_ID_CONC = unmodifiableSet(EnumSet.of( + private static Set CH_ID_CONC = unmodifiableSet(EnumSet.of( Collector.Characteristics.IDENTITY_FINISH, Collector.Characteristics.CONCURRENT)); @@ -35,12 +36,12 @@ public class ArrayCollectors { * @param the array's type. * @return the collector. */ - public static > @NotNull Collector collector( - @NotNull Class type, - @NotNull Function, A> arrayFactory) { + public static > Collector collector( + Class type, + Function, A> arrayFactory) { return new Collector<>() { - private final @NotNull Supplier supplier = () -> arrayFactory.apply(type); + private final Supplier supplier = () -> arrayFactory.apply(type); @Override public Supplier supplier() { @@ -81,12 +82,12 @@ public Set characteristics() { * @param the array's type. * @return the collector. */ - public static > @NotNull Collector concurrentCollector( - @NotNull Class type, - @NotNull Function, A> arrayFactory) { + public static > Collector concurrentCollector( + Class type, + Function, A> arrayFactory) { return new Collector<>() { - private final @NotNull Supplier supplier = () -> arrayFactory.apply(type); + private final Supplier supplier = () -> arrayFactory.apply(type); @Override public Supplier supplier() { @@ -125,7 +126,7 @@ public Set characteristics() { * @param the array element's type. * @return the collector. */ - public static @NotNull Collector, Array> toArray(@NotNull Class type) { + public static Collector, Array> toArray(Class type) { return collector(type, ArrayFactory::newArray); } @@ -136,8 +137,8 @@ public Set characteristics() { * @param the array element's type. * @return the collector. */ - public static @NotNull Collector, ConcurrentArray> toConcurrentArray( - @NotNull Class type) { + public static Collector, ConcurrentArray> toConcurrentArray( + Class type) { return concurrentCollector(type, ArrayFactory::newConcurrentStampedLockArray); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java index 734a303b..6a639c4a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java @@ -1,8 +1,8 @@ package javasabr.rlib.common.util.array; import java.util.Comparator; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface to implement a comparator for {@link Array}. @@ -10,6 +10,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface ArrayComparator extends Comparator { @Override @@ -32,5 +33,5 @@ default int compare(@Nullable T first, @Nullable T second) { * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater * than the second. */ - int compareImpl(@NotNull T first, @NotNull T second); + int compareImpl(T first, T second); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java index f7aaf868..3cf831f7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java @@ -16,67 +16,68 @@ import javasabr.rlib.common.util.array.impl.ReadOnlyFastArray; import javasabr.rlib.common.util.array.impl.SortedFastArray; import javasabr.rlib.common.util.array.impl.SynchronizedArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory to create different kinds of arrays. * * @author JavaSaBr */ +@NullMarked public class ArrayFactory { public static final Array EMPTY_ARRAY = newReadOnlyArray(ArrayUtils.EMPTY_OBJECT_ARRAY); @SafeVarargs - public static @NotNull Array asArray(@NotNull E... args) { + public static Array asArray(E... args) { return new FastArray<>(args); } - public static @NotNull Array newArray(@NotNull Class type) { + public static Array newArray(Class type) { return newUnsafeArray(type); } - public static @NotNull Array newArray(@NotNull Class type, int capacity) { + public static Array newArray(Class type, int capacity) { return newUnsafeArray(type, capacity); } - public static @NotNull Array newCopyOnModifyArray(@NotNull Class type) { + public static Array newCopyOnModifyArray(Class type) { return new CopyOnModifyArray<>(type, 0); } - public static @NotNull UnsafeArray newUnsafeArray(@NotNull Class type) { + public static UnsafeArray newUnsafeArray(Class type) { return new FastArray<>(type); } - public static UnsafeArray newUnsafeArray(@NotNull Class type, int capacity) { + public static UnsafeArray newUnsafeArray(Class type, int capacity) { return new FastArray<>(type, capacity); } - public static @NotNull ReadOnlyArray newReadOnlyArray(@NotNull E[] elements) { + public static ReadOnlyArray newReadOnlyArray(E[] elements) { return new ReadOnlyFastArray<>(elements); } - public static @NotNull Array newArraySet(@NotNull Class type) { + public static Array newArraySet(Class type) { return new FastArraySet<>(type); } - public static @NotNull ConcurrentArray newConcurrentReentrantRWLockArray(@NotNull Class type) { + public static ConcurrentArray newConcurrentReentrantRWLockArray(Class type) { return new ConcurrentReentrantRWLockArray<>(type); } - public static @NotNull ConcurrentArray newConcurrentReentrantRWLockArraySet(@NotNull Class type) { + public static ConcurrentArray newConcurrentReentrantRWLockArraySet(Class type) { return new ConcurrentReentrantRWLockArraySet<>(type); } - public static @NotNull ConcurrentArray newConcurrentAtomicARSWLockArray(@NotNull Class type) { + public static ConcurrentArray newConcurrentAtomicARSWLockArray(Class type) { return new ConcurrentAtomicARSWLockArray<>(type); } - public static @NotNull ConcurrentArray newConcurrentStampedLockArray(@NotNull Class type) { + public static ConcurrentArray newConcurrentStampedLockArray(Class type) { return new ConcurrentStampedLockArray<>(type); } - public static @NotNull ConcurrentArray newConcurrentStampedLockArray(E @NotNull [] array) { + public static ConcurrentArray newConcurrentStampedLockArray(E [] array) { Class type = unsafeNNCast(array .getClass() @@ -88,56 +89,56 @@ public static UnsafeArray newUnsafeArray(@NotNull Class type, return result; } - public static @NotNull ConcurrentArray newConcurrentStampedLockArraySet(@NotNull Class type) { + public static ConcurrentArray newConcurrentStampedLockArraySet(Class type) { return new ConcurrentStampedLockArraySet<>(type); } - public static > @NotNull Array newSortedArray(@NotNull Class type) { + public static > Array newSortedArray(Class type) { return new SortedFastArray<>(unsafeNNCast(type)); } - public static @NotNull Array newSynchronizedArray(@NotNull Class type) { + public static Array newSynchronizedArray(Class type) { return new SynchronizedArray<>(type); } - public static @NotNull MutableIntegerArray newMutableIntegerArray() { + public static MutableIntegerArray newMutableIntegerArray() { return new DefaultIntegerArray(); } - public static @NotNull MutableIntegerArray newMutableIntegerArray(int capacity) { + public static MutableIntegerArray newMutableIntegerArray(int capacity) { return new DefaultIntegerArray(capacity); } - public static @NotNull MutableIntegerArray newMutableIntegerArray(int... numbers) { + public static MutableIntegerArray newMutableIntegerArray(int... numbers) { return new DefaultIntegerArray(numbers); } - public static @NotNull LongArray newLongArray() { + public static LongArray newLongArray() { return new FastLongArray(); } - public static @NotNull LongArray newLongArray(int capacity) { + public static LongArray newLongArray(int capacity) { return new FastLongArray(capacity); } - public static @NotNull float[] toFloatArray(float... elements) { + public static float[] toFloatArray(float... elements) { return elements; } - public static @NotNull int[] toIntArray(int... elements) { + public static int[] toIntArray(int... elements) { return elements; } - public static @NotNull long[] toLongArray(long... elements) { + public static long[] toLongArray(long... elements) { return elements; } - public static @NotNull boolean[] toBooleanArray(boolean... elements) { + public static boolean[] toBooleanArray(boolean... elements) { return elements; } @SafeVarargs - public static @NotNull T[] toArray(K... elements) { + public static T[] toArray(K... elements) { return elements; } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java index 153406f4..cfc18a82 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java @@ -16,8 +16,8 @@ import javasabr.rlib.common.function.NotNullSupplier; import javasabr.rlib.common.function.NotNullTripleConsumer; import javasabr.rlib.common.util.ClassUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface with methods to manage thread-safe access with arrays. @@ -25,10 +25,11 @@ * @param the element's type. * @author JavaSaBr */ +@NullMarked public interface ConcurrentArray extends Array { @SafeVarargs - static @NotNull ConcurrentArray of(@NotNull T... elements) { + static ConcurrentArray of(T... elements) { return ArrayFactory.newConcurrentStampedLockArray(elements); } @@ -39,7 +40,7 @@ public interface ConcurrentArray extends Array { * @param the element's type. * @return the new concurrent array. */ - static @NotNull ConcurrentArray ofType(@NotNull Class type) { + static ConcurrentArray ofType(Class type) { return ArrayFactory.newConcurrentStampedLockArray(type); } @@ -50,7 +51,7 @@ public interface ConcurrentArray extends Array { * @param the element's type. * @return the supplier. */ - static @NotNull NotNullSupplier> supplier(@NotNull Class type) { + static NotNullSupplier> supplier(Class type) { return () -> ArrayFactory.newConcurrentStampedLockArray(type); } @@ -60,7 +61,7 @@ public interface ConcurrentArray extends Array { * @param the element's type. * @return the supplier. */ - static @NotNull Function, ConcurrentArray> function() { + static Function, ConcurrentArray> function() { return ArrayFactory::newConcurrentStampedLockArray; } @@ -71,7 +72,7 @@ public interface ConcurrentArray extends Array { * @param the element's type. * @return the supplier. */ - static @NotNull Function, ConcurrentArray> function(@NotNull Class type) { + static Function, ConcurrentArray> function(Class type) { return aClass -> ArrayFactory.newConcurrentStampedLockArray(ClassUtils.>unsafeNNCast(type)); } @@ -136,7 +137,7 @@ default void writeUnlock(long stamp) { * @param consumer the consumer. * @return this array. */ - default @NotNull ConcurrentArray forEachInReadLock(@NotNull NotNullConsumer consumer) { + default ConcurrentArray forEachInReadLock(NotNullConsumer consumer) { var stamp = readLock(); try { @@ -156,9 +157,9 @@ default void writeUnlock(long stamp) { * @param the argument's type. * @return this array. */ - default @NotNull ConcurrentArray forEachInReadLock( - @NotNull T argument, - @NotNull NotNullBiConsumer function) { + default ConcurrentArray forEachInReadLock( + T argument, + NotNullBiConsumer function) { var stamp = readLock(); try { @@ -179,10 +180,10 @@ default void writeUnlock(long stamp) { * @param the second argument's type. * @return this array. */ - default @NotNull ConcurrentArray forEachInReadLock( + default ConcurrentArray forEachInReadLock( int first, - @NotNull A second, - @NotNull NotNullIntBiObjectConsumer consumer) { + A second, + NotNullIntBiObjectConsumer consumer) { var stamp = readLock(); try { @@ -204,10 +205,10 @@ default void writeUnlock(long stamp) { * @param the second argument's type. * @return this array. */ - default @NotNull ConcurrentArray forEachInReadLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer consumer) { + default ConcurrentArray forEachInReadLock( + F first, + S second, + NotNullTripleConsumer consumer) { var stamp = readLock(); try { @@ -227,9 +228,9 @@ default void writeUnlock(long stamp) { * @param the argument's type. * @return this array. */ - default @NotNull ConcurrentArray forEachInReadLockR( - @NotNull T argument, - @NotNull NotNullBiConsumer function) { + default ConcurrentArray forEachInReadLockR( + T argument, + NotNullBiConsumer function) { var stamp = readLock(); try { @@ -251,10 +252,10 @@ default void writeUnlock(long stamp) { * @param the converted type. * @return this array. */ - default @NotNull ConcurrentArray forEachConvertedInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer function) { + default ConcurrentArray forEachConvertedInReadLock( + T argument, + NotNullFunction converter, + NotNullBiConsumer function) { var stamp = readLock(); try { @@ -279,11 +280,11 @@ default void writeUnlock(long stamp) { * @return this array. * @since 9.8.0 */ - default @NotNull ConcurrentArray forEachConvertedInReadLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullFunction converter, - @NotNull NotNullTripleConsumer function) { + default ConcurrentArray forEachConvertedInReadLock( + F first, + S second, + NotNullFunction converter, + NotNullTripleConsumer function) { var stamp = readLock(); try { @@ -305,10 +306,10 @@ default void writeUnlock(long stamp) { * @param the converted type. * @return this array. */ - default @NotNull ConcurrentArray forEachInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiConsumer function) { + default ConcurrentArray forEachInReadLock( + T argument, + NotNullFunction converter, + NotNullBiConsumer function) { var stamp = readLock(); try { @@ -327,7 +328,7 @@ default void writeUnlock(long stamp) { * @param the result's type. * @return the result from the function. */ - default @Nullable R getInReadLock(@NotNull NotNullNullableFunction, R> function) { + default @Nullable R getInReadLock(NotNullNullableFunction, R> function) { var stamp = readLock(); try { return function.apply(this); @@ -347,8 +348,8 @@ default void writeUnlock(long stamp) { * @since 9.5.0 */ default @Nullable R getInReadLock( - @NotNull A arg, - @NotNull NotNullNullableBiFunction, A, R> function) { + A arg, + NotNullNullableBiFunction, A, R> function) { var stamp = readLock(); try { return function.apply(this, arg); @@ -370,9 +371,9 @@ default void writeUnlock(long stamp) { * @since 9.9.0 */ default @Nullable R getInReadLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullNullableTripleFunction, A, T, R> function) { + A first, + T second, + NotNullNullableTripleFunction, A, T, R> function) { var stamp = readLock(); try { return function.apply(this, first, second); @@ -388,7 +389,7 @@ default void writeUnlock(long stamp) { * @param the result's type. * @return the result from the function. */ - default @Nullable R getInWriteLock(@NotNull NotNullNullableFunction, R> function) { + default @Nullable R getInWriteLock(NotNullNullableFunction, R> function) { var stamp = writeLock(); try { return function.apply(this); @@ -408,8 +409,8 @@ default void writeUnlock(long stamp) { * @since 9.5.0 */ default @Nullable R getInWriteLock( - @NotNull A argument, - @NotNull NotNullNullableBiFunction, A, R> function) { + A argument, + NotNullNullableBiFunction, A, R> function) { var stamp = writeLock(); try { return function.apply(this, argument); @@ -431,9 +432,9 @@ default void writeUnlock(long stamp) { * @since 9.9.0 */ default @Nullable R getInWriteLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullNullableTripleFunction, A, T, R> function) { + A first, + T second, + NotNullNullableTripleFunction, A, T, R> function) { var stamp = writeLock(); try { return function.apply(this, first, second); @@ -448,7 +449,7 @@ default void writeUnlock(long stamp) { * @param function the function. * @return this array. */ - default @NotNull ConcurrentArray runInReadLock(@NotNull NotNullConsumer> function) { + default ConcurrentArray runInReadLock(NotNullConsumer> function) { var stamp = readLock(); try { @@ -468,9 +469,9 @@ default void writeUnlock(long stamp) { * @param function the function. * @return this array. */ - default @NotNull ConcurrentArray runInReadLock( - @NotNull F argument, - @NotNull NotNullBiConsumer, F> function) { + default ConcurrentArray runInReadLock( + F argument, + NotNullBiConsumer, F> function) { var stamp = readLock(); try { @@ -493,10 +494,10 @@ default void writeUnlock(long stamp) { * @return this array. * @since 9.9.0 */ - default @NotNull ConcurrentArray runInReadLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullTripleConsumer, A, T> function) { + default ConcurrentArray runInReadLock( + A first, + T second, + NotNullTripleConsumer, A, T> function) { var stamp = readLock(); try { @@ -514,7 +515,7 @@ default void writeUnlock(long stamp) { * @param function the function. * @return this array. */ - default @NotNull ConcurrentArray runInWriteLock(@NotNull NotNullConsumer> function) { + default ConcurrentArray runInWriteLock(NotNullConsumer> function) { var stamp = writeLock(); try { @@ -534,9 +535,9 @@ default void writeUnlock(long stamp) { * @param function the function. * @return this array. */ - default @NotNull ConcurrentArray runInWriteLock( - @NotNull F argument, - @NotNull NotNullBiConsumer, F> function) { + default ConcurrentArray runInWriteLock( + F argument, + NotNullBiConsumer, F> function) { var stamp = writeLock(); try { @@ -559,10 +560,10 @@ default void writeUnlock(long stamp) { * @return this array. * @since 9.9.0 */ - default @NotNull ConcurrentArray runInWriteLock( - @NotNull A first, - @NotNull T second, - @NotNull NotNullTripleConsumer, A, T> function) { + default ConcurrentArray runInWriteLock( + A first, + T second, + NotNullTripleConsumer, A, T> function) { var stamp = writeLock(); try { function.accept(this, first, second); @@ -580,7 +581,7 @@ default void writeUnlock(long stamp) { * @return the found element or null. * @since 9.5.0 */ - default @Nullable E findAnyInReadLock(int argument, @NotNull NotNullIntObjectPredicate filter) { + default @Nullable E findAnyInReadLock(int argument, NotNullIntObjectPredicate filter) { if (isEmpty()) { return null; @@ -606,9 +607,9 @@ default void writeUnlock(long stamp) { * @since 9.7.0 */ default @Nullable E findAnyConvertedInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + T argument, + NotNullFunction converter, + NotNullBiPredicate filter) { if (isEmpty()) { return null; } @@ -632,8 +633,8 @@ default void writeUnlock(long stamp) { */ default @Nullable E findAnyConvertedToIntInReadLock( int argument, - @NotNull NotNullFunctionInt converter, - @NotNull BiIntPredicate filter) { + NotNullFunctionInt converter, + BiIntPredicate filter) { if (isEmpty()) { return null; } @@ -659,9 +660,9 @@ default void writeUnlock(long stamp) { */ default @Nullable E findAnyConvertedToIntInReadLock( int argument, - @NotNull NotNullFunction firstConverter, - @NotNull NotNullFunctionInt secondConverter, - @NotNull BiIntPredicate filter) { + NotNullFunction firstConverter, + NotNullFunctionInt secondConverter, + BiIntPredicate filter) { if (isEmpty()) { return null; } @@ -682,7 +683,7 @@ default void writeUnlock(long stamp) { * @param filter the condition. * @return true if there is at least an element for the condition. */ - default boolean anyMatchInReadLock(@NotNull T argument, @NotNull NotNullBiPredicate filter) { + default boolean anyMatchInReadLock(T argument, NotNullBiPredicate filter) { if (isEmpty()) { return false; @@ -703,7 +704,7 @@ default boolean anyMatchInReadLock(@NotNull T argument, @NotNull NotNullBiPr * @param filter the condition. * @return true if there is at least an element for the condition. */ - default boolean anyMatchInReadLock(int argument, @NotNull NotNullIntObjectPredicate filter) { + default boolean anyMatchInReadLock(int argument, NotNullIntObjectPredicate filter) { if (isEmpty()) { return false; @@ -729,9 +730,9 @@ default boolean anyMatchInReadLock(int argument, @NotNull NotNullIntObjectPredic * @since 9.7.0 */ default boolean anyMatchConvertedInReadLock( - @NotNull T argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + T argument, + NotNullFunction converter, + NotNullBiPredicate filter) { if (isEmpty()) { return false; } @@ -750,7 +751,7 @@ default boolean anyMatchConvertedInReadLock( * @param filter the predicate which returns {@code true} for elements to be removed. * @return {@code true} if any elements were removed. */ - default boolean removeIfInWriteLock(@NotNull NotNullPredicate filter) { + default boolean removeIfInWriteLock(NotNullPredicate filter) { var stamp = writeLock(); try { return removeIf(filter); @@ -767,7 +768,7 @@ default boolean removeIfInWriteLock(@NotNull NotNullPredicate filter) * @param the argument's type. * @return {@code true} if any elements were removed. */ - default boolean removeIfInWriteLock(@NotNull A argument, @NotNull NotNullBiPredicate filter) { + default boolean removeIfInWriteLock(A argument, NotNullBiPredicate filter) { var stamp = writeLock(); try { return removeIf(argument, filter); @@ -787,9 +788,9 @@ default boolean removeIfInWriteLock(@NotNull A argument, @NotNull NotNullBiP * @return {@code true} if any elements were removed. */ default boolean removeIfInWriteLock( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + A argument, + NotNullFunction converter, + NotNullBiPredicate filter) { var stamp = writeLock(); try { return removeIf(argument, converter, filter); @@ -810,9 +811,9 @@ default boolean removeIfInWriteLock( * @since 9.6.0 */ default boolean removeIfConvertedInWriteLock( - @NotNull A argument, - @NotNull NotNullFunction converter, - @NotNull NotNullBiPredicate filter) { + A argument, + NotNullFunction converter, + NotNullBiPredicate filter) { var stamp = writeLock(); try { return removeIfConverted(argument, converter, filter); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java index d7992913..c593bc57 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentIntegerArray.java @@ -5,24 +5,20 @@ public interface ConcurrentIntegerArray { /** * Write lock. */ - default void writeLock() { - } + default void writeLock() {} /** * Write unlock. */ - default void writeUnlock() { - } + default void writeUnlock() {} /** * Read lock. */ - default void readLock() { - } + default void readLock() {} /** * Read unlock. */ - default void readUnlock() { - } + default void readUnlock() {} } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java index b025d1bc..00ce38c8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/IntegerArray.java @@ -6,28 +6,29 @@ import java.util.stream.IntStream; import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.array.impl.ReadOnlyIntegerArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface of dynamic integer array. */ +@NullMarked public interface IntegerArray extends Iterable { - @NotNull IntegerArray EMPTY = new ReadOnlyIntegerArray(ArrayUtils.EMPTY_INT_ARRAY); + IntegerArray EMPTY = new ReadOnlyIntegerArray(ArrayUtils.EMPTY_INT_ARRAY); - static @NotNull IntegerArray of(int value) { + static IntegerArray of(int value) { return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(value)); } - static @NotNull IntegerArray of(int v1, int v2) { + static IntegerArray of(int v1, int v2) { return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(v1, v2)); } - static @NotNull IntegerArray of(int v1, int v2, int v3) { + static IntegerArray of(int v1, int v2, int v3) { return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(v1, v2, v3)); } - static @NotNull IntegerArray of(int... values) { + static IntegerArray of(int... values) { return new ReadOnlyIntegerArray(ArrayFactory.toIntArray(values)); } @@ -36,7 +37,7 @@ public interface IntegerArray extends Iterable { * * @return the wrapped int array. */ - int @NotNull [] array(); + int [] array(); default boolean contains(int element) { @@ -51,7 +52,7 @@ default boolean contains(int element) { return false; } - default boolean containsAll(int @NotNull [] array) { + default boolean containsAll(int [] array) { for (int val : array) { if (!contains(val)) { @@ -62,7 +63,7 @@ default boolean containsAll(int @NotNull [] array) { return true; } - default boolean containsAll(@NotNull IntegerArray array) { + default boolean containsAll(IntegerArray array) { var elements = array.array(); @@ -120,10 +121,10 @@ default boolean isEmpty() { } @Override - @NotNull ArrayIterator iterator(); + ArrayIterator iterator(); @Override - default void forEach(@NotNull Consumer consumer) { + default void forEach(Consumer consumer) { var array = array(); @@ -132,7 +133,7 @@ default void forEach(@NotNull Consumer consumer) { } } - default void forEachInt(@NotNull IntConsumer consumer) { + default void forEachInt(IntConsumer consumer) { var array = array(); @@ -181,7 +182,7 @@ default int lastIndexOf(int element) { * * @return the array with data from this array. */ - default int @NotNull [] toArray() { + default int [] toArray() { return ArrayUtils.copyOfRange(array(), 0, size()); } @@ -191,7 +192,7 @@ default int lastIndexOf(int element) { * @param newArray the new array. * @return the array with data from this array. */ - default int @NotNull [] toArray(int @NotNull [] newArray) { + default int [] toArray(int [] newArray) { var array = array(); @@ -207,7 +208,7 @@ default int lastIndexOf(int element) { return ArrayUtils.copyOfRange(array(), 0, size()); } - default @NotNull IntStream stream() { + default IntStream stream() { return Arrays.stream(array(), 0, size()); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java index b181bff6..854ffb60 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/LongArray.java @@ -1,10 +1,12 @@ package javasabr.rlib.common.util.array; import javasabr.rlib.common.util.ArrayUtils; +import org.jspecify.annotations.NullMarked; /** * The interface Long array. */ +@NullMarked public interface LongArray extends Iterable { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java index a582c1f8..d754658a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/MutableIntegerArray.java @@ -1,7 +1,8 @@ package javasabr.rlib.common.util.array; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; +@NullMarked public interface MutableIntegerArray extends IntegerArray { /** @@ -10,7 +11,7 @@ public interface MutableIntegerArray extends IntegerArray { * @param number the new integer. * @return this array. */ - @NotNull IntegerArray add(int number); + IntegerArray add(int number); /** * Add new numbers to this array. @@ -18,7 +19,7 @@ public interface MutableIntegerArray extends IntegerArray { * @param numbers the new numbers. * @return this array. */ - @NotNull IntegerArray addAll(int @NotNull [] numbers); + IntegerArray addAll(int [] numbers); /** * Add new numbers to this array. @@ -26,14 +27,14 @@ public interface MutableIntegerArray extends IntegerArray { * @param numbers the new numbers. * @return this array. */ - @NotNull IntegerArray addAll(@NotNull IntegerArray numbers); + IntegerArray addAll(IntegerArray numbers); /** * Clear this array. * * @return this array. */ - @NotNull IntegerArray clear(); + IntegerArray clear(); /** * Remove the first equal number in array with putting last number to position of removed number. @@ -82,7 +83,7 @@ default boolean fastRemove(int number) { * @param numbers the array of numbers to remove. * @return true if at least one number was removed from this array. */ - default boolean removeAll(@NotNull IntegerArray numbers) { + default boolean removeAll(IntegerArray numbers) { if (numbers.isEmpty()) { return false; @@ -106,7 +107,7 @@ default boolean removeAll(@NotNull IntegerArray numbers) { * @param numbers the array of numbers. * @return true if at least one number was removed from this array. */ - default boolean retainAll(@NotNull IntegerArray numbers) { + default boolean retainAll(IntegerArray numbers) { var array = array(); var count = 0; @@ -152,12 +153,12 @@ default boolean remove(int number) { * * @return this array. */ - @NotNull IntegerArray sort(); + IntegerArray sort(); /** * Resize wrapped array to the relevant size. * * @return this array. */ - @NotNull IntegerArray trimToSize(); + IntegerArray trimToSize(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java index ac6219b3..7baea642 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java @@ -3,7 +3,7 @@ import java.util.Collection; import java.util.function.Function; import java.util.function.Predicate; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface to mark an array as read only array. @@ -11,11 +11,12 @@ * @param the element's type. * @author JavaSaBr */ +@NullMarked public interface ReadOnlyArray extends Array { @Override @Deprecated - void apply(@NotNull Function function); + void apply(Function function); @Override @Deprecated @@ -23,47 +24,47 @@ public interface ReadOnlyArray extends Array { @Override @Deprecated - boolean addAll(@NotNull E[] array); + boolean addAll(E[] array); @Override @Deprecated - boolean addAll(@NotNull Array array); + boolean addAll(Array array); @Override @Deprecated - boolean addAll(@NotNull Collection c); + boolean addAll(Collection c); @Override @Deprecated - boolean fastRemove(@NotNull Object object); + boolean fastRemove(Object object); @Override @Deprecated - @NotNull E remove(int index); + E remove(int index); @Override @Deprecated - boolean removeIf(@NotNull Predicate filter); + boolean removeIf(Predicate filter); @Override @Deprecated - boolean retainAll(@NotNull Collection target); + boolean retainAll(Collection target); @Override @Deprecated - boolean retainAll(@NotNull Array target); + boolean retainAll(Array target); @Override @Deprecated - boolean removeAll(@NotNull Collection target); + boolean removeAll(Collection target); @Override @Deprecated - boolean removeAll(@NotNull Array target); + boolean removeAll(Array target); @Override @Deprecated - boolean remove(@NotNull Object object); + boolean remove(Object object); @Override @Deprecated @@ -71,5 +72,5 @@ public interface ReadOnlyArray extends Array { @Override @Deprecated - @NotNull Array sort(@NotNull ArrayComparator comparator); + Array sort(ArrayComparator comparator); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java index b79b573b..b98870b1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.array; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface with unsafe methods for the Array. @@ -9,6 +9,7 @@ * @param the element's type. * @author JavaSaBr */ +@NullMarked public interface UnsafeArray extends Array { /** @@ -26,7 +27,7 @@ default void prepareForSize(int size) { * @param object the new element. * @return true if this array was changed. */ - default boolean unsafeAdd(@NotNull E object) { + default boolean unsafeAdd(E object) { throw new UnsupportedOperationException(); } @@ -46,7 +47,7 @@ default boolean unsafeAdd(@NotNull E object) { * @param index the index. * @param element the element. */ - default void unsafeSet(int index, @NotNull E element) { + default void unsafeSet(int index, E element) { throw new UnsupportedOperationException(); } @@ -55,5 +56,5 @@ default void unsafeSet(int index, @NotNull E element) { * * @return the array */ - @NotNull Array trimToSize(); + Array trimToSize(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java index 0e143ab3..1188e570 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java @@ -1,13 +1,14 @@ package javasabr.rlib.common.util.array.impl; +import java.io.Serial; import java.util.Arrays; import java.util.Objects; import java.util.function.Function; import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.array.Array; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of dynamic arrays. @@ -15,8 +16,10 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public abstract class AbstractArray implements Array { + @Serial private static final long serialVersionUID = 2113052245369887690L; /** @@ -24,11 +27,11 @@ public abstract class AbstractArray implements Array { */ protected static final int DEFAULT_CAPACITY = 10; - public AbstractArray(@NotNull Class type) { + public AbstractArray(Class type) { this(type, DEFAULT_CAPACITY); } - public AbstractArray(@NotNull Class type, int capacity) { + public AbstractArray(Class type, int capacity) { super(); if (capacity < 0) { @@ -38,7 +41,7 @@ public AbstractArray(@NotNull Class type, int capacity) { setArray(ArrayUtils.create(type, capacity)); } - public AbstractArray(@NotNull E[] array) { + public AbstractArray(E[] array) { super(); setArray(array); setSize(array.length); @@ -58,11 +61,11 @@ public void free() { } @Override - public @NotNull AbstractArray clone() throws CloneNotSupportedException { + public AbstractArray clone() throws CloneNotSupportedException { return ClassUtils.unsafeNNCast(super.clone()); } - protected abstract void setArray(E @NotNull [] array); + protected abstract void setArray(E [] array); protected abstract void setSize(int size); @@ -72,7 +75,7 @@ public String toString() { } @Override - public @NotNull String toString(@NotNull Function toString) { + public String toString(Function toString) { return getClass().getSimpleName() + " size = " + size() + " :\n " + ArrayUtils.toString(this, toString); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java index 75602526..018aa2c6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java @@ -2,6 +2,7 @@ import static java.lang.Math.max; +import java.io.Serial; import java.util.Collection; import java.util.NoSuchElementException; import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; @@ -10,7 +11,7 @@ import javasabr.rlib.common.util.array.ArrayIterator; import javasabr.rlib.common.util.array.ConcurrentArray; import javasabr.rlib.common.util.array.UnsafeArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The base concurrent implementation of dynamic arrays. @@ -18,10 +19,12 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked @SuppressWarnings("NonAtomicOperationOnVolatileField") public abstract class AbstractConcurrentArray extends AbstractArray implements ConcurrentArray, UnsafeArray { + @Serial private static final long serialVersionUID = -6291504312637658721L; /** @@ -33,19 +36,19 @@ public abstract class AbstractConcurrentArray extends AbstractArray implem * The unsafe array. */ @SuppressWarnings("NullableProblems") - private volatile E @NotNull [] array; + private volatile E [] array; - public AbstractConcurrentArray(@NotNull Class type) { + public AbstractConcurrentArray(Class type) { this(type, 10); } - public AbstractConcurrentArray(@NotNull Class type, int size) { + public AbstractConcurrentArray(Class type, int size) { super(type, size); this.size = new ReusableAtomicInteger(); } @Override - public boolean add(@NotNull E element) { + public boolean add(E element) { if (size() == array.length) { array = ArrayUtils.copyOfAndExtend(array, Math.max(array.length >> 1, 1)); @@ -56,7 +59,7 @@ public boolean add(@NotNull E element) { } @Override - public final boolean addAll(@NotNull Array elements) { + public final boolean addAll(Array elements) { if (elements.isEmpty()) { return false; @@ -76,7 +79,7 @@ public final boolean addAll(@NotNull Array elements) { } @Override - public boolean addAll(@NotNull Collection collection) { + public boolean addAll(Collection collection) { if (collection.isEmpty()) { return false; @@ -97,7 +100,7 @@ public boolean addAll(@NotNull Collection collection) { } @Override - public final boolean addAll(@NotNull E[] elements) { + public final boolean addAll(E[] elements) { if (elements.length < 1) { return false; @@ -117,7 +120,7 @@ public final boolean addAll(@NotNull E[] elements) { } @Override - public final @NotNull E[] array() { + public final E[] array() { return array; } @@ -134,7 +137,7 @@ public void prepareForSize(int size) { } @Override - public final @NotNull E fastRemove(int index) { + public final E fastRemove(int index) { if (index < 0 || index >= size()) { throw new NoSuchElementException(); @@ -150,7 +153,7 @@ public void prepareForSize(int size) { } @Override - public final @NotNull E get(int index) { + public final E get(int index) { if (index < 0 || index >= size()) { throw new NoSuchElementException(); @@ -160,12 +163,12 @@ public void prepareForSize(int size) { } @Override - public final @NotNull ArrayIterator iterator() { + public final ArrayIterator iterator() { return new DefaultArrayIterator<>(this); } @Override - public void replace(int index, @NotNull E element) { + public void replace(int index, E element) { if (index < 0 || index >= size()) { throw new ArrayIndexOutOfBoundsException(); @@ -175,7 +178,7 @@ public void replace(int index, @NotNull E element) { } @Override - protected final void setArray(E @NotNull [] array) { + protected final void setArray(E [] array) { this.array = array; } @@ -190,7 +193,7 @@ public final int size() { } @Override - public @NotNull E remove(int index) { + public E remove(int index) { if (index < 0 || index >= size()) { throw new ArrayIndexOutOfBoundsException(); @@ -210,7 +213,7 @@ public final int size() { } @Override - public final @NotNull AbstractConcurrentArray trimToSize() { + public final AbstractConcurrentArray trimToSize() { var size = size(); @@ -223,18 +226,18 @@ public final int size() { } @Override - public boolean unsafeAdd(@NotNull E object) { + public boolean unsafeAdd(E object) { array[size.getAndIncrement()] = object; return true; } @Override - public @NotNull E unsafeGet(int index) { + public E unsafeGet(int index) { return array[index]; } @Override - public void unsafeSet(final int index, @NotNull final E element) { + public void unsafeSet(final int index, final E element) { if (array[index] != null) { size.decrementAndGet(); @@ -251,7 +254,7 @@ public void unsafeSet(final int index, @NotNull final E element) { * @param selfSize the self size * @param targetSize the target size */ - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + protected void processAdd(Array elements, int selfSize, int targetSize) { System.arraycopy(elements.array(), 0, array, selfSize, targetSize); size.set(selfSize + targetSize); } @@ -263,18 +266,18 @@ protected void processAdd(@NotNull Array elements, int selfSize, in * @param selfSize the self size * @param targetSize the target size */ - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + protected void processAdd(E[] elements, int selfSize, int targetSize) { System.arraycopy(elements, 0, array, selfSize, targetSize); size.set(selfSize + targetSize); } @Override - public @NotNull UnsafeArray asUnsafe() { + public UnsafeArray asUnsafe() { return this; } @Override - public @NotNull AbstractConcurrentArray clone() throws CloneNotSupportedException { + public AbstractConcurrentArray clone() throws CloneNotSupportedException { var clone = (AbstractConcurrentArray) super.clone(); clone.array = ArrayUtils.copyOfAndExtend(array, size()); return clone; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java index 80822c2f..04b0027b 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArray.java @@ -3,7 +3,7 @@ import javasabr.rlib.common.concurrent.lock.AsyncReadSyncWriteLock; import javasabr.rlib.common.concurrent.lock.LockFactory; import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The concurrent implementation of the array using {@link LockFactory#newReentrantARSWLock()} for @@ -12,17 +12,18 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class ConcurrentAtomicARSWLockArray extends AbstractConcurrentArray { private static final long serialVersionUID = -6291504312637658721L; - private final @NotNull AsyncReadSyncWriteLock lock; + private final AsyncReadSyncWriteLock lock; - public ConcurrentAtomicARSWLockArray(@NotNull Class type) { + public ConcurrentAtomicARSWLockArray(Class type) { this(type, 10); } - public ConcurrentAtomicARSWLockArray(@NotNull Class type, int size) { + public ConcurrentAtomicARSWLockArray(Class type, int size) { super(type, size); this.lock = LockFactory.newAtomicARSWLock(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java index 3e7b0ec5..183f9485 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentAtomicARSWLockArraySet.java @@ -3,7 +3,7 @@ import javasabr.rlib.common.concurrent.lock.LockFactory; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The concurrent implementation of the array without duplications using {@link LockFactory#newAtomicARSWLock()} for @@ -12,25 +12,26 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class ConcurrentAtomicARSWLockArraySet extends ConcurrentAtomicARSWLockArray { private static final long serialVersionUID = -3394386864246350866L; - public ConcurrentAtomicARSWLockArraySet(@NotNull Class type) { + public ConcurrentAtomicARSWLockArraySet(Class type) { super(type); } - public ConcurrentAtomicARSWLockArraySet(@NotNull Class type, int size) { + public ConcurrentAtomicARSWLockArraySet(Class type, int size) { super(type, size); } @Override - public boolean add(@NotNull E element) { + public boolean add(E element) { return !contains(element) && super.add(element); } @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + protected void processAdd(Array elements, int selfSize, int targetSize) { var array = elements.array(); for (int i = 0, length = elements.size(); i < length; i++) { E element = array[i]; @@ -41,7 +42,7 @@ protected void processAdd(@NotNull Array elements, int selfSize, in } @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + protected void processAdd(E[] elements, int selfSize, int targetSize) { for (E element : elements) { if (!contains(element)) { unsafeAdd(element); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java index 1a948dec..16f06ca5 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArray.java @@ -4,7 +4,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import javasabr.rlib.common.concurrent.lock.LockFactory; import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The concurrent implementation of the array using {@link ReentrantReadWriteLock} for @@ -13,18 +13,19 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class ConcurrentReentrantRWLockArray extends AbstractConcurrentArray { private static final long serialVersionUID = -7985171224116955303L; - private final @NotNull Lock readLock; - private final @NotNull Lock writeLock; + private final Lock readLock; + private final Lock writeLock; - public ConcurrentReentrantRWLockArray(@NotNull Class type) { + public ConcurrentReentrantRWLockArray(Class type) { this(type, 10); } - public ConcurrentReentrantRWLockArray(@NotNull Class type, int size) { + public ConcurrentReentrantRWLockArray(Class type, int size) { super(type, size); var readWriteLock = LockFactory.newReentrantRWLock(); this.readLock = readWriteLock.readLock(); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java index 19cb2dd4..98346d42 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentReentrantRWLockArraySet.java @@ -3,7 +3,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The concurrent implementation of the array without duplications using {@link ReentrantReadWriteLock} for @@ -12,25 +12,26 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class ConcurrentReentrantRWLockArraySet extends ConcurrentReentrantRWLockArray { private static final long serialVersionUID = -3394386864246350866L; - public ConcurrentReentrantRWLockArraySet(@NotNull Class type) { + public ConcurrentReentrantRWLockArraySet(Class type) { super(type); } - public ConcurrentReentrantRWLockArraySet(@NotNull Class type, int size) { + public ConcurrentReentrantRWLockArraySet(Class type, int size) { super(type, size); } @Override - public boolean add(@NotNull E element) { + public boolean add(E element) { return !contains(element) && super.add(element); } @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + protected void processAdd(Array elements, int selfSize, int targetSize) { var array = elements.array(); for (int i = 0, length = elements.size(); i < length; i++) { E element = array[i]; @@ -41,7 +42,7 @@ protected void processAdd(@NotNull Array elements, int selfSize, in } @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + protected void processAdd(E[] elements, int selfSize, int targetSize) { for (E element : elements) { if (!contains(element)) { unsafeAdd(element); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java index 7133be80..fbc088d2 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java @@ -3,7 +3,7 @@ import java.util.concurrent.locks.StampedLock; import javasabr.rlib.common.concurrent.lock.LockFactory; import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The concurrent implementation of array using {@link StampedLock} for {@link ConcurrentArray#readLock()} and @@ -12,17 +12,18 @@ * @param the element's type. * @author JavaSaBr */ +@NullMarked public class ConcurrentStampedLockArray extends AbstractConcurrentArray { private static final long serialVersionUID = -6291504312637658721L; - private final @NotNull StampedLock lock; + private final StampedLock lock; - public ConcurrentStampedLockArray(@NotNull Class type) { + public ConcurrentStampedLockArray(Class type) { this(type, 10); } - public ConcurrentStampedLockArray(@NotNull Class type, int size) { + public ConcurrentStampedLockArray(Class type, int size) { super(type, size); this.lock = LockFactory.newStampedLock(); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java index 0f84d420..ef36b96a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java @@ -3,7 +3,7 @@ import java.util.concurrent.locks.StampedLock; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The concurrent implementation of the array without duplications using {@link StampedLock} for @@ -12,25 +12,26 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class ConcurrentStampedLockArraySet extends ConcurrentStampedLockArray { private static final long serialVersionUID = -6291504312637658721L; - public ConcurrentStampedLockArraySet(@NotNull Class type) { + public ConcurrentStampedLockArraySet(Class type) { this(type, 10); } - public ConcurrentStampedLockArraySet(@NotNull Class type, int size) { + public ConcurrentStampedLockArraySet(Class type, int size) { super(type, size); } @Override - public boolean add(@NotNull E element) { + public boolean add(E element) { return !contains(element) && super.add(element); } @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + protected void processAdd(Array elements, int selfSize, int targetSize) { var array = elements.array(); for (int i = 0, length = elements.size(); i < length; i++) { E element = array[i]; @@ -41,7 +42,7 @@ protected void processAdd(@NotNull Array elements, int selfSize, in } @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + protected void processAdd(E[] elements, int selfSize, int targetSize) { for (E element : elements) { if (!contains(element)) { unsafeAdd(element); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java index 8564f860..25646aa8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java @@ -8,7 +8,7 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayComparator; import javasabr.rlib.common.util.array.ArrayFactory; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the array which create a new back-end array for each modification. Thread-safe. @@ -16,19 +16,20 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class CopyOnModifyArray extends AbstractArray { private static final long serialVersionUID = -8477384427415127978L; @SuppressWarnings("NullableProblems") - protected volatile @NotNull ReusableAtomicReference array; + protected volatile ReusableAtomicReference array; - public CopyOnModifyArray(@NotNull Class type, int size) { + public CopyOnModifyArray(Class type, int size) { super(type, size); } @Override - public boolean add(@NotNull E object) { + public boolean add(E object) { var current = array.get(); var newArray = ArrayUtils.copyOfAndExtend(current, 1); @@ -42,7 +43,7 @@ public boolean add(@NotNull E object) { } @Override - public boolean addAll(@NotNull Array elements) { + public boolean addAll(Array elements) { if (elements.isEmpty()) { return false; @@ -63,7 +64,7 @@ public boolean addAll(@NotNull Array elements) { } @Override - public boolean addAll(@NotNull Collection collection) { + public boolean addAll(Collection collection) { if (collection.isEmpty()) { return false; @@ -86,7 +87,7 @@ public boolean addAll(@NotNull Collection collection) { } @Override - public boolean addAll(@NotNull E[] elements) { + public boolean addAll(E[] elements) { if (elements.length < 1) { return false; @@ -103,17 +104,17 @@ public boolean addAll(@NotNull E[] elements) { } @Override - public final @NotNull E[] array() { + public final E[] array() { return array.get(); } @Override - public @NotNull E remove(int index) { + public E remove(int index) { throw new UnsupportedOperationException(); } @Override - public boolean removeAll(@NotNull Array target) { + public boolean removeAll(Array target) { if (target.isEmpty()) { return false; @@ -136,7 +137,7 @@ public boolean removeAll(@NotNull Array target) { } @Override - public boolean removeAll(@NotNull Collection target) { + public boolean removeAll(Collection target) { if (target.isEmpty()) { return false; @@ -159,7 +160,7 @@ public boolean removeAll(@NotNull Collection target) { } @Override - public boolean remove(@NotNull Object object) { + public boolean remove(Object object) { var current = array.get(); var index = ArrayUtils.indexOf(current, object); @@ -190,12 +191,12 @@ public boolean remove(@NotNull Object object) { } @Override - public boolean fastRemove(@NotNull Object object) { + public boolean fastRemove(Object object) { return remove(object); } @Override - public @NotNull E fastRemove(int index) { + public E fastRemove(int index) { throw new UnsupportedOperationException(); } @@ -216,7 +217,7 @@ public void clear() { } @Override - public final @NotNull E get(int index) { + public final E get(int index) { if (index < 0 || index >= size()) { throw new NoSuchElementException(); @@ -226,12 +227,12 @@ public void clear() { } @Override - public void replace(int index, @NotNull E element) { + public void replace(int index, E element) { throw new UnsupportedOperationException(); } @Override - protected final void setArray(E @NotNull [] array) { + protected final void setArray(E [] array) { //noinspection ConstantConditions if (this.array == null) { @@ -251,7 +252,7 @@ public final int size() { } @Override - public @NotNull Array sort(@NotNull ArrayComparator comparator) { + public Array sort(ArrayComparator comparator) { var current = array(); var newArray = ArrayUtils.copyOfAndExtend(current, 0); @@ -266,7 +267,7 @@ public final int size() { } @Override - public @NotNull CopyOnModifyArray clone() throws CloneNotSupportedException { + public CopyOnModifyArray clone() throws CloneNotSupportedException { var clone = (CopyOnModifyArray) super.clone(); clone.array = new ReusableAtomicReference<>(ArrayUtils.copyOf(array())); return clone; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java index ef776179..6f5d5768 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayIterator; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the unsafeArray iterator. @@ -10,24 +10,25 @@ * @param the element's type. * @author JavaSaBr */ +@NullMarked public class DefaultArrayIterator implements ArrayIterator { /** * The array for iteration. */ - private final @NotNull Array array; + private final Array array; /** * The unsafe array for directly access. */ - private final @NotNull E[] unsafeArray; + private final E[] unsafeArray; /** * The current position in the array. */ private int ordinal; - public DefaultArrayIterator(@NotNull Array array) { + public DefaultArrayIterator(Array array) { this.array = array; this.unsafeArray = array.array(); } @@ -48,7 +49,7 @@ public int index() { } @Override - public @NotNull E next() { + public E next() { return ordinal >= unsafeArray.length ? null : unsafeArray[ordinal++]; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java index 21ce823d..4c0b577c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultIntegerArray.java @@ -6,14 +6,15 @@ import javasabr.rlib.common.util.array.ArrayIterator; import javasabr.rlib.common.util.array.IntegerArray; import javasabr.rlib.common.util.array.MutableIntegerArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * Simple implementation of dynamic integer array. * * @author JavaSaBr */ +@NullMarked public class DefaultIntegerArray implements MutableIntegerArray { protected int[] array; @@ -28,13 +29,13 @@ public DefaultIntegerArray(int size) { this.size = 0; } - public DefaultIntegerArray(int @NotNull [] numbers) { + public DefaultIntegerArray(int [] numbers) { this.array = numbers; this.size = numbers.length; } @Override - public @NotNull DefaultIntegerArray add(int number) { + public DefaultIntegerArray add(int number) { if (size == array.length) { array = ArrayUtils.copyOf(array, Math.max(array.length >> 1, 1)); @@ -46,7 +47,7 @@ public DefaultIntegerArray(int @NotNull [] numbers) { } @Override - public @NotNull DefaultIntegerArray addAll(int @NotNull [] numbers) { + public DefaultIntegerArray addAll(int [] numbers) { if (numbers.length < 1) { return this; @@ -67,7 +68,7 @@ public DefaultIntegerArray(int @NotNull [] numbers) { } @Override - public final @NotNull DefaultIntegerArray addAll(@NotNull IntegerArray numbers) { + public final DefaultIntegerArray addAll(IntegerArray numbers) { if (numbers.isEmpty()) { return this; @@ -90,12 +91,12 @@ public DefaultIntegerArray(int @NotNull [] numbers) { } @Override - public final @NotNull int[] array() { + public final int[] array() { return array; } @Override - public final @NotNull DefaultIntegerArray clear() { + public final DefaultIntegerArray clear() { size = 0; return this; } @@ -136,7 +137,7 @@ public final int get(int index) { } @Override - public final @NotNull ArrayIterator iterator() { + public final ArrayIterator iterator() { return new DefaultIterator(); } @@ -185,13 +186,13 @@ public final boolean removeByIndex(int index) { } @Override - public final @NotNull DefaultIntegerArray sort() { + public final DefaultIntegerArray sort() { ArrayUtils.sort(array, 0, size); return this; } @Override - public final @NotNull DefaultIntegerArray trimToSize() { + public final DefaultIntegerArray trimToSize() { var array = array(); @@ -244,7 +245,7 @@ public int index() { } @Override - public @NotNull Integer next() { + public Integer next() { return array[ordinal++]; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java index 33023f0b..be5be829 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java @@ -8,7 +8,7 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayIterator; import javasabr.rlib.common.util.array.UnsafeArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The fast implementation of the array. This array is not threadsafe. @@ -16,6 +16,7 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class FastArray extends AbstractArray implements UnsafeArray { private static final long serialVersionUID = -8477384427415127978L; @@ -24,27 +25,27 @@ public class FastArray extends AbstractArray implements UnsafeArray { * The unsafe array. */ @SuppressWarnings("NullableProblems") - protected E @NotNull [] array; + protected E [] array; /** * The current size of this array. */ protected int size; - public FastArray(@NotNull Class type) { + public FastArray(Class type) { super(type); } - public FastArray(@NotNull Class type, final int size) { + public FastArray(Class type, final int size) { super(type, size); } - public FastArray(@NotNull E[] array) { + public FastArray(E[] array) { super(array); } @Override - public boolean add(@NotNull E object) { + public boolean add(E object) { if (size == array.length) { array = ArrayUtils.copyOfAndExtend(array, max(array.length >> 1, 1)); @@ -54,7 +55,7 @@ public boolean add(@NotNull E object) { } @Override - public boolean addAll(@NotNull Array elements) { + public boolean addAll(Array elements) { if (elements.isEmpty()) { return false; @@ -74,7 +75,7 @@ public boolean addAll(@NotNull Array elements) { } @Override - public boolean addAll(@NotNull Collection collection) { + public boolean addAll(Collection collection) { if (collection.isEmpty()) { return false; @@ -97,7 +98,7 @@ public boolean addAll(@NotNull Collection collection) { } @Override - public boolean addAll(@NotNull E[] elements) { + public boolean addAll(E[] elements) { if (elements.length < 1) { return false; @@ -117,7 +118,7 @@ public boolean addAll(@NotNull E[] elements) { } @Override - public final @NotNull E[] array() { + public final E[] array() { return array; } @@ -134,7 +135,7 @@ public void prepareForSize(int size) { } @Override - public @NotNull E fastRemove(int index) { + public E fastRemove(int index) { if (index < 0 || index >= size) { throw new NoSuchElementException(); @@ -151,7 +152,7 @@ public void prepareForSize(int size) { } @Override - public final @NotNull E get(int index) { + public final E get(int index) { if (index < 0 || index >= size()) { throw new NoSuchElementException(); @@ -161,7 +162,7 @@ public void prepareForSize(int size) { } @Override - public final @NotNull ArrayIterator iterator() { + public final ArrayIterator iterator() { return new DefaultArrayIterator<>(this); } @@ -172,7 +173,7 @@ public void prepareForSize(int size) { * @param selfSize the self size. * @param targetSize the target size. */ - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + protected void processAdd(Array elements, int selfSize, int targetSize) { System.arraycopy(elements.array(), 0, array, selfSize, targetSize); size = selfSize + targetSize; } @@ -184,13 +185,13 @@ protected void processAdd(@NotNull Array elements, int selfSize, in * @param selfSize the self size. * @param targetSize the target size. */ - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + protected void processAdd(E[] elements, int selfSize, int targetSize) { System.arraycopy(elements, 0, array, selfSize, targetSize); size = selfSize + targetSize; } @Override - public void replace(int index, @NotNull E element) { + public void replace(int index, E element) { if (index < 0 || index >= size) { throw new ArrayIndexOutOfBoundsException(); @@ -200,7 +201,7 @@ public void replace(int index, @NotNull E element) { } @Override - protected final void setArray(E @NotNull [] array) { + protected final void setArray(E [] array) { this.array = array; } @@ -215,7 +216,7 @@ public final int size() { } @Override - public @NotNull E remove(int index) { + public E remove(int index) { if (index < 0 || index >= size) { throw new NoSuchElementException(); @@ -235,7 +236,7 @@ public final int size() { } @Override - public @NotNull FastArray trimToSize() { + public FastArray trimToSize() { if (size == array.length) { return this; @@ -247,13 +248,13 @@ public final int size() { } @Override - public boolean unsafeAdd(@NotNull E object) { + public boolean unsafeAdd(E object) { array[size++] = object; return true; } @Override - public void unsafeSet(int index, @NotNull E element) { + public void unsafeSet(int index, E element) { if (array[index] != null) { size -= 1; } @@ -267,12 +268,12 @@ public E unsafeGet(int index) { } @Override - public @NotNull UnsafeArray asUnsafe() { + public UnsafeArray asUnsafe() { return this; } @Override - public @NotNull FastArray clone() throws CloneNotSupportedException { + public FastArray clone() throws CloneNotSupportedException { var clone = (FastArray) super.clone(); clone.array = ArrayUtils.copyOfAndExtend(array, size()); return clone; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java index 002779e5..f0f4ae87 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.array.impl; import javasabr.rlib.common.util.array.Array; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The fast implementation of the array with checking on duplicates. This array is not threadsafe. @@ -9,25 +9,26 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class FastArraySet extends FastArray { private static final long serialVersionUID = 1L; - public FastArraySet(@NotNull Class type) { + public FastArraySet(Class type) { super(type); } - public FastArraySet(@NotNull Class type, int size) { + public FastArraySet(Class type, int size) { super(type, size); } @Override - public boolean add(@NotNull E element) { + public boolean add(E element) { return !contains(element) && super.add(element); } @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + protected void processAdd(Array elements, int selfSize, int targetSize) { var array = elements.array(); for (int i = 0, length = elements.size(); i < length; i++) { E element = array[i]; @@ -38,7 +39,7 @@ protected void processAdd(@NotNull Array elements, int selfSize, in } @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + protected void processAdd(E[] elements, int selfSize, int targetSize) { for (E element : elements) { if (!contains(element)) { unsafeAdd(element); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java index 07c979b7..d4dbc7de 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastLongArray.java @@ -3,12 +3,14 @@ import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.array.ArrayIterator; import javasabr.rlib.common.util.array.LongArray; +import org.jspecify.annotations.NullMarked; /** * Реализация не потокобезопасного динамического массива примитивов long. * * @author JavaSaBr */ +@NullMarked public class FastLongArray implements LongArray { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java index 80e378a7..e60bc3c9 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java @@ -6,8 +6,8 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayComparator; import javasabr.rlib.common.util.array.ReadOnlyArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The read only version of the {@link FastArray}. @@ -15,54 +15,55 @@ * @param the element's type. * @author JavaSaBr */ +@NullMarked public final class ReadOnlyFastArray extends FastArray implements ReadOnlyArray { - public ReadOnlyFastArray(@NotNull E[] array) { + public ReadOnlyFastArray(E[] array) { super(array); } @Override - public void apply(@NotNull Function function) { + public void apply(Function function) { throw new IllegalStateException("This array is read only."); } @Override - public boolean add(@NotNull E object) { + public boolean add(E object) { throw new IllegalStateException("This array is read only."); } @Override - public boolean addAll(@NotNull Collection collection) { + public boolean addAll(Collection collection) { throw new IllegalStateException("This array is read only."); } @Override - public boolean fastRemove(@NotNull Object object) { + public boolean fastRemove(Object object) { throw new IllegalStateException("This array is read only."); } @Override - public @NotNull E remove(int index) { + public E remove(int index) { throw new IllegalStateException("This array is read only."); } @Override - public boolean addAll(@NotNull Array elements) { + public boolean addAll(Array elements) { throw new IllegalStateException("This array is read only."); } @Override - public boolean addAll(@NotNull E[] elements) { + public boolean addAll(E[] elements) { throw new IllegalStateException("This array is read only."); } @Override - public @NotNull E fastRemove(int index) { + public E fastRemove(int index) { throw new IllegalStateException("This array is read only."); } @Override - public boolean unsafeAdd(@NotNull E object) { + public boolean unsafeAdd(E object) { throw new IllegalStateException("This array is read only."); } @@ -72,12 +73,12 @@ public E unsafeGet(int index) { } @Override - public void unsafeSet(int index, @NotNull E element) { + public void unsafeSet(int index, E element) { throw new IllegalStateException("This array is read only."); } @Override - public void replace(int index, @NotNull E element) { + public void replace(int index, E element) { throw new IllegalStateException("This array is read only."); } @@ -87,7 +88,7 @@ public void clear() { } @Override - public @NotNull Array sort(@NotNull ArrayComparator comparator) { + public Array sort(ArrayComparator comparator) { throw new IllegalStateException("This array is read only."); } @@ -97,27 +98,27 @@ public boolean remove(@Nullable Object object) { } @Override - public boolean removeAll(@NotNull Array target) { + public boolean removeAll(Array target) { throw new IllegalStateException("This array is read only."); } @Override - public boolean removeAll(@NotNull Collection target) { + public boolean removeAll(Collection target) { throw new IllegalStateException("This array is read only."); } @Override - public boolean retainAll(@NotNull Array target) { + public boolean retainAll(Array target) { throw new IllegalStateException("This array is read only."); } @Override - public boolean retainAll(@NotNull Collection target) { + public boolean retainAll(Collection target) { throw new IllegalStateException("This array is read only."); } @Override - public boolean removeIf(@NotNull Predicate filter) { + public boolean removeIf(Predicate filter) { throw new IllegalStateException("This array is read only."); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java index 36d36087..e2bd44b1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyIntegerArray.java @@ -4,24 +4,25 @@ import java.util.Objects; import javasabr.rlib.common.util.array.ArrayIterator; import javasabr.rlib.common.util.array.IntegerArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * Simple implementation of read only integer array. * * @author JavaSaBr */ +@NullMarked public class ReadOnlyIntegerArray implements IntegerArray { protected final int[] array; - public ReadOnlyIntegerArray(int @NotNull [] array) { + public ReadOnlyIntegerArray(int [] array) { this.array = array; } @Override - public final @NotNull int[] array() { + public final int[] array() { return array; } @@ -40,7 +41,7 @@ public final int get(int index) { } @Override - public final @NotNull ArrayIterator iterator() { + public final ArrayIterator iterator() { return new ReadOnlyIterator(); } @@ -100,7 +101,7 @@ public int index() { } @Override - public @NotNull Integer next() { + public Integer next() { return array[ordinal++]; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java index 8113d72a..352d4534 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.common.util.array.Array; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The sorted implementation of the {@link FastArray}. @@ -10,20 +10,21 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class SortedFastArray> extends FastArray { private static final long serialVersionUID = 1L; - public SortedFastArray(@NotNull Class type) { + public SortedFastArray(Class type) { super(type); } - public SortedFastArray(@NotNull Class type, int size) { + public SortedFastArray(Class type, int size) { super(type, size); } @Override - public boolean add(@NotNull E element) { + public boolean add(E element) { if (size == array.length) { array = ArrayUtils.copyOfAndExtend(array, array.length * 3 / 2 + 1); @@ -33,7 +34,7 @@ public boolean add(@NotNull E element) { } @Override - protected void processAdd(@NotNull Array elements, int selfSize, int targetSize) { + protected void processAdd(Array elements, int selfSize, int targetSize) { var array = elements.array(); for (int i = 0, length = elements.size(); i < length; i++) { E element = array[i]; @@ -44,7 +45,7 @@ protected void processAdd(@NotNull Array elements, int selfSize, in } @Override - protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { + protected void processAdd(E[] elements, int selfSize, int targetSize) { for (E element : elements) { if (!contains(element)) { unsafeAdd(element); @@ -53,7 +54,7 @@ protected void processAdd(@NotNull E[] elements, int selfSize, int targetSize) { } @Override - public boolean unsafeAdd(@NotNull E element) { + public boolean unsafeAdd(E element) { E[] array = array(); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java index fe73af1b..3482b9fb 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java @@ -9,7 +9,7 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayIterator; import javasabr.rlib.common.util.array.UnsafeArray; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the array with synchronization all methods. @@ -17,6 +17,7 @@ * @param the array's element type. * @author JavaSaBr */ +@NullMarked public class SynchronizedArray extends AbstractArray implements UnsafeArray { private static final long serialVersionUID = -7288153859732883548L; @@ -31,17 +32,17 @@ public class SynchronizedArray extends AbstractArray implements UnsafeArra */ private volatile E[] array; - public SynchronizedArray(@NotNull Class type) { + public SynchronizedArray(Class type) { this(type, 10); } - public SynchronizedArray(@NotNull Class type, int size) { + public SynchronizedArray(Class type, int size) { super(type, size); this.size = new ReusableAtomicInteger(); } @Override - public synchronized boolean add(@NotNull E element) { + public synchronized boolean add(E element) { if (size() == array.length) { array = ArrayUtils.copyOfAndExtend(array, array.length >> 1); @@ -52,7 +53,7 @@ public synchronized boolean add(@NotNull E element) { } @Override - public synchronized final boolean addAll(@NotNull Array elements) { + public synchronized final boolean addAll(Array elements) { if (elements.isEmpty()) { return true; @@ -72,7 +73,7 @@ public synchronized final boolean addAll(@NotNull Array elements) { } @Override - public synchronized boolean addAll(@NotNull final Collection collection) { + public synchronized boolean addAll(final Collection collection) { if (collection.isEmpty()) { return true; } @@ -90,7 +91,7 @@ public synchronized boolean addAll(@NotNull final Collection collec } @Override - public synchronized final boolean addAll(@NotNull final E[] elements) { + public synchronized final boolean addAll(final E[] elements) { final int current = array.length; final int selfSize = size(); @@ -105,13 +106,11 @@ public synchronized final boolean addAll(@NotNull final E[] elements) { return true; } - @NotNull @Override public final E[] array() { return array; } - @NotNull @Override public synchronized final E fastRemove(final int index) { @@ -128,7 +127,6 @@ public synchronized final E fastRemove(final int index) { return old; } - @NotNull @Override public synchronized final E get(final int index) { @@ -140,12 +138,12 @@ public synchronized final E get(final int index) { } @Override - public synchronized @NotNull ArrayIterator iterator() { + public synchronized ArrayIterator iterator() { return new DefaultArrayIterator<>(this); } @Override - public void replace(int index, @NotNull E element) { + public void replace(int index, E element) { if (index < 0 || index >= size()) { throw new ArrayIndexOutOfBoundsException(); @@ -155,7 +153,7 @@ public void replace(int index, @NotNull E element) { } @Override - protected final void setArray(@NotNull final E[] array) { + protected final void setArray(final E[] array) { this.array = array; } @@ -170,7 +168,7 @@ public final int size() { } @Override - public synchronized @NotNull E remove(int index) { + public synchronized E remove(int index) { if (index < 0 || index >= size()) { throw new NoSuchElementException(); @@ -190,7 +188,7 @@ public final int size() { } @Override - public synchronized @NotNull SynchronizedArray trimToSize() { + public synchronized SynchronizedArray trimToSize() { var size = size(); @@ -202,12 +200,12 @@ public final int size() { return this; } - protected void processAdd(@NotNull final Array elements, final int selfSize, final int targetSize) { + protected void processAdd(final Array elements, final int selfSize, final int targetSize) { System.arraycopy(elements.array(), 0, array, selfSize, targetSize); size.set(selfSize + targetSize); } - protected void processAdd(@NotNull final E[] elements, final int selfSize, final int targetSize) { + protected void processAdd(final E[] elements, final int selfSize, final int targetSize) { System.arraycopy(elements, 0, array, selfSize, targetSize); size.set(selfSize + targetSize); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java index e80b86cc..3c471efd 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/crypt/SymmetryCrypt.java @@ -9,31 +9,29 @@ import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The symmetry crypt based on RC4. * * @author JavaSaBr */ +@NullMarked public class SymmetryCrypt { /** * The crypter. */ - @NotNull private final Cipher ecipher; /** * The encrypter. */ - @NotNull private final Cipher dcipher; /** * THe secret key. */ - @NotNull private final SecretKey secretKey; /** @@ -45,7 +43,7 @@ public class SymmetryCrypt { * @throws UnsupportedEncodingException the unsupported encoding exception * @throws InvalidKeyException the invalid key exception */ - public SymmetryCrypt(@NotNull final String key) + public SymmetryCrypt(final String key) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException { final Cipher ecipher = Cipher.getInstance("RC4"); @@ -91,7 +89,7 @@ public String getFormat() { * @throws IllegalBlockSizeException the illegal block size exception * @throws BadPaddingException the bad padding exception */ - public void decrypt(@NotNull final byte[] in, final int offset, final int length, @NotNull final byte[] out) + public void decrypt(final byte[] in, final int offset, final int length, final byte[] out) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { dcipher.doFinal(in, offset, length, out, offset); } @@ -107,7 +105,7 @@ public void decrypt(@NotNull final byte[] in, final int offset, final int length * @throws IllegalBlockSizeException the illegal block size exception * @throws BadPaddingException the bad padding exception */ - public void encrypt(@NotNull final byte[] in, final int offset, final int length, @NotNull final byte[] out) + public void encrypt(final byte[] in, final int offset, final int length, final byte[] out) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { ecipher.doFinal(in, offset, length, out, offset); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java index 13eaa669..34bd603e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The base implementation of the {@link ConcurrentIntegerDictionary}. @@ -10,12 +10,13 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public abstract class AbstractConcurrentIntegerDictionary extends AbstractIntegerDictionary implements ConcurrentIntegerDictionary { - private final @NotNull ReusableAtomicInteger size; + private final ReusableAtomicInteger size; - private volatile @NotNull IntegerEntry[] entries; + private volatile IntegerEntry[] entries; private volatile int threshold; @@ -38,12 +39,12 @@ protected AbstractConcurrentIntegerDictionary(float loadFactor, int initCapacity } @Override - public void setEntries(@NotNull IntegerEntry[] entries) { + public void setEntries(IntegerEntry[] entries) { this.entries = entries; } @Override - public IntegerEntry @NotNull [] entries() { + public IntegerEntry [] entries() { return entries; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java index 342532f7..adc3736a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The base implementation of the {@link ConcurrentLongDictionary}. @@ -10,12 +10,13 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public abstract class AbstractConcurrentLongDictionary extends AbstractLongDictionary implements ConcurrentLongDictionary { - private final @NotNull ReusableAtomicInteger size; + private final ReusableAtomicInteger size; - private volatile @NotNull LongEntry[] entries; + private volatile LongEntry[] entries; private volatile int threshold; @@ -38,12 +39,12 @@ protected AbstractConcurrentLongDictionary(float loadFactor, int initCapacity) { } @Override - protected void setEntries(@NotNull LongEntry[] entries) { + protected void setEntries(LongEntry[] entries) { this.entries = entries; } @Override - public LongEntry @NotNull [] entries() { + public LongEntry [] entries() { return entries; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java index 4f66ce53..1bf746c7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.concurrent.atomic.ReusableAtomicInteger; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The base implementation of the {@link ConcurrentObjectDictionary}. @@ -11,12 +11,13 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public abstract class AbstractConcurrentObjectDictionary extends AbstractObjectDictionary implements ConcurrentObjectDictionary { - private final @NotNull ReusableAtomicInteger size; + private final ReusableAtomicInteger size; - private volatile @NotNull ObjectEntry[] entries; + private volatile ObjectEntry[] entries; private volatile int threshold; @@ -39,12 +40,12 @@ protected AbstractConcurrentObjectDictionary(float loadFactor, int initCapacity) } @Override - public void setEntries(@NotNull ObjectEntry[] entries) { + public void setEntries(ObjectEntry[] entries) { this.entries = entries; } @Override - public ObjectEntry @NotNull [] entries() { + public ObjectEntry [] entries() { return entries; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java index f8115191..df6b5536 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java @@ -7,8 +7,8 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.pools.PoolFactory; import javasabr.rlib.common.util.pools.ReusablePool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of the {@link Dictionary}. @@ -17,6 +17,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public abstract class AbstractDictionary> implements Dictionary { /** @@ -85,7 +86,7 @@ protected AbstractDictionary(float loadFactor, int initCapacity) { } @Override - public final void apply(@NotNull NotNullFunction function) { + public final void apply(NotNullFunction function) { for (var entry : entries()) { while (entry != null) { entry.setValue(function.apply(entry.getValue())); @@ -129,7 +130,7 @@ public final boolean containsValue(@Nullable V value) { } @Override - public final void forEach(@NotNull Consumer consumer) { + public final void forEach(Consumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(entry.getValue()); @@ -165,7 +166,7 @@ protected final void resize(int newLength) { * * @param newEntries the new array of entries. */ - private void transfer(@NotNull E[] newEntries) { + private void transfer(E[] newEntries) { var entries = entries(); var newCapacity = newEntries.length; @@ -190,7 +191,7 @@ private void transfer(@NotNull E[] newEntries) { } @Override - public final @NotNull Array values(@NotNull Array container) { + public final Array values(Array container) { var unsafeArray = container.asUnsafe(); unsafeArray.prepareForSize(container.size() + size()); @@ -210,21 +211,21 @@ private void transfer(@NotNull E[] newEntries) { * * @return the entries type. */ - protected abstract @NotNull Class getEntryType(); + protected abstract Class getEntryType(); /** * Set new array of entries of this {@link Dictionary}. * * @param entries the new array of entries. */ - protected abstract void setEntries(@NotNull E[] entries); + protected abstract void setEntries(E[] entries); /** * Get an array of all entries in this dictionary.. * * @return the array of entries. */ - protected abstract E @NotNull [] entries(); + protected abstract E [] entries(); /** * Set the next size value at which to resize (capacity * load factor). diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java index cabe22e8..099fbb4f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java @@ -9,8 +9,8 @@ import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.array.IntegerArray; import javasabr.rlib.common.util.array.MutableIntegerArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of {@link IntegerDictionary}. @@ -18,6 +18,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public abstract class AbstractIntegerDictionary extends AbstractDictionary> implements UnsafeIntegerDictionary { @@ -30,7 +31,7 @@ protected AbstractIntegerDictionary(float loadFactor, int initCapacity) { } @Override - protected @NotNull Class> getEntryType() { + protected Class> getEntryType() { return IntegerEntry.class; } @@ -42,7 +43,7 @@ protected AbstractIntegerDictionary(float loadFactor, int initCapacity) { * @param value the value of the key. * @param index the index of bucket. */ - protected final void addEntry(int hash, int key, @NotNull V value, int index) { + protected final void addEntry(int hash, int key, V value, int index) { var entries = entries(); var entry = entries[index]; @@ -63,7 +64,7 @@ public final boolean containsKey(int key) { } @Override - public void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { + public void forEach(IntObjectConsumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(entry.getKey(), entry.getValue()); @@ -74,8 +75,8 @@ public void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { @Override public void forEach( - @NotNull T argument, - @NotNull IntBiObjectConsumer<@NotNull ? super V, @NotNull ? super T> consumer) { + T argument, + IntBiObjectConsumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(entry.getKey(), entry.getValue(), argument); @@ -91,7 +92,7 @@ public void forEach( } @Override - public @NotNull V getOrCompute(int key, @NotNull Supplier<@NotNull V> factory) { + public V getOrCompute(int key, Supplier factory) { var entry = getEntry(key); @@ -108,7 +109,7 @@ public void forEach( } @Override - public @NotNull V getOrCompute(int key, @NotNull IntFunction<@NotNull V> factory) { + public V getOrCompute(int key, IntFunction factory) { var entry = getEntry(key); @@ -125,7 +126,7 @@ public void forEach( } @Override - public @Nullable V getOrCompute(int key, @NotNull T argument, @NotNull Function<@NotNull T, @NotNull V> factory) { + public @Nullable V getOrCompute(int key, T argument, Function factory) { var entry = getEntry(key); @@ -163,12 +164,12 @@ public void forEach( } @Override - public final @NotNull Iterator iterator() { + public final Iterator iterator() { return new IntegerDictionaryIterator<>(this); } @Override - public @NotNull IntegerArray keyArray(@NotNull MutableIntegerArray container) { + public IntegerArray keyArray(MutableIntegerArray container) { for (var entry : entries()) { while (entry != null) { @@ -181,7 +182,7 @@ public void forEach( } @Override - public void copyTo(@NotNull Dictionary dictionary) { + public void copyTo(Dictionary dictionary) { if (isEmpty() || !(dictionary instanceof IntegerDictionary)) { return; @@ -198,7 +199,7 @@ public void copyTo(@NotNull Dictionary dictionary) { } @Override - public final @Nullable V put(int key, @NotNull V value) { + public final @Nullable V put(int key, V value) { var entries = entries(); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java index 56f4a8a6..afeb1f2e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java @@ -8,8 +8,8 @@ import javasabr.rlib.common.function.LongObjectConsumer; import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.array.LongArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of the {@link LongDictionary}. @@ -17,6 +17,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public abstract class AbstractLongDictionary extends AbstractDictionary> implements UnsafeLongDictionary { @@ -37,7 +38,7 @@ protected AbstractLongDictionary(float loadFactor, int initCapacity) { } @Override - protected @NotNull Class> getEntryType() { + protected Class> getEntryType() { return LongEntry.class; } @@ -49,7 +50,7 @@ protected AbstractLongDictionary(float loadFactor, int initCapacity) { * @param value the value of the key. * @param index the index of bucket. */ - private void addEntry(int hash, long key, @NotNull V value, int index) { + private void addEntry(int hash, long key, V value, int index) { var entries = entries(); var entry = entries[index]; @@ -76,7 +77,7 @@ public final boolean containsKey(long key) { } @Override - public @NotNull V getOrCompute(long key, @NotNull Supplier<@NotNull V> factory) { + public V getOrCompute(long key, Supplier factory) { var entry = getEntry(key); @@ -93,7 +94,7 @@ public final boolean containsKey(long key) { } @Override - public @NotNull V getOrCompute(long key, @NotNull LongFunction<@NotNull V> factory) { + public V getOrCompute(long key, LongFunction factory) { var entry = getEntry(key); @@ -112,8 +113,8 @@ public final boolean containsKey(long key) { @Override public @Nullable V getOrCompute( long key, - @NotNull T argument, - @NotNull Function<@NotNull T, @NotNull V> factory) { + T argument, + Function factory) { var entry = getEntry(key); @@ -157,7 +158,7 @@ public final Iterator iterator() { } @Override - public @NotNull LongArray keyArray(@NotNull LongArray container) { + public LongArray keyArray(LongArray container) { for (var entry : entries()) { while (entry != null) { @@ -170,7 +171,7 @@ public final Iterator iterator() { } @Override - public void copyTo(@NotNull Dictionary dictionary) { + public void copyTo(Dictionary dictionary) { if (isEmpty() || !(dictionary instanceof LongDictionary)) { return; @@ -187,7 +188,7 @@ public void copyTo(@NotNull Dictionary dictionary) { } @Override - public V put(long key, @NotNull V value) { + public V put(long key, V value) { var entries = entries(); var hash = hash(key); @@ -285,7 +286,7 @@ public final String toString() { } @Override - public void forEach(@NotNull T argument, @NotNull LongBiObjectConsumer<@NotNull V, @NotNull T> consumer) { + public void forEach(T argument, LongBiObjectConsumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(entry.getKey(), entry.getValue(), argument); @@ -295,7 +296,7 @@ public void forEach(@NotNull T argument, @NotNull LongBiObjectConsumer<@NotN } @Override - public void forEach(@NotNull LongObjectConsumer<@NotNull V> consumer) { + public void forEach(LongObjectConsumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(entry.getKey(), entry.getValue()); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java index 096e514a..e2998959 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java @@ -9,8 +9,8 @@ import javasabr.rlib.common.function.NotNullTripleConsumer; import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.array.Array; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The base implementation of the {@link ObjectDictionary}. @@ -19,6 +19,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public abstract class AbstractObjectDictionary extends AbstractDictionary> implements UnsafeObjectDictionary { @@ -39,7 +40,7 @@ protected AbstractObjectDictionary(float loadFactor, int initCapacity) { } @Override - protected @NotNull Class> getEntryType() { + protected Class> getEntryType() { return ObjectEntry.class; } @@ -67,18 +68,18 @@ private void addEntry(int hash, K key, V value, int index) { } @Override - public final boolean containsKey(@NotNull K key) { + public final boolean containsKey(K key) { return getEntry(key) != null; } @Override - public @Nullable V get(@NotNull K key) { + public @Nullable V get(K key) { var entry = getEntry(key); return entry == null ? null : entry.getValue(); } @Override - public @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullSupplier factory) { + public V getOrCompute(K key, NotNullSupplier factory) { var entry = getEntry(key); @@ -96,7 +97,7 @@ public final boolean containsKey(@NotNull K key) { } @Override - public @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullFunction factory) { + public V getOrCompute(K key, NotNullFunction factory) { var entry = getEntry(key); @@ -114,7 +115,7 @@ public final boolean containsKey(@NotNull K key) { } @Override - public @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullFunction factory) { + public V getOrCompute(K key, T argument, NotNullFunction factory) { var entry = getEntry(key); @@ -132,7 +133,7 @@ public final boolean containsKey(@NotNull K key) { } @Override - public @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullBiFunction factory) { + public V getOrCompute(K key, T argument, NotNullBiFunction factory) { var entry = getEntry(key); @@ -177,7 +178,7 @@ public final Iterator iterator() { } @Override - public final @NotNull Array keyArray(@NotNull Array container) { + public final Array keyArray(Array container) { var unsafeArray = container.asUnsafe(); unsafeArray.prepareForSize(container.size() + size()); @@ -194,7 +195,7 @@ public final Iterator iterator() { } @Override - public void copyTo(@NotNull Dictionary dictionary) { + public void copyTo(Dictionary dictionary) { if (isEmpty() || !(dictionary instanceof ObjectDictionary)) { return; @@ -212,7 +213,7 @@ public void copyTo(@NotNull Dictionary dictionary) { } @Override - public @Nullable V put(@NotNull K key, @NotNull V value) { + public @Nullable V put(K key, V value) { var entries = entries(); @@ -230,7 +231,7 @@ public void copyTo(@NotNull Dictionary dictionary) { } @Override - public @Nullable V remove(@NotNull K key) { + public @Nullable V remove(K key) { var old = removeEntryForKey(key); @@ -246,7 +247,7 @@ public void copyTo(@NotNull Dictionary dictionary) { } @Override - public @Nullable ObjectEntry removeEntryForKey(@NotNull K key) { + public @Nullable ObjectEntry removeEntryForKey(K key) { var entries = entries(); @@ -311,7 +312,7 @@ public final String toString() { } @Override - public void forEach(@NotNull NotNullBiConsumer consumer) { + public void forEach(NotNullBiConsumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(entry.getKey(), entry.getValue()); @@ -322,8 +323,8 @@ public void forEach(@NotNull NotNullBiConsumer consumer) { @Override public void forEach( - @NotNull T argument, - @NotNull NotNullTripleConsumer consumer) { + T argument, + NotNullTripleConsumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(argument, entry.getKey(), entry.getValue()); @@ -334,9 +335,9 @@ public void forEach( @Override public void forEach( - @NotNull F first, - @NotNull S second, - @NotNull FourObjectConsumer<@NotNull ? super F, @NotNull ? super S, @NotNull ? super K, @NotNull ? super V> consumer) { + F first, + S second, + FourObjectConsumer consumer) { for (var entry : entries()) { while (entry != null) { consumer.accept(first, second, entry.getKey(), entry.getValue()); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java index b6d3d785..9b943a0a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockIntegerDictionary.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.concurrent.lock.AsyncReadSyncWriteLock; import javasabr.rlib.common.concurrent.lock.LockFactory; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the {@link ConcurrentIntegerDictionary} using {@link LockFactory#newAtomicARSWLock()}*. @@ -10,12 +10,12 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class ConcurrentAtomicARSWLockIntegerDictionary extends AbstractConcurrentIntegerDictionary { /** * The lock. */ - @NotNull private final AsyncReadSyncWriteLock lock; public ConcurrentAtomicARSWLockIntegerDictionary() { diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java index a6088201..588d5e46 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockLongDictionary.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.concurrent.lock.AsyncReadSyncWriteLock; import javasabr.rlib.common.concurrent.lock.LockFactory; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the {@link ConcurrentLongDictionary} using {@link LockFactory#newAtomicARSWLock()}*. @@ -10,12 +10,12 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class ConcurrentAtomicARSWLockLongDictionary extends AbstractConcurrentLongDictionary { /** * The lock. */ - @NotNull private final AsyncReadSyncWriteLock lock; public ConcurrentAtomicARSWLockLongDictionary() { diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java index 305b0b13..c70f04a8 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentAtomicARSWLockObjectDictionary.java @@ -2,7 +2,7 @@ import javasabr.rlib.common.concurrent.lock.AsyncReadSyncWriteLock; import javasabr.rlib.common.concurrent.lock.LockFactory; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the {@link ConcurrentObjectDictionary} using {@link LockFactory#newAtomicARSWLock()}*. @@ -11,12 +11,12 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class ConcurrentAtomicARSWLockObjectDictionary extends AbstractConcurrentObjectDictionary { /** * The lock. */ - @NotNull private final AsyncReadSyncWriteLock lock; public ConcurrentAtomicARSWLockObjectDictionary() { diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java index 76550dbd..f6b09d0a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java @@ -1,5 +1,7 @@ package javasabr.rlib.common.util.dictionary; +import org.jspecify.annotations.NullMarked; + /** * The interface with methods for supporting threadsafe for the {@link Dictionary}. * @@ -7,6 +9,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface ConcurrentDictionary extends Dictionary { /** diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java index 8aaf2f3f..85004309 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.util.dictionary; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface with methods for supporting threadsafe for the {@link IntegerDictionary}. @@ -8,6 +8,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface ConcurrentIntegerDictionary extends IntegerDictionary, ConcurrentDictionary { /** @@ -17,7 +18,7 @@ public interface ConcurrentIntegerDictionary extends IntegerDictionary, Co * @param the value's type. * @return the new concurrent integer dictionary. */ - static @NotNull ConcurrentIntegerDictionary ofType(@NotNull Class valueType) { + static ConcurrentIntegerDictionary ofType(Class valueType) { return DictionaryFactory.newConcurrentAtomicIntegerDictionary(); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java index 228a121f..476e8691 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java @@ -1,6 +1,6 @@ package javasabr.rlib.common.util.dictionary; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface with methods for supporting threadsafe for the {@link LongDictionary}. @@ -8,6 +8,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface ConcurrentLongDictionary extends LongDictionary, ConcurrentDictionary { /** @@ -17,7 +18,7 @@ public interface ConcurrentLongDictionary extends LongDictionary, Concurre * @param the value's type. * @return the new concurrent long dictionary. */ - static @NotNull ConcurrentLongDictionary ofType(@NotNull Class valueType) { + static ConcurrentLongDictionary ofType(Class valueType) { return DictionaryFactory.newConcurrentAtomicLongDictionary(); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java index 891ada2e..f5d09356 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java @@ -5,8 +5,8 @@ import javasabr.rlib.common.function.NotNullNullableBiFunction; import javasabr.rlib.common.function.NotNullNullableTripleFunction; import javasabr.rlib.common.function.NotNullTripleConsumer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface with methods for supporting thread-safe for the {@link ObjectDictionary}. @@ -15,6 +15,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface ConcurrentObjectDictionary extends ObjectDictionary, ConcurrentDictionary { /** @@ -24,7 +25,7 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @param the key's and value's type. * @return the new concurrent object dictionary. */ - static @NotNull ObjectDictionary ofType(@NotNull Class keyValueType) { + static ObjectDictionary ofType(Class keyValueType) { return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); } @@ -37,9 +38,9 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @param the value's type. * @return the new concurrent object dictionary. */ - static @NotNull ConcurrentObjectDictionary ofType( - @NotNull Class keyType, - @NotNull Class valueType) { + static ConcurrentObjectDictionary ofType( + Class keyType, + Class valueType) { return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); } @@ -51,9 +52,9 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @param the argument's type. * @return this dictionary. */ - default @NotNull ConcurrentObjectDictionary runInReadLock( - @NotNull A argument, - @NotNull NotNullBiConsumer, A> consumer) { + default ConcurrentObjectDictionary runInReadLock( + A argument, + NotNullBiConsumer, A> consumer) { var stamp = readLock(); try { @@ -71,8 +72,8 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @param consumer the function. * @return this dictionary. */ - default @NotNull ConcurrentObjectDictionary runInWriteLock( - @NotNull NotNullConsumer> consumer) { + default ConcurrentObjectDictionary runInWriteLock( + NotNullConsumer> consumer) { var stamp = writeLock(); try { @@ -92,9 +93,9 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @param the argument's type. * @return this dictionary. */ - default @NotNull ConcurrentObjectDictionary runInWriteLock( - @NotNull A argument, - @NotNull NotNullBiConsumer, A> consumer) { + default ConcurrentObjectDictionary runInWriteLock( + A argument, + NotNullBiConsumer, A> consumer) { var stamp = writeLock(); try { @@ -116,10 +117,10 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @param the second argument's type. * @return this dictionary. */ - default @NotNull ConcurrentObjectDictionary runInWriteLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullTripleConsumer, F, S> consumer) { + default ConcurrentObjectDictionary runInWriteLock( + F first, + S second, + NotNullTripleConsumer, F, S> consumer) { var stamp = writeLock(); try { @@ -141,8 +142,8 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @return the result of the function. */ default @Nullable R getInReadLock( - @NotNull A argument, - @NotNull NotNullNullableBiFunction, A, R> function) { + A argument, + NotNullNullableBiFunction, A, R> function) { var stamp = readLock(); try { return function.apply(this, argument); @@ -163,9 +164,9 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @return the result of the function. */ default @Nullable R getInReadLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullNullableTripleFunction, F, S, R> function) { + F first, + S second, + NotNullNullableTripleFunction, F, S, R> function) { var stamp = readLock(); try { return function.apply(this, first, second); @@ -184,8 +185,8 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @return the result of the function. */ default @Nullable R getInWriteLock( - @NotNull A argument, - @NotNull NotNullNullableBiFunction, A, R> function) { + A argument, + NotNullNullableBiFunction, A, R> function) { var stamp = writeLock(); try { return function.apply(this, argument); @@ -206,9 +207,9 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * @return the result of the function. */ default @Nullable R getInWriteLock( - @NotNull F first, - @NotNull S second, - @NotNull NotNullNullableTripleFunction, F, S, R> function) { + F first, + S second, + NotNullNullableTripleFunction, F, S, R> function) { var stamp = writeLock(); try { return function.apply(this, first, second); @@ -222,7 +223,7 @@ public interface ConcurrentObjectDictionary extends ObjectDictionary * * @param consumer the consumer. */ - default void forEachInReadLock(@NotNull NotNullBiConsumer consumer) { + default void forEachInReadLock(NotNullBiConsumer consumer) { var stamp = readLock(); try { forEach(consumer); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java index 4cb9c7d5..59c9e51f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java @@ -2,7 +2,7 @@ import java.util.concurrent.locks.StampedLock; import javasabr.rlib.common.concurrent.lock.LockFactory; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of the {@link ConcurrentObjectDictionary} using {@link LockFactory#newAtomicARSWLock()}*. @@ -11,9 +11,10 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class ConcurrentStampedLockObjectDictionary extends AbstractConcurrentObjectDictionary { - private final @NotNull StampedLock lock; + private final StampedLock lock; public ConcurrentStampedLockObjectDictionary() { this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java index f8fcda1f..d912e7c4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java @@ -4,7 +4,7 @@ import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayFactory; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The interface for implementing a key-value dictionary. @@ -13,6 +13,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface Dictionary extends Iterable, Reusable { /** @@ -20,7 +21,7 @@ public interface Dictionary extends Iterable, Reusable { * * @param function the function. */ - default void apply(@NotNull NotNullFunction function) { + default void apply(NotNullFunction function) { throw new UnsupportedOperationException(); } @@ -37,7 +38,7 @@ default void clear() { * @param value the value. * @return true if this dictionary contains the value. */ - default boolean containsValue(@NotNull V value) { + default boolean containsValue(V value) { throw new UnsupportedOperationException(); } @@ -60,14 +61,14 @@ default boolean isEmpty() { * * @param dictionary the dictionary. */ - void copyTo(@NotNull Dictionary dictionary); + void copyTo(Dictionary dictionary); /** * Put all data from the dictionary to this dictionary. * * @param dictionary the dictionary with new data. */ - default void put(@NotNull Dictionary dictionary) { + default void put(Dictionary dictionary) { dictionary.copyTo(this); } @@ -86,7 +87,7 @@ default int size() { * @param container the container to store the values. * @return the container with all values from this dictionary. */ - default @NotNull Array values(@NotNull Array container) { + default Array values(Array container) { throw new UnsupportedOperationException(); } @@ -96,7 +97,7 @@ default int size() { * @param type the value's type. * @return the array with all values from this dictionary. */ - default @NotNull Array values(@NotNull Class type) { + default Array values(Class type) { return values(ArrayFactory.newArray(type, size())); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java index c9210731..40e8aed1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java @@ -11,13 +11,14 @@ import java.util.function.Supplier; import java.util.stream.Collector; import javasabr.rlib.common.util.ObjectUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The collectors to {@link Dictionary} * * @author JavaSaBr */ +@NullMarked public final class DictionaryCollectors { static final Set CH_ID = unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); @@ -37,11 +38,11 @@ static class CollectorImpl implements Collector { private final Set characteristics; CollectorImpl( - @NotNull Supplier supplier, - @NotNull BiConsumer accumulator, - @NotNull BinaryOperator combiner, - @NotNull Function finisher, - @NotNull Set characteristics) { + Supplier supplier, + BiConsumer accumulator, + BinaryOperator combiner, + Function finisher, + Set characteristics) { this.supplier = supplier; this.accumulator = accumulator; this.combiner = combiner; @@ -50,10 +51,10 @@ static class CollectorImpl implements Collector { } CollectorImpl( - @NotNull Supplier supplier, - @NotNull BiConsumer accumulator, - @NotNull BinaryOperator combiner, - @NotNull Set characteristics) { + Supplier supplier, + BiConsumer accumulator, + BinaryOperator combiner, + Set characteristics) { this(supplier, accumulator, combiner, a -> (R) a, characteristics); } @@ -83,9 +84,9 @@ public Set characteristics() { } } - public static @NotNull Collector> toObjectDictionary( - @NotNull Function keyMapper, - @NotNull Function valueMapper) { + public static Collector> toObjectDictionary( + Function keyMapper, + Function valueMapper) { return new CollectorImpl<>( DictionaryFactory::newObjectDictionary, uniqKeysAccumulator(keyMapper, valueMapper), @@ -93,9 +94,9 @@ public Set characteristics() { CH_ID); } - public static @NotNull Collector> toLongDictionary( - @NotNull Function keyMapper, - @NotNull Function valueMapper) { + public static Collector> toLongDictionary( + Function keyMapper, + Function valueMapper) { return new CollectorImpl<>( DictionaryFactory::newLongDictionary, uniqLongsAccumulator(keyMapper, valueMapper), @@ -115,8 +116,8 @@ public Set characteristics() { * @return an accumulating consumer. */ private static BiConsumer, T> uniqKeysAccumulator( - @NotNull Function keyMapper, - @NotNull Function valueMapper) { + Function keyMapper, + Function valueMapper) { return (map, element) -> { K key = keyMapper.apply(element); @@ -140,8 +141,8 @@ private static BiConsumer, T> uniqKeysAccumulat * @return an accumulating consumer. */ private static BiConsumer, T> uniqLongsAccumulator( - @NotNull Function keyMapper, - @NotNull Function valueMapper) { + Function keyMapper, + Function valueMapper) { return (map, element) -> { var key = keyMapper.apply(element); diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java index 7697650a..09e1efc7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java @@ -1,86 +1,87 @@ package javasabr.rlib.common.util.dictionary; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The factory for creating new {@link Dictionary}. * * @author JavaSaBr */ +@NullMarked public final class DictionaryFactory { public static final ObjectDictionary EMPTY_OD = new ReadOnlyFastObjectDictionary<>(); public static final LongDictionary EMPTY_LD = new ReadOnlyFastLongDictionary<>(); - public static @NotNull ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary() { + public static ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary() { return new ConcurrentAtomicARSWLockIntegerDictionary<>(); } - public static @NotNull ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary( + public static ConcurrentIntegerDictionary newConcurrentAtomicIntegerDictionary( float loadFactor, int initCapacity) { return new ConcurrentAtomicARSWLockIntegerDictionary<>(loadFactor, initCapacity); } - public static @NotNull ConcurrentLongDictionary newConcurrentAtomicLongDictionary() { + public static ConcurrentLongDictionary newConcurrentAtomicLongDictionary() { return new ConcurrentAtomicARSWLockLongDictionary<>(); } - public static @NotNull ConcurrentLongDictionary newConcurrentAtomicLongDictionary( + public static ConcurrentLongDictionary newConcurrentAtomicLongDictionary( float loadFactor, int initCapacity) { return new ConcurrentAtomicARSWLockLongDictionary<>(loadFactor, initCapacity); } - public static @NotNull ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary() { + public static ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary() { return new ConcurrentAtomicARSWLockObjectDictionary<>(); } - public static @NotNull ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary( + public static ConcurrentObjectDictionary newConcurrentAtomicObjectDictionary( float loadFactor, int initCapacity) { return new ConcurrentAtomicARSWLockObjectDictionary<>(loadFactor, initCapacity); } - public static @NotNull ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary() { + public static ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary() { return new ConcurrentStampedLockObjectDictionary<>(); } - public static @NotNull ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary( + public static ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary( float loadFactor, int initCapacity) { return new ConcurrentStampedLockObjectDictionary<>(loadFactor, initCapacity); } - public static @NotNull IntegerDictionary newIntegerDictionary() { + public static IntegerDictionary newIntegerDictionary() { return new FastIntegerDictionary<>(); } - public static @NotNull IntegerDictionary newIntegerDictionary(float loadFactor, int initCapacity) { + public static IntegerDictionary newIntegerDictionary(float loadFactor, int initCapacity) { return new FastIntegerDictionary<>(loadFactor, initCapacity); } - public static @NotNull LongDictionary newLongDictionary() { + public static LongDictionary newLongDictionary() { return new FastLongDictionary<>(); } - public static @NotNull LongDictionary newLongDictionary(int initCapacity) { + public static LongDictionary newLongDictionary(int initCapacity) { return new FastLongDictionary<>(initCapacity); } - public static @NotNull LongDictionary newLongDictionary(float loadFactor, int initCapacity) { + public static LongDictionary newLongDictionary(float loadFactor, int initCapacity) { return new FastLongDictionary<>(loadFactor, initCapacity); } - public static @NotNull ObjectDictionary newObjectDictionary() { + public static ObjectDictionary newObjectDictionary() { return new FastObjectDictionary<>(); } - public static @NotNull ObjectDictionary newObjectDictionary(float loadFactor, int initCapacity) { + public static ObjectDictionary newObjectDictionary(float loadFactor, int initCapacity) { return new FastObjectDictionary<>(loadFactor, initCapacity); } - public static @NotNull ObjectDictionary newReadOnlyObjectDictionary(@NotNull Object... values) { + public static ObjectDictionary newReadOnlyObjectDictionary(Object... values) { return new ReadOnlyFastObjectDictionary<>(values); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java index 9160b915..3dcc8372 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java @@ -1,9 +1,10 @@ package javasabr.rlib.common.util.dictionary; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; +@NullMarked public interface Entry extends Reusable { /** @@ -11,7 +12,8 @@ public interface Entry extends Reusable { * * @return the next entry. */ - @Nullable T getNext(); + @Nullable + T getNext(); /** * Set the next entry. @@ -25,7 +27,7 @@ public interface Entry extends Reusable { * * @return the value. */ - @NotNull V getValue(); + V getValue(); /** * Set the value. @@ -33,7 +35,7 @@ public interface Entry extends Reusable { * @param value the new value of this entry. * @return the old value of null. */ - @NotNull V setValue(@NotNull V value); + V setValue(V value); /** * Get the hash. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java index 8d02b682..5cb313a7 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.dictionary; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The fast implementation of {@link IntegerDictionary} without threadsafe supporting. @@ -9,9 +9,10 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class FastIntegerDictionary extends AbstractIntegerDictionary implements UnsafeIntegerDictionary { - private @NotNull IntegerEntry[] entries; + private IntegerEntry[] entries; private int threshold; private int size; @@ -39,12 +40,12 @@ public void setSize(int size) { } @Override - public void setEntries(@NotNull IntegerEntry[] entries) { + public void setEntries(IntegerEntry[] entries) { this.entries = entries; } @Override - public IntegerEntry @NotNull [] entries() { + public IntegerEntry [] entries() { return entries; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java index bc7d53ff..bdac1f9f 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.dictionary; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The fast implementation of {@link LongDictionary} without threadsafe supporting. @@ -9,9 +9,10 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class FastLongDictionary extends AbstractLongDictionary { - private @NotNull LongEntry[] entries; + private LongEntry[] entries; private int threshold; private int size; @@ -39,12 +40,12 @@ public void setSize(int size) { } @Override - public void setEntries(@NotNull LongEntry[] content) { + public void setEntries(LongEntry[] content) { this.entries = content; } @Override - public LongEntry @NotNull [] entries() { + public LongEntry [] entries() { return entries; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java index d168a606..86016e50 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.dictionary; import javasabr.rlib.common.util.ArrayUtils; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; /** * The fast implementation of {@link ObjectDictionary} without threadsafe supporting. @@ -10,9 +10,10 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class FastObjectDictionary extends AbstractObjectDictionary { - private @NotNull ObjectEntry[] entries; + private ObjectEntry[] entries; private int threshold; private int size; @@ -40,12 +41,12 @@ public void setSize(int size) { } @Override - public void setEntries(@NotNull ObjectEntry[] entries) { + public void setEntries(ObjectEntry[] entries) { this.entries = entries; } @Override - public ObjectEntry @NotNull [] entries() { + public ObjectEntry [] entries() { return entries; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java index 8ef9270f..eaa824e1 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java @@ -8,8 +8,8 @@ import javasabr.rlib.common.util.array.ArrayFactory; import javasabr.rlib.common.util.array.IntegerArray; import javasabr.rlib.common.util.array.MutableIntegerArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface to implement a dictionary which uses int as key. @@ -17,6 +17,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface IntegerDictionary extends Dictionary { /** @@ -26,7 +27,7 @@ public interface IntegerDictionary extends Dictionary { * @param the value's type. * @return the new integer dictionary. */ - static @NotNull IntegerDictionary ofType(@NotNull Class valueType) { + static IntegerDictionary ofType(Class valueType) { return DictionaryFactory.newIntegerDictionary(); } @@ -37,7 +38,7 @@ public interface IntegerDictionary extends Dictionary { * @param the value's type. * @return the new integer dictionary. */ - static @NotNull IntegerDictionary of(@NotNull Object... values) { + static IntegerDictionary of(Object... values) { if (values.length < 2 || values.length % 2 != 0) { throw new IllegalArgumentException("Incorrect argument's count."); @@ -82,7 +83,7 @@ default boolean containsKey(int key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute(int key, @NotNull Supplier<@NotNull V> factory) { + default V getOrCompute(int key, Supplier factory) { throw new UnsupportedOperationException(); } @@ -94,7 +95,7 @@ default boolean containsKey(int key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute(int key, @NotNull IntFunction<@NotNull V> factory) { + default V getOrCompute(int key, IntFunction factory) { throw new UnsupportedOperationException(); } @@ -110,7 +111,7 @@ default boolean containsKey(int key) { * @see #getOrCompute(int, Object, Function) */ - default @Nullable V get(int key, @Nullable T argument, @NotNull Function factory) { + default @Nullable V get(int key, @Nullable T argument, Function factory) { return getOrCompute(key, argument, factory); } @@ -126,8 +127,8 @@ default boolean containsKey(int key) { */ default @Nullable V getOrCompute( int key, - @NotNull T argument, - @NotNull Function<@NotNull T, @NotNull V> factory) { + T argument, + Function factory) { throw new UnsupportedOperationException(); } @@ -136,7 +137,7 @@ default boolean containsKey(int key) { * * @return the array with all keys of this dictionary. */ - default @NotNull IntegerArray keyArray() { + default IntegerArray keyArray() { return keyArray(ArrayFactory.newMutableIntegerArray(size())); } @@ -146,7 +147,7 @@ default boolean containsKey(int key) { * @param container the container. * @return the container with all keys. */ - default @NotNull IntegerArray keyArray(@NotNull MutableIntegerArray container) { + default IntegerArray keyArray(MutableIntegerArray container) { throw new UnsupportedOperationException(); } @@ -157,7 +158,7 @@ default boolean containsKey(int key) { * @param value the value. * @return the previous value for the key or null. */ - default @Nullable V put(int key, @NotNull V value) { + default @Nullable V put(int key, V value) { throw new UnsupportedOperationException(); } @@ -176,7 +177,7 @@ default boolean containsKey(int key) { * * @param consumer the consumer. */ - default void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { + default void forEach(IntObjectConsumer consumer) { throw new UnsupportedOperationException(); } @@ -188,8 +189,8 @@ default void forEach(@NotNull IntObjectConsumer<@NotNull ? super V> consumer) { * @param the argument's type. */ default void forEach( - @NotNull T argument, - @NotNull IntBiObjectConsumer<@NotNull ? super V, @NotNull ? super T> consumer) { + T argument, + IntBiObjectConsumer consumer) { throw new UnsupportedOperationException(); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java index 46cd2dc7..e38d3541 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java @@ -2,8 +2,8 @@ import java.util.Iterator; import java.util.NoSuchElementException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The iterator to iterate {@link IntegerDictionary}. @@ -11,38 +11,35 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class IntegerDictionaryIterator implements Iterator { /** * The dictionary. */ - @NotNull private final UnsafeIntegerDictionary dictionary; /** * The next entry. */ - @Nullable - private IntegerEntry next; + private @Nullable IntegerEntry next; /** * The current entry. */ - @Nullable - private IntegerEntry current; + private @Nullable IntegerEntry current; /** * The current index. */ private int index; - public IntegerDictionaryIterator(@NotNull UnsafeIntegerDictionary dictionary) { + public IntegerDictionaryIterator(UnsafeIntegerDictionary dictionary) { this.dictionary = dictionary; - if (dictionary.size() > 0) { + if (!dictionary.isEmpty()) { IntegerEntry[] entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null) - ; + while (index < entries.length && (next = entries[index++]) == null); } } @@ -71,8 +68,7 @@ private IntegerEntry nextEntry() { } if ((next = entry.getNext()) == null) { - while (index < content.length && (next = content[index++]) == null) - ; + while (index < content.length && (next = content[index++]) == null); } current = entry; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java index 154d3b75..a2ca7a83 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java @@ -1,8 +1,8 @@ package javasabr.rlib.common.util.dictionary; import java.util.Objects; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The entry of {@link IntegerDictionary}. @@ -10,18 +10,17 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class IntegerEntry implements Entry, V> { /** * The next entry. */ - @Nullable - private IntegerEntry next; + private @Nullable IntegerEntry next; /** * The value of this entry. */ - @NotNull private V value; /** @@ -87,7 +86,7 @@ public void setNext(@Nullable IntegerEntry next) { } @Override - public @NotNull V getValue() { + public V getValue() { return value; } @@ -104,7 +103,7 @@ public final int hashCode() { * @param value the value. * @param next the next. */ - public void set(int hash, int key, @NotNull V value, @Nullable IntegerEntry next) { + public void set(int hash, int key, V value, @Nullable IntegerEntry next) { this.value = value; this.next = next; this.key = key; @@ -112,7 +111,7 @@ public void set(int hash, int key, @NotNull V value, @Nullable IntegerEntry n } @Override - public @NotNull V setValue(@NotNull V value) { + public V setValue(V value) { V old = getValue(); this.value = value; return old; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java index dbb3f847..0a55deae 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java @@ -8,8 +8,8 @@ import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.array.ArrayFactory; import javasabr.rlib.common.util.array.LongArray; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface to implement a dictionary which uses long as key. @@ -17,6 +17,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface LongDictionary extends Dictionary { /** @@ -25,7 +26,7 @@ public interface LongDictionary extends Dictionary { * @param the value's type. * @return the read-only empty dictionary. */ - static @NotNull LongDictionary empty() { + static LongDictionary empty() { return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_LD); } @@ -36,7 +37,7 @@ public interface LongDictionary extends Dictionary { * @param the value's type. * @return the new long dictionary. */ - static @NotNull LongDictionary ofType(@NotNull Class valueType) { + static LongDictionary ofType(Class valueType) { return DictionaryFactory.newLongDictionary(); } @@ -47,7 +48,7 @@ public interface LongDictionary extends Dictionary { * @param the value's type. * @return the new long dictionary. */ - static @NotNull LongDictionary of(@NotNull Object... values) { + static LongDictionary of(Object... values) { if (values.length < 2 || values.length % 2 != 0) { throw new IllegalArgumentException("Incorrect argument's count."); @@ -62,7 +63,7 @@ public interface LongDictionary extends Dictionary { return dictionary; } - static > @NotNull M append(@NotNull M first, @NotNull M second) { + static > M append(M first, M second) { second.copyTo(first); return first; } @@ -97,7 +98,7 @@ default boolean containsKey(long key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute(long key, @NotNull Supplier<@NotNull V> factory) { + default V getOrCompute(long key, Supplier factory) { throw new UnsupportedOperationException(); } @@ -109,7 +110,7 @@ default boolean containsKey(long key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute(long key, @NotNull LongFunction<@NotNull V> factory) { + default V getOrCompute(long key, LongFunction factory) { throw new UnsupportedOperationException(); } @@ -125,8 +126,8 @@ default boolean containsKey(long key) { */ default @Nullable V getOrCompute( long key, - @NotNull T argument, - @NotNull Function<@NotNull T, @NotNull V> factory) { + T argument, + Function factory) { throw new UnsupportedOperationException(); } @@ -135,7 +136,7 @@ default boolean containsKey(long key) { * * @return the array with all keys of this dictionary. */ - default @NotNull LongArray keyArray() { + default LongArray keyArray() { return keyArray(ArrayFactory.newLongArray(size())); } @@ -145,7 +146,7 @@ default boolean containsKey(long key) { * @param container the container. * @return the container with all keys. */ - default @NotNull LongArray keyArray(@NotNull LongArray container) { + default LongArray keyArray(LongArray container) { throw new UnsupportedOperationException(); } @@ -156,7 +157,7 @@ default boolean containsKey(long key) { * @param value the value. * @return the previous value for the key or null. */ - default @Nullable V put(long key, @NotNull V value) { + default @Nullable V put(long key, V value) { throw new UnsupportedOperationException(); } @@ -175,7 +176,7 @@ default boolean containsKey(long key) { * * @param consumer the consumer. */ - default void forEach(@NotNull LongObjectConsumer<@NotNull V> consumer) { + default void forEach(LongObjectConsumer consumer) { throw new UnsupportedOperationException(); } @@ -186,7 +187,7 @@ default void forEach(@NotNull LongObjectConsumer<@NotNull V> consumer) { * @param consumer the consumer. * @param the argument's type. */ - default void forEach(@NotNull T argument, @NotNull LongBiObjectConsumer<@NotNull V, @NotNull T> consumer) { + default void forEach(T argument, LongBiObjectConsumer consumer) { throw new UnsupportedOperationException(); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java index 929ed292..2e205753 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java @@ -2,8 +2,8 @@ import java.util.Iterator; import java.util.NoSuchElementException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The iterator to iterate {@link LongDictionary}. @@ -11,38 +11,35 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class LongDictionaryIterator implements Iterator { /** * The dictionary. */ - @NotNull private final UnsafeLongDictionary dictionary; /** * The next entry. */ - @Nullable - private LongEntry next; + private @Nullable LongEntry next; /** * The current entry. */ - @Nullable - private LongEntry current; + private @Nullable LongEntry current; /** * The current index. */ private int index; - public LongDictionaryIterator(@NotNull UnsafeLongDictionary dictionary) { + public LongDictionaryIterator(UnsafeLongDictionary dictionary) { this.dictionary = dictionary; - if (dictionary.size() > 0) { + if (!dictionary.isEmpty()) { LongEntry[] entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null) - ; + while (index < entries.length && (next = entries[index++]) == null); } } @@ -71,8 +68,7 @@ private LongEntry nextEntry() { } if ((next = entry.getNext()) == null) { - while (index < entries.length && (next = entries[index++]) == null) - ; + while (index < entries.length && (next = entries[index++]) == null); } current = entry; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java index dbbc2ff4..ded0198c 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java @@ -1,8 +1,8 @@ package javasabr.rlib.common.util.dictionary; import java.util.Objects; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The entry of {@link LongDictionary}. @@ -10,18 +10,17 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public final class LongEntry implements Entry, V> { /** * The next entry. */ - @Nullable - private LongEntry next; + private @Nullable LongEntry next; /** * The value of this entry. */ - @NotNull private V value; /** @@ -86,7 +85,7 @@ public void setNext(@Nullable LongEntry next) { } @Override - public @NotNull V getValue() { + public V getValue() { return value; } @@ -103,7 +102,7 @@ public final int hashCode() { * @param value the value. * @param next the next. */ - public void set(int hash, long key, @NotNull V value, @Nullable LongEntry next) { + public void set(int hash, long key, V value, @Nullable LongEntry next) { this.value = value; this.next = next; this.key = key; @@ -111,7 +110,7 @@ public void set(int hash, long key, @NotNull V value, @Nullable LongEntry nex } @Override - public @NotNull V setValue(@NotNull V value) { + public V setValue(V value) { V old = getValue(); this.value = value; return old; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java index 250ac14b..252e26cf 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java @@ -10,8 +10,8 @@ import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.array.Array; import javasabr.rlib.common.util.array.ArrayFactory; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface for implementing a key-value dictionary which using an object key. @@ -20,6 +20,7 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public interface ObjectDictionary extends Dictionary { /** @@ -29,7 +30,7 @@ public interface ObjectDictionary extends Dictionary { * @param the key's and value's type. * @return the new object dictionary. */ - static @NotNull ObjectDictionary ofType(@NotNull Class keyValueType) { + static ObjectDictionary ofType(Class keyValueType) { return DictionaryFactory.newObjectDictionary(); } @@ -42,9 +43,9 @@ public interface ObjectDictionary extends Dictionary { * @param the value's type. * @return the new object dictionary. */ - static @NotNull ObjectDictionary ofType( - @NotNull Class keyType, - @NotNull Class valueType) { + static ObjectDictionary ofType( + Class keyType, + Class valueType) { return DictionaryFactory.newObjectDictionary(); } @@ -56,7 +57,7 @@ public interface ObjectDictionary extends Dictionary { * @param the value's type. * @return the new object dictionary. */ - static @NotNull ObjectDictionary of(@NotNull Object... values) { + static ObjectDictionary of(Object... values) { return new ReadOnlyFastObjectDictionary<>(values); } @@ -67,11 +68,11 @@ public interface ObjectDictionary extends Dictionary { * @param the value's type. * @return the read-only empty dictionary. */ - static @NotNull ObjectDictionary empty() { + static ObjectDictionary empty() { return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_OD); } - static > @NotNull M append(@NotNull M first, @NotNull M second) { + static > M append(M first, M second) { second.copyTo(first); return first; } @@ -82,7 +83,7 @@ public interface ObjectDictionary extends Dictionary { * @param key key whose presence in this dictionary is to be tested. * @return true if this dictionary contains a mapping for the specified key. */ - default boolean containsKey(@NotNull K key) { + default boolean containsKey(K key) { throw new UnsupportedOperationException(); } @@ -94,7 +95,7 @@ default boolean containsKey(@NotNull K key) { * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for * the key. */ - default @Nullable V get(@NotNull K key) { + default @Nullable V get(K key) { throw new UnsupportedOperationException(); } @@ -107,7 +108,7 @@ default boolean containsKey(@NotNull K key) { * @return the value to which the specified key is mapped, or default if this dictionary contains no mapping for the * key. */ - default @Nullable V getOrDefault(@NotNull K key, @NotNull V def) { + default @Nullable V getOrDefault(K key, V def) { var value = get(key); return value == null ? def : value; } @@ -119,7 +120,7 @@ default boolean containsKey(@NotNull K key) { * @param key the key whose associated value is to be returned. * @return the optional value to which the specified key is mapped. */ - default @NotNull Optional getOptional(@NotNull K key) { + default Optional getOptional(K key) { return Optional.ofNullable(get(key)); } @@ -131,7 +132,7 @@ default boolean containsKey(@NotNull K key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullSupplier factory) { + default V getOrCompute(K key, NotNullSupplier factory) { throw new UnsupportedOperationException(); } @@ -143,7 +144,7 @@ default boolean containsKey(@NotNull K key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute(@NotNull K key, @NotNull NotNullFunction factory) { + default V getOrCompute(K key, NotNullFunction factory) { throw new UnsupportedOperationException(); } @@ -157,7 +158,7 @@ default boolean containsKey(@NotNull K key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute(@NotNull K key, @NotNull T argument, @NotNull NotNullFunction factory) { + default V getOrCompute(K key, T argument, NotNullFunction factory) { throw new UnsupportedOperationException(); } @@ -172,7 +173,7 @@ default boolean containsKey(@NotNull K key) { * @return the stored value by the key or the new value. * @see #getOrCompute(Object, Object, NotNullBiFunction) */ - default @NotNull V get(@NotNull K key, @NotNull T argument, @NotNull NotNullBiFunction factory) { + default V get(K key, T argument, NotNullBiFunction factory) { return getOrCompute(key, argument, factory); } @@ -186,10 +187,10 @@ default boolean containsKey(@NotNull K key) { * @param factory the factory. * @return the stored value by the key or the new value. */ - default @NotNull V getOrCompute( - @NotNull K key, - @NotNull T argument, - @NotNull NotNullBiFunction factory) { + default V getOrCompute( + K key, + T argument, + NotNullBiFunction factory) { throw new UnsupportedOperationException(); } @@ -199,7 +200,7 @@ default boolean containsKey(@NotNull K key) { * @param container the container. * @return the array with all keys. */ - default @NotNull Array keyArray(@NotNull Array container) { + default Array keyArray(Array container) { throw new UnsupportedOperationException(); } @@ -209,7 +210,7 @@ default boolean containsKey(@NotNull K key) { * @param type the key's type. * @return the array with all keys of this dictionary. */ - default @NotNull Array keyArray(@NotNull Class type) { + default Array keyArray(Class type) { return keyArray(ArrayFactory.newArray(type, size())); } @@ -220,7 +221,7 @@ default boolean containsKey(@NotNull K key) { * @param value the value. * @return the previous value for the key or null. */ - default @Nullable V put(@NotNull K key, @NotNull V value) { + default @Nullable V put(K key, V value) { throw new UnsupportedOperationException(); } @@ -231,7 +232,7 @@ default boolean containsKey(@NotNull K key) { * @param value the value. * @return the optional value of the previous value for the key. */ - default @NotNull Optional putOptional(@NotNull K key, @NotNull V value) { + default Optional putOptional(K key, V value) { return Optional.ofNullable(put(key, value)); } @@ -241,7 +242,7 @@ default boolean containsKey(@NotNull K key) { * @param key the key. * @return the previous value for the key or null. */ - default @Nullable V remove(@NotNull K key) { + default @Nullable V remove(K key) { throw new UnsupportedOperationException(); } @@ -251,7 +252,7 @@ default boolean containsKey(@NotNull K key) { * @param key the key. * @return the optional value of the previous value for the key. */ - default @NotNull Optional removeOptional(@NotNull K key) { + default Optional removeOptional(K key) { return Optional.ofNullable(remove(key)); } @@ -260,7 +261,7 @@ default boolean containsKey(@NotNull K key) { * * @param consumer the consumer. */ - default void forEach(@NotNull NotNullBiConsumer consumer) { + default void forEach(NotNullBiConsumer consumer) { throw new UnsupportedOperationException(); } @@ -272,8 +273,8 @@ default void forEach(@NotNull NotNullBiConsumer consumer) * @param the argument's type. */ default void forEach( - @NotNull T argument, - @NotNull NotNullTripleConsumer consumer) { + T argument, + NotNullTripleConsumer consumer) { throw new UnsupportedOperationException(); } @@ -287,9 +288,9 @@ default void forEach( * @param the second argument's type. */ default void forEach( - @NotNull F first, - @NotNull S second, - @NotNull FourObjectConsumer<@NotNull ? super F, @NotNull ? super S, @NotNull ? super K, @NotNull ? super V> consumer) { + F first, + S second, + FourObjectConsumer consumer) { throw new UnsupportedOperationException(); } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java index a4eea1c3..18c53805 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java @@ -2,8 +2,8 @@ import java.util.Iterator; import java.util.NoSuchElementException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The iterator to iterate {@link ObjectDictionary}. @@ -12,12 +12,13 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class ObjectDictionaryIterator implements Iterator { /** * The dictionary. */ - private final @NotNull UnsafeObjectDictionary dictionary; + private final UnsafeObjectDictionary dictionary; /** * The next entry. @@ -34,13 +35,12 @@ public class ObjectDictionaryIterator implements Iterator { */ private int index; - public ObjectDictionaryIterator(@NotNull UnsafeObjectDictionary dictionary) { + public ObjectDictionaryIterator(UnsafeObjectDictionary dictionary) { this.dictionary = dictionary; - if (dictionary.size() > 0) { + if (!dictionary.isEmpty()) { var entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null) - ; + while (index < entries.length && (next = entries[index++]) == null); } } @@ -50,7 +50,7 @@ public boolean hasNext() { } @Override - public @NotNull V next() { + public V next() { //noinspection ConstantConditions return nextEntry().getValue(); } @@ -60,7 +60,7 @@ public boolean hasNext() { * * @return the next entry. */ - private @NotNull ObjectEntry nextEntry() { + private ObjectEntry nextEntry() { var entries = dictionary.entries(); var entry = next; @@ -70,8 +70,7 @@ public boolean hasNext() { } if ((next = entry.getNext()) == null) { - while (index < entries.length && (next = entries[index++]) == null) - ; + while (index < entries.length && (next = entries[index++]) == null); } current = entry; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java index 29730f5b..29ea2948 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java @@ -3,8 +3,8 @@ import java.util.Objects; import lombok.Getter; import lombok.Setter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The entry of {@link ObjectDictionary}. @@ -13,31 +13,33 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked public class ObjectEntry implements Entry, V> { /** * The next entry. */ - private @Setter + @Setter @Getter - @Nullable ObjectEntry next; + private @Nullable ObjectEntry next; /** * The key of this entry. */ - private @Getter - @Nullable K key; + @Getter + private @Nullable K key; /** * The value of this entry. */ - private @Getter - @Nullable V value; + @Getter + private @Nullable V value; /** * The hash of the key. */ - private @Getter int hash; + @Getter + private int hash; @Override public boolean equals(@Nullable Object object) { @@ -81,7 +83,7 @@ public final int hashCode() { * @param value the value. * @param next the next entry. */ - public void set(int hash, @NotNull K key, @NotNull V value, @Nullable ObjectEntry next) { + public void set(int hash, K key, V value, @Nullable ObjectEntry next) { this.value = value; this.next = next; this.key = key; @@ -90,7 +92,7 @@ public void set(int hash, @NotNull K key, @NotNull V value, @Nullable ObjectEntr @Override @SuppressWarnings("ConstantConditions") - public @NotNull V setValue(@NotNull V value) { + public V setValue(V value) { var old = getValue(); this.value = value; return old; diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java index f2431fa6..544d49f3 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java @@ -1,8 +1,8 @@ package javasabr.rlib.common.util.dictionary; import lombok.NoArgsConstructor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The fast read-only implementation of {@link LongDictionary} without threadsafe supporting. @@ -10,11 +10,12 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked @NoArgsConstructor public class ReadOnlyFastLongDictionary extends FastLongDictionary { @Override - public void put(@NotNull Dictionary dictionary) { + public void put(Dictionary dictionary) { throw new IllegalStateException("Dictionary is only read."); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java index 21a2c8ab..23c41a8d 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java @@ -1,8 +1,8 @@ package javasabr.rlib.common.util.dictionary; import lombok.NoArgsConstructor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The fast read-only implementation of {@link ObjectDictionary} without threadsafe supporting. @@ -11,10 +11,11 @@ * @param the value's type. * @author JavaSaBr */ +@NullMarked @NoArgsConstructor public class ReadOnlyFastObjectDictionary extends FastObjectDictionary { - public ReadOnlyFastObjectDictionary(@NotNull Object... values) { + public ReadOnlyFastObjectDictionary(Object... values) { if (values.length < 2 || values.length % 2 != 0) { throw new IllegalArgumentException("Incorrect argument's count."); @@ -27,22 +28,22 @@ public ReadOnlyFastObjectDictionary(@NotNull Object... values) { } @Override - public void put(@NotNull Dictionary dictionary) { + public void put(Dictionary dictionary) { throw new IllegalStateException("Dictionary is readonly."); } @Override - public @Nullable V put(@NotNull K key, @Nullable V value) { + public @Nullable V put(K key, @Nullable V value) { throw new IllegalStateException("Dictionary is readonly."); } @Override - public @Nullable V remove(@NotNull K key) { + public @Nullable V remove(K key) { throw new IllegalStateException("Dictionary is readonly."); } @Override - public @Nullable ObjectEntry removeEntryForKey(@NotNull K key) { + public @Nullable ObjectEntry removeEntryForKey(K key) { throw new IllegalStateException("Dictionary is readonly."); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java index 7abfe189..786efeb6 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.dictionary; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface for implementing Unsafe part of {@link IntegerDictionary} API. @@ -9,6 +9,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface UnsafeIntegerDictionary extends IntegerDictionary { /** @@ -16,7 +17,7 @@ public interface UnsafeIntegerDictionary extends IntegerDictionary { * * @return the array of entries. */ - @NotNull IntegerEntry[] entries(); + IntegerEntry[] entries(); /** * Remove an entry for the key. @@ -24,5 +25,6 @@ public interface UnsafeIntegerDictionary extends IntegerDictionary { * @param key the key of the entry. * @return removed entry. */ - @Nullable IntegerEntry removeEntryForKey(final int key); + @Nullable + IntegerEntry removeEntryForKey(final int key); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java index 1b16b135..f9700e70 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.dictionary; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface for implementing Unsafe part of {@link LongDictionary} API. @@ -9,6 +9,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface UnsafeLongDictionary extends LongDictionary { /** @@ -16,7 +17,7 @@ public interface UnsafeLongDictionary extends LongDictionary { * * @return the array of entries. */ - @NotNull LongEntry[] entries(); + LongEntry[] entries(); /** * Remove an entry for the key. @@ -24,5 +25,6 @@ public interface UnsafeLongDictionary extends LongDictionary { * @param key the key of the entry. * @return removed entry. */ - @Nullable LongEntry removeEntryForKey(long key); + @Nullable + LongEntry removeEntryForKey(long key); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java index 72dff7dc..d3661237 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.common.util.dictionary; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The interface for implementing Unsafe part of {@link ObjectDictionary} API. @@ -10,6 +10,7 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public interface UnsafeObjectDictionary extends ObjectDictionary { /** @@ -17,7 +18,7 @@ public interface UnsafeObjectDictionary extends ObjectDictionary { * * @return the array of entries. */ - @NotNull ObjectEntry[] entries(); + ObjectEntry[] entries(); /** * Remove an entry for the key. @@ -25,5 +26,5 @@ public interface UnsafeObjectDictionary extends ObjectDictionary { * @param key the key of the entry. * @return removed entry. */ - @Nullable ObjectEntry removeEntryForKey(@NotNull K key); + @Nullable ObjectEntry removeEntryForKey(K key); } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java index e84b4fa2..1564d7a0 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/Node.java @@ -1,8 +1,8 @@ package javasabr.rlib.common.util.linkedlist.impl; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * The node of the LinkedList. @@ -10,24 +10,23 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public final class Node implements Reusable { /** * The item. */ - private E item; + private @Nullable E item; /** * The prev node. */ - @Nullable - private Node prev; + private @Nullable Node prev; /** * The next node. */ - @Nullable - private Node next; + private @Nullable Node next; @Override public void free() { @@ -41,8 +40,7 @@ public void free() { * * @return yhe item. */ - @NotNull - public E getItem() { + public @Nullable E getItem() { return item; } @@ -51,7 +49,7 @@ public E getItem() { * * @param item yhe item. */ - public void setItem(@Nullable final E item) { + public void setItem(@Nullable E item) { this.item = item; } @@ -60,8 +58,7 @@ public void setItem(@Nullable final E item) { * * @return yhe next node. */ - @Nullable - public Node getNext() { + public @Nullable Node getNext() { return next; } @@ -70,7 +67,7 @@ public Node getNext() { * * @param next yhe next node. */ - public void setNext(@Nullable final Node next) { + public void setNext(@Nullable Node next) { this.next = next; } @@ -79,8 +76,7 @@ public void setNext(@Nullable final Node next) { * * @return yhe prev node. */ - @Nullable - public Node getPrev() { + public @Nullable Node getPrev() { return prev; } @@ -89,7 +85,7 @@ public Node getPrev() { * * @param prev yhe prev node. */ - public void setPrev(@Nullable final Node prev) { + public void setPrev(@Nullable Node prev) { this.prev = prev; } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java index ce7c5a5b..f4bb0a07 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/linkedlist/impl/SortedLinkedList.java @@ -1,7 +1,8 @@ package javasabr.rlib.common.util.linkedlist.impl; -import java.util.Objects; -import org.jetbrains.annotations.NotNull; +import java.io.Serial; +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.NullMarked; /** * The implementation of {@link FastLinkedList} with to sort on put an element. @@ -9,8 +10,10 @@ * @param the type parameter * @author JavaSaBr */ +@NullMarked public class SortedLinkedList> extends FastLinkedList { + @Serial private static final long serialVersionUID = -8115760928469233254L; /** @@ -18,19 +21,16 @@ public class SortedLinkedList> extends FastLinkedList * * @param type the type */ - public SortedLinkedList(final Class type) { + public SortedLinkedList(Class type) { super(type); } @Override - public boolean add(@NotNull final E element) { - Objects.requireNonNull(element); + public boolean add(@NonNull E element) { for (Node node = getFirstNode(); node != null; node = node.getNext()) { - - final E item = node.getItem(); - - if (element.compareTo(item) < 0) { + E item = node.getItem(); + if (item != null && element.compareTo(item) < 0) { insertBefore(node, element); return true; } From cc44b3c139dfb5963aef3a1543f615dbdd73e0ad Mon Sep 17 00:00:00 2001 From: javasabr Date: Fri, 8 Aug 2025 20:54:45 +0200 Subject: [PATCH 3/8] continue global refactoring --- .../java/javasabr/rlib/logger/api/Logger.java | 111 +++++++++--------- .../rlib/logger/api/LoggerFactory.java | 15 ++- .../javasabr/rlib/logger/api/LoggerLevel.java | 4 +- .../rlib/logger/api/LoggerListener.java | 4 +- .../rlib/logger/api/LoggerManager.java | 19 ++- .../rlib/logger/api/impl/NullLogger.java | 11 +- .../logger/api/impl/NullLoggerFactory.java | 21 ++-- .../rlib/logger/api/package-info.java | 4 + .../rlib/logger/impl/DefaultLogger.java | 13 +- .../logger/impl/DefaultLoggerFactory.java | 33 +++--- .../rlib/logger/impl/FolderFileListener.java | 8 +- .../rlib/logger/impl/package-info.java | 4 + .../rlib/logger/slf4j/Slf4jLogger.java | 7 +- .../rlib/logger/slf4j/Slf4jLoggerFactory.java | 15 ++- .../rlib/logger/slf4j/package-info.java | 4 + 15 files changed, 133 insertions(+), 140 deletions(-) create mode 100644 rlib-logger-api/src/main/java/javasabr/rlib/logger/api/package-info.java create mode 100644 rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/package-info.java create mode 100644 rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/package-info.java diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java index 070ec2a6..8de421e5 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/Logger.java @@ -1,7 +1,6 @@ package javasabr.rlib.logger.api; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The interface to implement a logger. @@ -13,49 +12,49 @@ public interface Logger { @FunctionalInterface interface Factory { - @NotNull String make(); + String make(); } @FunctionalInterface interface SinFactory { - @NotNull String make(@NotNull F first); + String make(F first); } @FunctionalInterface interface IntSinFactory { - @NotNull String make(int val); + String make(int val); } @FunctionalInterface interface BiFactory { - @NotNull String make(@NotNull F first, @NotNull S second); + String make(F first, S second); } @FunctionalInterface interface NullableBiFactory { - @NotNull String make(@Nullable F first, @Nullable S second); + String make(@Nullable F first, @Nullable S second); } @FunctionalInterface interface ObjIntFactory { - @NotNull String make(@NotNull F first, int second); + String make(F first, int second); } @FunctionalInterface interface IntBiFactory { - @NotNull String make(int first, int second); + String make(int first, int second); } @FunctionalInterface interface TriFactory { - @NotNull String make(@NotNull F first, @NotNull S second, @NotNull T third); + String make(F first, S second, T third); } /** @@ -63,7 +62,7 @@ interface TriFactory { * * @param message the message. */ - default void debug(@NotNull String message) { + default void debug(String message) { print(LoggerLevel.DEBUG, message); } @@ -73,7 +72,7 @@ default void debug(@NotNull String message) { * @param arg the arg for the message factory. * @param messageFactory the message factory. */ - default void debug(int arg, @NotNull Logger.IntSinFactory messageFactory) { + default void debug(int arg, Logger.IntSinFactory messageFactory) { print(LoggerLevel.DEBUG, arg, messageFactory); } @@ -84,7 +83,7 @@ default void debug(int arg, @NotNull Logger.IntSinFactory messageFactory) { * @param messageFactory the message factory. * @param the argument's type. */ - default void debug(@NotNull T arg, @NotNull Logger.SinFactory messageFactory) { + default void debug(T arg, Logger.SinFactory messageFactory) { print(LoggerLevel.DEBUG, arg, messageFactory); } @@ -97,7 +96,7 @@ default void debug(@NotNull T arg, @NotNull Logger.SinFactory messageFact * @param the first argument's type. * @param the second argument's type. */ - default void debug(@NotNull F first, @NotNull S second, @NotNull Logger.BiFactory messageFactory) { + default void debug(F first, S second, Logger.BiFactory messageFactory) { print(LoggerLevel.DEBUG, first, second, messageFactory); } @@ -113,7 +112,7 @@ default void debug(@NotNull F first, @NotNull S second, @NotNull Logger.B default void debugNullable( @Nullable F first, @Nullable S second, - @NotNull Logger.NullableBiFactory messageFactory) { + Logger.NullableBiFactory messageFactory) { print(LoggerLevel.DEBUG, first, second, messageFactory); } @@ -125,7 +124,7 @@ default void debugNullable( * @param messageFactory the message factory. * @param the first argument's type. */ - default void debug(@NotNull F first, int second, @NotNull Logger.ObjIntFactory messageFactory) { + default void debug(F first, int second, Logger.ObjIntFactory messageFactory) { print(LoggerLevel.DEBUG, first, second, messageFactory); } @@ -136,7 +135,7 @@ default void debug(@NotNull F first, int second, @NotNull Logger.ObjIntFacto * @param second the second arg for the message factory. * @param messageFactory the message factory. */ - default void debug(int first, int second, @NotNull Logger.IntBiFactory messageFactory) { + default void debug(int first, int second, Logger.IntBiFactory messageFactory) { print(LoggerLevel.DEBUG, first, second, messageFactory); } @@ -152,10 +151,10 @@ default void debug(int first, int second, @NotNull Logger.IntBiFactory messageFa * @param the third argument's type. */ default void debug( - @NotNull F first, - @NotNull S second, - @NotNull T third, - @NotNull Logger.TriFactory messageFactory) { + F first, + S second, + T third, + Logger.TriFactory messageFactory) { print(LoggerLevel.DEBUG, first, second, third, messageFactory); } @@ -164,7 +163,7 @@ default void debug( * * @param message the message. */ - default void error(@NotNull String message) { + default void error(String message) { print(LoggerLevel.ERROR, message); } @@ -173,7 +172,7 @@ default void error(@NotNull String message) { * * @param exception the exception. */ - default void error(@NotNull Throwable exception) { + default void error(Throwable exception) { print(LoggerLevel.ERROR, exception); } @@ -182,7 +181,7 @@ default void error(@NotNull Throwable exception) { * * @param message the message. */ - default void info(@NotNull String message) { + default void info(String message) { print(LoggerLevel.INFO, message); } @@ -193,7 +192,7 @@ default void info(@NotNull String message) { * @param messageFactory the message factory. * @param the argument's type. */ - default void info(@NotNull T arg, @NotNull Logger.SinFactory messageFactory) { + default void info(T arg, Logger.SinFactory messageFactory) { print(LoggerLevel.INFO, arg, messageFactory); } @@ -206,7 +205,7 @@ default void info(@NotNull T arg, @NotNull Logger.SinFactory messageFacto * @param the first argument's type. * @param the second argument's type. */ - default void info(@NotNull F first, @NotNull S second, @NotNull Logger.BiFactory messageFactory) { + default void info(F first, S second, Logger.BiFactory messageFactory) { print(LoggerLevel.INFO, first, second, messageFactory); } @@ -222,10 +221,10 @@ default void info(@NotNull F first, @NotNull S second, @NotNull Logger.Bi * @param the third argument's type. */ default void info( - @NotNull F first, - @NotNull S second, - @NotNull T third, - @NotNull Logger.TriFactory messageFactory) { + F first, + S second, + T third, + Logger.TriFactory messageFactory) { print(LoggerLevel.INFO, first, second, third, messageFactory); } @@ -235,7 +234,7 @@ default void info( * @param level the logger level. * @return true if the level is enabled. */ - default boolean isEnabled(@NotNull LoggerLevel level) { + default boolean isEnabled(LoggerLevel level) { return level.isEnabled(); } @@ -246,7 +245,7 @@ default boolean isEnabled(@NotNull LoggerLevel level) { * @param enabled true if need to be enabled. * @return true if the status was changed. */ - default boolean setEnabled(@NotNull LoggerLevel level, boolean enabled) { + default boolean setEnabled(LoggerLevel level, boolean enabled) { return false; } @@ -256,7 +255,7 @@ default boolean setEnabled(@NotNull LoggerLevel level, boolean enabled) { * @param level the logger level. * @return true if the status was changed. */ - default boolean applyDefault(@NotNull LoggerLevel level) { + default boolean applyDefault(LoggerLevel level) { return false; } @@ -265,7 +264,7 @@ default boolean applyDefault(@NotNull LoggerLevel level) { * * @param message the message. */ - default void warning(@NotNull String message) { + default void warning(String message) { print(LoggerLevel.WARNING, message); } @@ -274,7 +273,7 @@ default void warning(@NotNull String message) { * * @param exception the exception. */ - default void warning(@NotNull Throwable exception) { + default void warning(Throwable exception) { print(LoggerLevel.WARNING, exception); } @@ -285,7 +284,7 @@ default void warning(@NotNull Throwable exception) { * @param messageFactory the message factory. * @param the argument's type. */ - default void warning(@NotNull A arg, @NotNull Logger.SinFactory messageFactory) { + default void warning(A arg, Logger.SinFactory messageFactory) { print(LoggerLevel.WARNING, arg, messageFactory); } @@ -298,7 +297,7 @@ default void warning(@NotNull A arg, @NotNull Logger.SinFactory messageFa * @param the first argument's type. * @param the second argument's type. */ - default void warning(@NotNull F first, @NotNull S second, @NotNull Logger.BiFactory messageFactory) { + default void warning(F first, S second, Logger.BiFactory messageFactory) { print(LoggerLevel.WARNING, first, second, messageFactory); } @@ -308,7 +307,7 @@ default void warning(@NotNull F first, @NotNull S second, @NotNull Logger * @param level the level of the message. * @param message the message. */ - void print(@NotNull LoggerLevel level, @NotNull String message); + void print(LoggerLevel level, String message); /** * Print the message. @@ -316,7 +315,7 @@ default void warning(@NotNull F first, @NotNull S second, @NotNull Logger * @param level the level of the message. * @param exception the exception. */ - void print(@NotNull LoggerLevel level, @NotNull Throwable exception); + void print(LoggerLevel level, Throwable exception); /** * Print a build message. @@ -326,7 +325,7 @@ default void warning(@NotNull F first, @NotNull S second, @NotNull Logger * @param messageFactory the message factory. * @param the argument's type. */ - default void print(@NotNull LoggerLevel level, @NotNull T arg, @NotNull Logger.SinFactory messageFactory) { + default void print(LoggerLevel level, T arg, Logger.SinFactory messageFactory) { if (isEnabled(level)) { print(level, messageFactory.make(arg)); } @@ -339,7 +338,7 @@ default void print(@NotNull LoggerLevel level, @NotNull T arg, @NotNull Logg * @param arg the arg for the message factory. * @param messageFactory the message factory. */ - default void print(@NotNull LoggerLevel level, int arg, @NotNull Logger.IntSinFactory messageFactory) { + default void print(LoggerLevel level, int arg, Logger.IntSinFactory messageFactory) { if (isEnabled(level)) { print(level, messageFactory.make(arg)); } @@ -356,10 +355,10 @@ default void print(@NotNull LoggerLevel level, int arg, @NotNull Logger.IntSinFa * @param the second argument's type. */ default void print( - @NotNull LoggerLevel level, - @NotNull F first, - @NotNull S second, - @NotNull Logger.BiFactory messageFactory) { + LoggerLevel level, + F first, + S second, + Logger.BiFactory messageFactory) { if (isEnabled(level)) { print(level, messageFactory.make(first, second)); } @@ -376,10 +375,10 @@ default void print( * @param the second argument's type. */ default void print( - @NotNull LoggerLevel level, + LoggerLevel level, @Nullable F first, @Nullable S second, - @NotNull Logger.NullableBiFactory messageFactory) { + Logger.NullableBiFactory messageFactory) { if (isEnabled(level)) { print(level, messageFactory.make(first, second)); } @@ -395,10 +394,10 @@ default void print( * @param the first argument's type. */ default void print( - @NotNull LoggerLevel level, - @NotNull F first, + LoggerLevel level, + F first, int second, - @NotNull Logger.ObjIntFactory messageFactory) { + Logger.ObjIntFactory messageFactory) { if (isEnabled(level)) { print(level, messageFactory.make(first, second)); } @@ -412,7 +411,7 @@ default void print( * @param second the second arg for the message factory. * @param messageFactory the message factory. */ - default void print(@NotNull LoggerLevel level, int first, int second, @NotNull Logger.IntBiFactory messageFactory) { + default void print(LoggerLevel level, int first, int second, Logger.IntBiFactory messageFactory) { if (isEnabled(level)) { print(level, messageFactory.make(first, second)); } @@ -431,11 +430,11 @@ default void print(@NotNull LoggerLevel level, int first, int second, @NotNull L * @param the third argument's type. */ default void print( - @NotNull LoggerLevel level, - @NotNull F first, - @NotNull S second, - @NotNull T third, - @NotNull Logger.TriFactory messageFactory) { + LoggerLevel level, + F first, + S second, + T third, + Logger.TriFactory messageFactory) { if (isEnabled(level)) { print(level, messageFactory.make(first, second, third)); diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java index 8e357ac8..eaac2001 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerFactory.java @@ -1,7 +1,6 @@ package javasabr.rlib.logger.api; import java.io.Writer; -import org.jetbrains.annotations.NotNull; public interface LoggerFactory { @@ -11,7 +10,7 @@ public interface LoggerFactory { * @param name the logger's name. * @return the new logger. */ - @NotNull Logger make(@NotNull String name); + Logger make(String name); /** * Make a new logger for the type. @@ -19,40 +18,40 @@ public interface LoggerFactory { * @param type the logger's type. * @return the new logger. */ - @NotNull Logger make(@NotNull Class type); + Logger make(Class type); /** * Get a default logger. * * @return he default logger. */ - @NotNull Logger getDefault(); + Logger getDefault(); /** * Add the new listener. * * @param listener the new listener. */ - void addListener(@NotNull LoggerListener listener); + void addListener(LoggerListener listener); /** * Add the new writer. * * @param writer the new writer. */ - void addWriter(@NotNull Writer writer); + void addWriter(Writer writer); /** * Remove the listener. * * @param listener the listener. */ - void removeListener(@NotNull LoggerListener listener); + void removeListener(LoggerListener listener); /** * Remove the writer. * * @param writer the writer. */ - void removeWriter(@NotNull Writer writer); + void removeWriter(Writer writer); } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java index 47fbb84e..03c55cb6 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerLevel.java @@ -2,7 +2,6 @@ import lombok.Getter; import lombok.Setter; -import org.jetbrains.annotations.NotNull; /** * The list of logging levels. @@ -34,7 +33,6 @@ public enum LoggerLevel { * The level title. */ @Setter - @NotNull private String title; /** @@ -48,7 +46,7 @@ public enum LoggerLevel { */ private boolean forceFlush; - LoggerLevel(@NotNull String title, boolean forceFlush, boolean enabled) { + LoggerLevel(String title, boolean forceFlush, boolean enabled) { this.title = title; this.forceFlush = forceFlush; this.enabled = enabled; diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java index 576eacf6..26c5ebbd 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerListener.java @@ -1,7 +1,5 @@ package javasabr.rlib.logger.api; -import org.jetbrains.annotations.NotNull; - /** * The interface to implement a listener of logger events. * @@ -14,7 +12,7 @@ public interface LoggerListener { * * @param text the text. */ - void println(@NotNull String text); + void println(String text); /** * Flush last data. diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java index d4371f79..293275eb 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/LoggerManager.java @@ -4,7 +4,6 @@ import java.lang.reflect.InvocationTargetException; import java.util.ServiceLoader; import javasabr.rlib.logger.api.impl.NullLoggerFactory; -import org.jetbrains.annotations.NotNull; /** * The class to manage loggers. @@ -61,7 +60,7 @@ public class LoggerManager { * * @param listener the new listener. */ - public static void addListener(@NotNull LoggerListener listener) { + public static void addListener(LoggerListener listener) { LOGGER_FACTORY.addListener(listener); } @@ -70,7 +69,7 @@ public static void addListener(@NotNull LoggerListener listener) { * * @param writer the new writer. */ - public static void addWriter(@NotNull Writer writer) { + public static void addWriter(Writer writer) { LOGGER_FACTORY.addWriter(writer); } @@ -79,7 +78,7 @@ public static void addWriter(@NotNull Writer writer) { * * @return the main logger. */ - public static @NotNull Logger getDefaultLogger() { + public static Logger getDefaultLogger() { return LOGGER_FACTORY.getDefault(); } @@ -89,7 +88,7 @@ public static void addWriter(@NotNull Writer writer) { * @param cs the class. * @return the logger for the class. */ - public static @NotNull Logger getLogger(@NotNull Class cs) { + public static Logger getLogger(Class cs) { return LOGGER_FACTORY.make(cs); } @@ -99,7 +98,7 @@ public static void addWriter(@NotNull Writer writer) { * @param id the id. * @return the logger for the class. */ - public static @NotNull Logger getLogger(@NotNull String id) { + public static Logger getLogger(String id) { return LOGGER_FACTORY.make(id); } @@ -108,7 +107,7 @@ public static void addWriter(@NotNull Writer writer) { * * @param listener the listener. */ - public static void removeListener(@NotNull LoggerListener listener) { + public static void removeListener(LoggerListener listener) { LOGGER_FACTORY.removeListener(listener); } @@ -117,7 +116,7 @@ public static void removeListener(@NotNull LoggerListener listener) { * * @param writer the writer. */ - public static void removeWriter(@NotNull Writer writer) { + public static void removeWriter(Writer writer) { LOGGER_FACTORY.removeWriter(writer); } @@ -127,7 +126,7 @@ public static void removeWriter(@NotNull Writer writer) { * @param cs the class which use its own logger. * @param level the logger level to enable. */ - public static void enable(@NotNull Class cs, @NotNull LoggerLevel level) { + public static void enable(Class cs, LoggerLevel level) { getLogger(cs).setEnabled(level, true); } @@ -137,7 +136,7 @@ public static void enable(@NotNull Class cs, @NotNull LoggerLevel level) { * @param cs the class which use its own logger. * @param level the logger level to disable. */ - public static void disable(@NotNull Class cs, @NotNull LoggerLevel level) { + public static void disable(Class cs, LoggerLevel level) { getLogger(cs).setEnabled(level, false); } } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java index 504eac73..01361fcf 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLogger.java @@ -2,17 +2,14 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerLevel; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; +@NullMarked public final class NullLogger implements Logger { @Override - public void print(@NotNull LoggerLevel level, @NotNull String message) { - - } + public void print(LoggerLevel level, String message) {} @Override - public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { - - } + public void print(LoggerLevel level, Throwable exception) {} } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java index b3e8cd64..be313870 100644 --- a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/impl/NullLoggerFactory.java @@ -4,40 +4,37 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerFactory; import javasabr.rlib.logger.api.LoggerListener; -import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NullMarked; +@NullMarked public class NullLoggerFactory implements LoggerFactory { private static final NullLogger NULL_LOGGER = new NullLogger(); @Override - public @NotNull Logger make(@NotNull String name) { + public Logger make(String name) { return NULL_LOGGER; } @Override - public @NotNull Logger make(@NotNull Class type) { + public Logger make(Class type) { return NULL_LOGGER; } @Override - public @NotNull Logger getDefault() { + public Logger getDefault() { return NULL_LOGGER; } @Override - public void addListener(@NotNull LoggerListener listener) { - } + public void addListener(LoggerListener listener) {} @Override - public void addWriter(@NotNull Writer writer) { - } + public void addWriter(Writer writer) {} @Override - public void removeListener(@NotNull LoggerListener listener) { - } + public void removeListener(LoggerListener listener) {} @Override - public void removeWriter(@NotNull Writer writer) { - } + public void removeWriter(Writer writer) {} } diff --git a/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/package-info.java b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/package-info.java new file mode 100644 index 00000000..fbca5b12 --- /dev/null +++ b/rlib-logger-api/src/main/java/javasabr/rlib/logger/api/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.logger.api; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java index a17be515..f79b8d7d 100644 --- a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java +++ b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLogger.java @@ -4,7 +4,6 @@ import javasabr.rlib.common.util.StringUtils; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerLevel; -import org.jetbrains.annotations.NotNull; /** * The base implementation of the logger. @@ -30,39 +29,39 @@ public final class DefaultLogger implements Logger { */ private final DefaultLoggerFactory loggerFactory; - public DefaultLogger(@NotNull String name, @NotNull DefaultLoggerFactory loggerFactory) { + public DefaultLogger(String name, DefaultLoggerFactory loggerFactory) { this.name = name; this.loggerFactory = loggerFactory; this.override = new Boolean[VALUES.length]; } @Override - public boolean isEnabled(@NotNull LoggerLevel level) { + public boolean isEnabled(LoggerLevel level) { var value = override[level.ordinal()]; return Objects.requireNonNullElse(value, level.isEnabled()); } @Override - public boolean setEnabled(@NotNull LoggerLevel level, boolean enabled) { + public boolean setEnabled(LoggerLevel level, boolean enabled) { override[level.ordinal()] = enabled; return true; } @Override - public boolean applyDefault(@NotNull LoggerLevel level) { + public boolean applyDefault(LoggerLevel level) { override[level.ordinal()] = null; return true; } @Override - public void print(@NotNull LoggerLevel level, @NotNull String message) { + public void print(LoggerLevel level, String message) { if (isEnabled(level)) { loggerFactory.write(level, name, message); } } @Override - public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { + public void print(LoggerLevel level, Throwable exception) { if (isEnabled(level)) { loggerFactory.write(level, name, StringUtils.toString(exception)); } diff --git a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java index e693d2a6..807249b8 100644 --- a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java +++ b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/DefaultLoggerFactory.java @@ -14,7 +14,6 @@ import javasabr.rlib.logger.api.LoggerFactory; import javasabr.rlib.logger.api.LoggerLevel; import javasabr.rlib.logger.api.LoggerListener; -import org.jetbrains.annotations.NotNull; /** * The class for managing loggers. @@ -26,27 +25,27 @@ public class DefaultLoggerFactory implements LoggerFactory { /** * The dictionary of all created loggers. */ - private final @NotNull ConcurrentMap loggers; + private final ConcurrentMap loggers; /** * The main logger. */ - private final @NotNull Logger logger; + private final Logger logger; /** * The list of listeners. */ - private final @NotNull ConcurrentArray listeners; + private final ConcurrentArray listeners; /** * The list of writers. */ - private final @NotNull ConcurrentArray writers; + private final ConcurrentArray writers; /** * The date time formatter. */ - private final @NotNull DateTimeFormatter timeFormatter; + private final DateTimeFormatter timeFormatter; public DefaultLoggerFactory() { this.loggers = new ConcurrentHashMap<>(); @@ -57,37 +56,37 @@ public DefaultLoggerFactory() { } @Override - public void addListener(@NotNull LoggerListener listener) { + public void addListener(LoggerListener listener) { listeners.runInWriteLock(listener, Array::add); } @Override - public void addWriter(@NotNull Writer writer) { + public void addWriter(Writer writer) { writers.runInWriteLock(writer, Array::add); } @Override - public @NotNull Logger getDefault() { + public Logger getDefault() { return logger; } @Override - public @NotNull Logger make(@NotNull Class type) { + public Logger make(Class type) { return notNull(loggers.computeIfAbsent(type.getSimpleName(), name -> new DefaultLogger(name, this))); } @Override - public @NotNull Logger make(@NotNull String name) { + public Logger make(String name) { return notNull(loggers.computeIfAbsent(name, str -> new DefaultLogger(str, this))); } @Override - public void removeListener(@NotNull LoggerListener listener) { + public void removeListener(LoggerListener listener) { listeners.runInWriteLock(listener, Array::remove); } @Override - public void removeWriter(@NotNull Writer writer) { + public void removeWriter(Writer writer) { writers.runInWriteLock(writer, Array::remove); } @@ -98,7 +97,7 @@ public void removeWriter(@NotNull Writer writer) { * @param name the name of owner. * @param message the message. */ - void write(@NotNull LoggerLevel level, @NotNull String name, @NotNull String message) { + void write(LoggerLevel level, String name, String message) { var timeStump = timeFormatter.format(LocalTime.now()); var result = level.getTitle() + ' ' + timeStump + ' ' + name + ": " + message; @@ -112,7 +111,7 @@ void write(@NotNull LoggerLevel level, @NotNull String name, @NotNull String mes * @param level the level of the result message. * @param resultMessage the result message. */ - private void write(@NotNull LoggerLevel level, @NotNull String resultMessage) { + private void write(LoggerLevel level, String resultMessage) { listeners.forEachInReadLockR(resultMessage, LoggerListener::println); writers.forEachInReadLockR(resultMessage, DefaultLoggerFactory::append); @@ -127,7 +126,7 @@ private void write(@NotNull LoggerLevel level, @NotNull String resultMessage) { writers.forEachInReadLock(DefaultLoggerFactory::flush); } - private static void append(@NotNull Writer writer, @NotNull String toWrite) { + private static void append(Writer writer, String toWrite) { try { writer.append(toWrite); writer.append('\n'); @@ -136,7 +135,7 @@ private static void append(@NotNull Writer writer, @NotNull String toWrite) { } } - private static void flush(@NotNull Writer writer) { + private static void flush(Writer writer) { try { writer.flush(); } catch (IOException e) { diff --git a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java index 626290dd..3a67f67d 100644 --- a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java +++ b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/FolderFileListener.java @@ -9,7 +9,6 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import javasabr.rlib.logger.api.LoggerListener; -import org.jetbrains.annotations.NotNull; /** * The implementation of a logger listener to save log to files in a directory. @@ -23,7 +22,6 @@ public class FolderFileListener implements LoggerListener { /** * The folder with log files. */ - @NotNull private final Path folder; /** @@ -31,7 +29,7 @@ public class FolderFileListener implements LoggerListener { */ private Writer writer; - public FolderFileListener(@NotNull Path folder) { + public FolderFileListener(Path folder) { if (!Files.isDirectory(folder)) { throw new IllegalArgumentException("file is not directory."); @@ -55,7 +53,7 @@ public FolderFileListener(@NotNull Path folder) { * @return the writer. * @throws IOException the io exception */ - public @NotNull Writer getWriter() throws IOException { + public Writer getWriter() throws IOException { if (writer == null) { @@ -69,7 +67,7 @@ public FolderFileListener(@NotNull Path folder) { } @Override - public void println(@NotNull String text) { + public void println(String text) { try { var writer = getWriter(); writer.append(text); diff --git a/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/package-info.java b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/package-info.java new file mode 100644 index 00000000..636b3430 --- /dev/null +++ b/rlib-logger-impl/src/main/java/javasabr/rlib/logger/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.logger.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java index 79239bba..d9a0b05e 100644 --- a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java +++ b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLogger.java @@ -3,7 +3,6 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerLevel; import lombok.RequiredArgsConstructor; -import org.jetbrains.annotations.NotNull; @RequiredArgsConstructor public class Slf4jLogger implements Logger { @@ -11,7 +10,7 @@ public class Slf4jLogger implements Logger { private final org.slf4j.Logger logger; @Override - public boolean isEnabled(@NotNull LoggerLevel level) { + public boolean isEnabled(LoggerLevel level) { switch (level) { case INFO: @@ -28,7 +27,7 @@ public boolean isEnabled(@NotNull LoggerLevel level) { } @Override - public void print(@NotNull LoggerLevel level, @NotNull String message) { + public void print(LoggerLevel level, String message) { switch (level) { case INFO: @@ -46,7 +45,7 @@ public void print(@NotNull LoggerLevel level, @NotNull String message) { } @Override - public void print(@NotNull LoggerLevel level, @NotNull Throwable exception) { + public void print(LoggerLevel level, Throwable exception) { switch (level) { case INFO: diff --git a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java index 68e35384..97a49704 100644 --- a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java +++ b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/Slf4jLoggerFactory.java @@ -4,7 +4,6 @@ import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerFactory; import javasabr.rlib.logger.api.LoggerListener; -import org.jetbrains.annotations.NotNull; public class Slf4jLoggerFactory implements LoggerFactory { @@ -15,37 +14,37 @@ public Slf4jLoggerFactory() { } @Override - public @NotNull Logger make(@NotNull String name) { + public Logger make(String name) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(name)); } @Override - public @NotNull Logger make(@NotNull Class type) { + public Logger make(Class type) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(type)); } @Override - public @NotNull Logger getDefault() { + public Logger getDefault() { return logger; } @Override - public void addListener(@NotNull LoggerListener listener) { + public void addListener(LoggerListener listener) { throw new UnsupportedOperationException(); } @Override - public void addWriter(@NotNull Writer writer) { + public void addWriter(Writer writer) { throw new UnsupportedOperationException(); } @Override - public void removeListener(@NotNull LoggerListener listener) { + public void removeListener(LoggerListener listener) { throw new UnsupportedOperationException(); } @Override - public void removeWriter(@NotNull Writer writer) { + public void removeWriter(Writer writer) { throw new UnsupportedOperationException(); } } diff --git a/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/package-info.java b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/package-info.java new file mode 100644 index 00000000..c78f3f07 --- /dev/null +++ b/rlib-logger-slf4j/src/main/java/javasabr/rlib/logger/slf4j/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.logger.slf4j; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file From 8f7ed0067eeecd91183e3a6b871aa51367d75775 Mon Sep 17 00:00:00 2001 From: javasabr Date: Fri, 8 Aug 2025 21:03:52 +0200 Subject: [PATCH 4/8] continue global refactoring --- .../javasabr/rlib/mail/sender/MailSender.java | 5 +- .../UncheckedMessagingException.java | 3 +- .../mail/sender/exception/package-info.java | 4 + .../mail/sender/impl/JavaxMailSender.java | 17 ++-- .../rlib/mail/sender/impl/package-info.java | 4 + .../rlib/mail/sender/package-info.java | 4 + .../rlib/network/BufferAllocator.java | 17 ++-- .../javasabr/rlib/network/Connection.java | 15 ++-- .../javasabr/rlib/network/NetworkConfig.java | 9 +- .../javasabr/rlib/network/NetworkCryptor.java | 13 ++- .../javasabr/rlib/network/NetworkFactory.java | 77 ++++++++-------- .../rlib/network/ServerNetworkConfig.java | 7 +- .../rlib/network/client/ClientNetwork.java | 10 +-- .../client/impl/DefaultClientNetwork.java | 15 ++-- .../network/client/impl/package-info.java | 4 + .../rlib/network/client/package-info.java | 4 + .../rlib/network/impl/AbstractConnection.java | 57 ++++++------ .../rlib/network/impl/AbstractNetwork.java | 9 +- .../network/impl/AbstractSSLConnection.java | 13 ++- .../network/impl/DefaultBufferAllocator.java | 27 +++--- .../rlib/network/impl/DefaultConnection.java | 9 +- .../network/impl/DefaultDataConnection.java | 17 ++-- .../impl/DefaultDataSSLConnection.java | 19 ++-- .../network/impl/IdBasedPacketConnection.java | 19 ++-- .../network/impl/ReuseBufferAllocator.java | 35 ++++---- .../network/impl/StringDataConnection.java | 9 +- .../network/impl/StringDataSSLConnection.java | 11 ++- .../rlib/network/impl/package-info.java | 4 + .../javasabr/rlib/network/package-info.java | 4 + .../network/packet/IdBasedReadablePacket.java | 5 +- .../javasabr/rlib/network/packet/Packet.java | 4 +- .../rlib/network/packet/ReadablePacket.java | 3 +- .../packet/ReusableWritablePacket.java | 3 +- .../rlib/network/packet/WritablePacket.java | 21 +++-- .../impl/AbstractIdBasedReadablePacket.java | 5 +- .../network/packet/impl/AbstractPacket.java | 4 +- .../packet/impl/AbstractPacketReader.java | 59 ++++++------ .../packet/impl/AbstractPacketWriter.java | 89 +++++++++---------- .../packet/impl/AbstractReadablePacket.java | 23 +++-- .../impl/AbstractReusableWritablePacket.java | 13 ++- .../packet/impl/AbstractSSLPacketReader.java | 33 ++++--- .../packet/impl/AbstractSSLPacketWriter.java | 35 ++++---- .../packet/impl/AbstractWritablePacket.java | 5 +- .../packet/impl/DefaultPacketReader.java | 21 +++-- .../packet/impl/DefaultPacketWriter.java | 33 ++++--- .../packet/impl/DefaultSSLPacketReader.java | 25 +++--- .../packet/impl/DefaultSSLPacketWriter.java | 39 ++++---- .../packet/impl/IdBasedPacketReader.java | 21 +++-- .../packet/impl/IdBasedPacketWriter.java | 21 +++-- .../packet/impl/SSLWritablePacket.java | 2 +- .../packet/impl/StringReadablePacket.java | 7 +- .../packet/impl/StringWritablePacket.java | 7 +- .../packet/impl/WritablePacketWrapper.java | 5 +- .../network/packet/impl/package-info.java | 4 + .../rlib/network/packet/package-info.java | 4 + .../registry/ReadablePacketRegistry.java | 25 +++--- .../impl/IdBasedReadablePacketRegistry.java | 19 ++-- .../packet/registry/impl/package-info.java | 4 + .../network/packet/registry/package-info.java | 4 + .../rlib/network/server/ServerNetwork.java | 9 +- .../server/impl/DefaultServerNetwork.java | 21 +++-- .../network/server/impl/package-info.java | 4 + .../rlib/network/server/package-info.java | 4 + .../rlib/network/util/NetworkUtils.java | 67 +++++++------- .../rlib/network/util/package-info.java | 4 + 65 files changed, 549 insertions(+), 544 deletions(-) create mode 100644 rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/package-info.java create mode 100644 rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/package-info.java create mode 100644 rlib-mail/src/main/java/javasabr/rlib/mail/sender/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/client/impl/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/client/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/impl/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/packet/impl/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/packet/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/packet/registry/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/server/impl/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/server/package-info.java create mode 100644 rlib-network/src/main/java/javasabr/rlib/network/util/package-info.java diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java index 8e61d6ef..c13af479 100644 --- a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/MailSender.java @@ -3,7 +3,6 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import javasabr.rlib.mail.sender.exception.UncheckedMessagingException; -import org.jetbrains.annotations.NotNull; public interface MailSender { @@ -15,7 +14,7 @@ public interface MailSender { * @param content the email's content. * @throws UncheckedMessagingException if something was wrong. */ - void send(@NotNull String email, @NotNull String subject, @NotNull String content); + void send(String email, String subject, String content); /** * Send a new email with the subject to the email address. @@ -26,5 +25,5 @@ public interface MailSender { * @return the async result of sending process. * @throws CompletionException -> UncheckedMessagingException if something was wrong. */ - @NotNull CompletableFuture sendAsync(@NotNull String email, @NotNull String subject, @NotNull String content); + CompletableFuture sendAsync(String email, String subject, String content); } diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java index 467d6d96..e9d5545c 100644 --- a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/UncheckedMessagingException.java @@ -1,11 +1,10 @@ package javasabr.rlib.mail.sender.exception; import jakarta.mail.MessagingException; -import org.jetbrains.annotations.NotNull; public class UncheckedMessagingException extends RuntimeException { - public UncheckedMessagingException(@NotNull MessagingException cause) { + public UncheckedMessagingException(MessagingException cause) { super(cause); } } diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/package-info.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/package-info.java new file mode 100644 index 00000000..1b2e7f33 --- /dev/null +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/exception/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.mail.sender.exception; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java index e52a31a5..5d482999 100644 --- a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/JavaxMailSender.java @@ -27,7 +27,6 @@ import javasabr.rlib.mail.sender.exception.UncheckedMessagingException; import lombok.Builder; import lombok.Getter; -import org.jetbrains.annotations.NotNull; public class JavaxMailSender implements MailSender { @@ -48,7 +47,7 @@ public static class JavaxMailSenderConfig { private final Session session; private final InternetAddress from; - public JavaxMailSender(@NotNull MailSenderConfig config) { + public JavaxMailSender(MailSenderConfig config) { this( config, JavaxMailSenderConfig @@ -59,7 +58,7 @@ public JavaxMailSender(@NotNull MailSenderConfig config) { .build()); } - public JavaxMailSender(@NotNull MailSenderConfig config, @NotNull JavaxMailSenderConfig javaxConfig) { + public JavaxMailSender(MailSenderConfig config, JavaxMailSenderConfig javaxConfig) { var prop = new Properties(); prop.put("mail.smtp.auth", String.valueOf(config.isUseAuth())); @@ -80,7 +79,7 @@ public JavaxMailSender(@NotNull MailSenderConfig config, @NotNull JavaxMailSende prop, new Authenticator() { @Override - protected @NotNull PasswordAuthentication getPasswordAuthentication() { + protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); @@ -112,7 +111,7 @@ prop, new Authenticator() { } @Override - public void send(@NotNull String email, @NotNull String subject, @NotNull String content) { + public void send(String email, String subject, String content) { try { @@ -137,10 +136,10 @@ public void send(@NotNull String email, @NotNull String subject, @NotNull String } @Override - public @NotNull CompletableFuture sendAsync( - @NotNull String email, - @NotNull String subject, - @NotNull String content) { + public CompletableFuture sendAsync( + String email, + String subject, + String content) { return runAsync(() -> send(email, subject, content), executor); } } diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/package-info.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/package-info.java new file mode 100644 index 00000000..82c2826a --- /dev/null +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.mail.sender.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-mail/src/main/java/javasabr/rlib/mail/sender/package-info.java b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/package-info.java new file mode 100644 index 00000000..83994781 --- /dev/null +++ b/rlib-mail/src/main/java/javasabr/rlib/mail/sender/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.mail.sender; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file 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 769c9303..52810c1d 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/BufferAllocator.java @@ -1,7 +1,6 @@ package javasabr.rlib.network; import java.nio.ByteBuffer; -import org.jetbrains.annotations.NotNull; /** * The interface to implement a buffer allocator for network things. @@ -15,21 +14,21 @@ public interface BufferAllocator { * * @return the new buffer. */ - @NotNull ByteBuffer takeReadBuffer(); + ByteBuffer takeReadBuffer(); /** * Get a new pending buffer to use. * * @return the new pending buffer. */ - @NotNull ByteBuffer takePendingBuffer(); + ByteBuffer takePendingBuffer(); /** * Get a new write buffer to use. * * @return the new buffer. */ - @NotNull ByteBuffer takeWriteBuffer(); + ByteBuffer takeWriteBuffer(); /** * Get a new buffer with requested capacity. @@ -37,7 +36,7 @@ public interface BufferAllocator { * @param bufferSize the size of new buffer. * @return the new buffer. */ - @NotNull ByteBuffer takeBuffer(int bufferSize); + ByteBuffer takeBuffer(int bufferSize); /** * Store an old read buffer if need. @@ -45,7 +44,7 @@ public interface BufferAllocator { * @param buffer the old read buffer. * @return this allocator. */ - @NotNull BufferAllocator putReadBuffer(@NotNull ByteBuffer buffer); + BufferAllocator putReadBuffer(ByteBuffer buffer); /** * Store an old pending buffer if need. @@ -53,7 +52,7 @@ public interface BufferAllocator { * @param buffer the old pending buffer. * @return this allocator. */ - @NotNull BufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer); + BufferAllocator putPendingBuffer(ByteBuffer buffer); /** * Store an old write buffer if need. @@ -61,7 +60,7 @@ public interface BufferAllocator { * @param buffer the old write buffer. * @return this allocator. */ - @NotNull BufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer); + BufferAllocator putWriteBuffer(ByteBuffer buffer); /** * Store an old byte buffer if need. @@ -70,5 +69,5 @@ public interface BufferAllocator { * @return this allocator. */ - @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer); + 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 18dee5c2..77d65ce3 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/Connection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/Connection.java @@ -5,7 +5,6 @@ import javasabr.rlib.network.packet.ReadablePacket; import javasabr.rlib.network.packet.WritablePacket; import lombok.AllArgsConstructor; -import org.jetbrains.annotations.NotNull; import reactor.core.publisher.Flux; /** @@ -17,9 +16,7 @@ public interface Connection @AllArgsConstructor class ReceivedPacketEvent, R extends ReadablePacket> { - @NotNull public final C connection; - @NotNull public final R packet; } @@ -28,7 +25,7 @@ class ReceivedPacketEvent, R extends ReadablePacket> * * @return the remote address. */ - @NotNull String getRemoteAddress(); + String getRemoteAddress(); /** * Get a timestamp of last write/read activity. @@ -54,7 +51,7 @@ class ReceivedPacketEvent, R extends ReadablePacket> * * @param packet the writable packet. */ - void send(@NotNull W packet); + void send(W packet); /** * Send a packet to connection's owner with async feedback of this sending. @@ -63,26 +60,26 @@ class ReceivedPacketEvent, R extends ReadablePacket> * @return the async result with true if the packet was sent or false if sending was failed. * @since 9.5.0 */ - @NotNull CompletableFuture sendWithFeedback(@NotNull W packet); + CompletableFuture sendWithFeedback(W packet); /** * Register a consumer to handle received packets. * * @param consumer the consumer. */ - void onReceive(@NotNull NotNullBiConsumer, ? super R> consumer); + void onReceive(NotNullBiConsumer, ? super R> consumer); /** * Get a stream of received packet events. * * @return the stream of received packet events. */ - @NotNull Flux, ? extends R>> receivedEvents(); + Flux, ? extends R>> receivedEvents(); /** * Get a stream of received packets. * * @return the stream of received packets. */ - @NotNull Flux receivedPackets(); + Flux receivedPackets(); } 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 cb0f6973..7c2ce76b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkConfig.java @@ -3,7 +3,6 @@ import java.nio.ByteOrder; import lombok.Builder; import lombok.Getter; -import org.jetbrains.annotations.NotNull; /** * The interface to implement a network config. @@ -29,10 +28,10 @@ class SimpleNetworkConfig implements NetworkConfig { private int writeBufferSize = 2048; } - @NotNull NetworkConfig DEFAULT_CLIENT = new NetworkConfig() { + NetworkConfig DEFAULT_CLIENT = new NetworkConfig() { @Override - public @NotNull String getThreadGroupName() { + public String getThreadGroupName() { return "ClientNetworkThread"; } }; @@ -42,7 +41,7 @@ class SimpleNetworkConfig implements NetworkConfig { * * @return the group name. */ - default @NotNull String getThreadGroupName() { + default String getThreadGroupName() { return "NetworkThread"; } @@ -74,7 +73,7 @@ default int getWriteBufferSize() { return 2048; } - default @NotNull ByteOrder getByteOrder() { + default ByteOrder getByteOrder() { return ByteOrder.BIG_ENDIAN; } 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 8d85968c..b9fb1fe7 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkCryptor.java @@ -1,8 +1,7 @@ package javasabr.rlib.network; import java.nio.ByteBuffer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The interface to implement a network cryptor. @@ -14,15 +13,15 @@ public interface NetworkCryptor { /** * Default NULL implementation of the network crypt. */ - @NotNull NetworkCryptor NULL = new NetworkCryptor() { + NetworkCryptor NULL = new NetworkCryptor() { @Override - public @Nullable ByteBuffer decrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore) { + public @Nullable ByteBuffer decrypt(ByteBuffer data, int length, ByteBuffer toStore) { return null; } @Override - public @Nullable ByteBuffer encrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore) { + public @Nullable ByteBuffer encrypt(ByteBuffer data, int length, ByteBuffer toStore) { return null; } }; @@ -35,7 +34,7 @@ public interface NetworkCryptor { * @param toStore the buffer to store decrypted data. * @return the buffer with decrypted data or null if don't need to decrypt anything. */ - @Nullable ByteBuffer decrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore); + @Nullable ByteBuffer decrypt(ByteBuffer data, int length, ByteBuffer toStore); /** * Encrypt data. @@ -45,5 +44,5 @@ public interface NetworkCryptor { * @param toStore the buffer to store encrypted data. * @return the buffer with encrypted data or null if don't need to decrypt encrypt. */ - @Nullable ByteBuffer encrypt(@NotNull ByteBuffer data, int length, @NotNull ByteBuffer toStore); + @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 8df7b8fa..ab1edeee 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/NetworkFactory.java @@ -13,7 +13,6 @@ import javasabr.rlib.network.server.ServerNetwork; import javasabr.rlib.network.server.impl.DefaultServerNetwork; import javax.net.ssl.SSLContext; -import org.jetbrains.annotations.NotNull; /** * Class with factory methods to build client/server networks. @@ -22,15 +21,15 @@ */ public final class NetworkFactory { - public static > @NotNull ClientNetwork newClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + public static > ClientNetwork newClientNetwork( + NetworkConfig networkConfig, + BiFunction, AsynchronousSocketChannel, C> channelToConnection) { return new DefaultClientNetwork<>(networkConfig, channelToConnection); } - public static > @NotNull ServerNetwork newServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + public static > ServerNetwork newServerNetwork( + ServerNetworkConfig networkConfig, + BiFunction, AsynchronousSocketChannel, C> channelToConnection) { return new DefaultServerNetwork<>(networkConfig, channelToConnection); } @@ -39,7 +38,7 @@ public final class NetworkFactory { * * @return the client network. */ - public static @NotNull ClientNetwork newStringDataClientNetwork() { + public static ClientNetwork newStringDataClientNetwork() { return newStringDataClientNetwork(NetworkConfig.DEFAULT_CLIENT); } @@ -49,8 +48,8 @@ public final class NetworkFactory { * @param networkConfig the network config. * @return the client network. */ - public static @NotNull ClientNetwork newStringDataClientNetwork( - @NotNull NetworkConfig networkConfig) { + public static ClientNetwork newStringDataClientNetwork( + NetworkConfig networkConfig) { return newStringDataClientNetwork(networkConfig, new DefaultBufferAllocator(networkConfig)); } @@ -61,9 +60,9 @@ public final class NetworkFactory { * @param bufferAllocator the buffer allocator. * @return the client network. */ - public static @NotNull ClientNetwork newStringDataClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator) { + public static ClientNetwork newStringDataClientNetwork( + NetworkConfig networkConfig, + BufferAllocator bufferAllocator) { return newClientNetwork( networkConfig, (network, channel) -> new StringDataConnection(network, channel, bufferAllocator)); @@ -75,8 +74,8 @@ public final class NetworkFactory { * @param packetRegistry the readable packet registry. * @return the server network. */ - public static @NotNull ClientNetwork newDefaultClientNetwork( - @NotNull ReadablePacketRegistry packetRegistry) { + public static ClientNetwork newDefaultClientNetwork( + ReadablePacketRegistry packetRegistry) { return newDefaultClientNetwork( NetworkConfig.DEFAULT_CLIENT, new DefaultBufferAllocator(NetworkConfig.DEFAULT_CLIENT), @@ -91,10 +90,10 @@ public final class NetworkFactory { * @param packetRegistry the readable packet registry. * @return the server network. */ - public static @NotNull ClientNetwork newDefaultClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry) { + public static ClientNetwork newDefaultClientNetwork( + NetworkConfig networkConfig, + BufferAllocator bufferAllocator, + ReadablePacketRegistry packetRegistry) { return newClientNetwork( networkConfig, (network, channel) -> new DefaultConnection(network, channel, bufferAllocator, packetRegistry)); @@ -108,10 +107,10 @@ public final class NetworkFactory { * @param sslContext the ssl context. * @return the client network. */ - public static @NotNull ClientNetwork newStringDataSSLClientNetwork( - @NotNull NetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext) { + public static ClientNetwork newStringDataSSLClientNetwork( + NetworkConfig networkConfig, + BufferAllocator bufferAllocator, + SSLContext sslContext) { return newClientNetwork( networkConfig, (network, channel) -> new StringDataSSLConnection(network, channel, bufferAllocator, sslContext, true)); @@ -122,7 +121,7 @@ public final class NetworkFactory { * * @return the server network. */ - public static @NotNull ServerNetwork newStringDataServerNetwork() { + public static ServerNetwork newStringDataServerNetwork() { return newStringDataServerNetwork(ServerNetworkConfig.DEFAULT_SERVER); } @@ -132,8 +131,8 @@ public final class NetworkFactory { * @param networkConfig the network config. * @return the server network. */ - public static @NotNull ServerNetwork newStringDataServerNetwork( - @NotNull ServerNetworkConfig networkConfig) { + public static ServerNetwork newStringDataServerNetwork( + ServerNetworkConfig networkConfig) { return newStringDataServerNetwork(networkConfig, new DefaultBufferAllocator(networkConfig)); } @@ -144,9 +143,9 @@ public final class NetworkFactory { * @param bufferAllocator the buffer allocator. * @return the server network. */ - public static @NotNull ServerNetwork newStringDataServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator) { + public static ServerNetwork newStringDataServerNetwork( + ServerNetworkConfig networkConfig, + BufferAllocator bufferAllocator) { return newServerNetwork( networkConfig, (network, channel) -> new StringDataConnection(network, channel, bufferAllocator)); @@ -160,10 +159,10 @@ public final class NetworkFactory { * @param sslContext the ssl context. * @return the server network. */ - public static @NotNull ServerNetwork newStringDataSSLServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext) { + public static ServerNetwork newStringDataSSLServerNetwork( + ServerNetworkConfig networkConfig, + BufferAllocator bufferAllocator, + SSLContext sslContext) { return newServerNetwork( networkConfig, (network, channel) -> new StringDataSSLConnection(network, channel, bufferAllocator, sslContext, false)); @@ -175,8 +174,8 @@ public final class NetworkFactory { * @param packetRegistry the readable packet registry. * @return the server network. */ - public static @NotNull ServerNetwork newDefaultServerNetwork( - @NotNull ReadablePacketRegistry packetRegistry) { + public static ServerNetwork newDefaultServerNetwork( + ReadablePacketRegistry packetRegistry) { return newDefaultServerNetwork( ServerNetworkConfig.DEFAULT_SERVER, new DefaultBufferAllocator(ServerNetworkConfig.DEFAULT_SERVER), @@ -191,10 +190,10 @@ public final class NetworkFactory { * @param packetRegistry the readable packet registry. * @return the server network. */ - public static @NotNull ServerNetwork newDefaultServerNetwork( - @NotNull ServerNetworkConfig networkConfig, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry) { + public static ServerNetwork newDefaultServerNetwork( + ServerNetworkConfig networkConfig, + BufferAllocator bufferAllocator, + ReadablePacketRegistry packetRegistry) { return newServerNetwork( networkConfig, (network, channel) -> new DefaultConnection(network, channel, bufferAllocator, packetRegistry)); 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 bb405284..2d9cf73f 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/ServerNetworkConfig.java @@ -4,7 +4,6 @@ import javasabr.rlib.common.concurrent.GroupThreadFactory; import lombok.Builder; import lombok.Getter; -import org.jetbrains.annotations.NotNull; /** * The interface to implement a server network config. @@ -36,7 +35,7 @@ class SimpleServerNetworkConfig implements ServerNetworkConfig { private int threadPriority = Thread.NORM_PRIORITY; } - @NotNull ServerNetworkConfig DEFAULT_SERVER = new ServerNetworkConfig() { + ServerNetworkConfig DEFAULT_SERVER = new ServerNetworkConfig() { @Override public int getThreadGroupMinSize() { @@ -44,7 +43,7 @@ public int getThreadGroupMinSize() { } @Override - public @NotNull String getThreadGroupName() { + public String getThreadGroupName() { return "ServerNetworkThread"; } }; @@ -72,7 +71,7 @@ default int getThreadGroupMaxSize() { * * @return the thread constructor. */ - default @NotNull GroupThreadFactory.ThreadConstructor getThreadConstructor() { + default GroupThreadFactory.ThreadConstructor getThreadConstructor() { return Thread::new; } 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 d9316e77..836d28d7 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 @@ -4,8 +4,7 @@ import java.util.concurrent.CompletableFuture; import javasabr.rlib.network.Connection; import javasabr.rlib.network.Network; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; import reactor.core.publisher.Mono; /** @@ -21,7 +20,7 @@ public interface ClientNetwork> extends Network { * @param serverAddress the sever address. * @return the future with result connection. */ - @NotNull CompletableFuture connect(@NotNull InetSocketAddress serverAddress); + CompletableFuture connect(InetSocketAddress serverAddress); /** * Connect to a server by the address. @@ -29,12 +28,13 @@ public interface ClientNetwork> extends Network { * @param serverAddress the sever address. * @return the future with result connection. */ - @NotNull Mono connected(@NotNull InetSocketAddress serverAddress); + Mono connected(InetSocketAddress serverAddress); /** * Get a current connection to a server or null. * * @return the current connection or null. */ - @Nullable C getCurrentConnection(); + @Nullable + C getCurrentConnection(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java index 30f255d6..73bd98ec 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java @@ -21,8 +21,7 @@ import javasabr.rlib.network.impl.AbstractNetwork; import javasabr.rlib.network.util.NetworkUtils; import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; import reactor.core.publisher.Mono; /** @@ -34,15 +33,15 @@ public class DefaultClientNetwork> extends AbstractNe protected static final Logger LOGGER = LoggerManager.getLogger(DefaultClientNetwork.class); - protected final @NotNull AtomicBoolean connecting; + protected final AtomicBoolean connecting; protected volatile @Nullable CompletableFuture pendingConnection; protected volatile @Getter @Nullable C currentConnection; public DefaultClientNetwork( - @NotNull NetworkConfig config, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + NetworkConfig config, + BiFunction, AsynchronousSocketChannel, C> channelToConnection) { super(config, channelToConnection); this.connecting = new AtomicBoolean(false); @@ -54,7 +53,7 @@ public DefaultClientNetwork( } @Override - public @NotNull CompletableFuture connect(@NotNull InetSocketAddress serverAddress) { + public CompletableFuture connect(InetSocketAddress serverAddress) { C currentConnection = getCurrentConnection(); @@ -89,7 +88,7 @@ public void completed(@Nullable Void result, @Nullable Void attachment) { } @Override - public void failed(@NotNull Throwable exc, @Nullable Void attachment) { + public void failed(Throwable exc, @Nullable Void attachment) { asyncResult.completeExceptionally(exc); } }); @@ -104,7 +103,7 @@ public void failed(@NotNull Throwable exc, @Nullable Void attachment) { } @Override - public @NotNull Mono connected(@NotNull InetSocketAddress serverAddress) { + public Mono connected(InetSocketAddress serverAddress) { return Mono.create(monoSink -> connect(serverAddress).whenComplete((connection, ex) -> { if (ex != null) { monoSink.error(ex); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/client/impl/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/package-info.java new file mode 100644 index 00000000..25a38743 --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.client.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-network/src/main/java/javasabr/rlib/network/client/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/client/package-info.java new file mode 100644 index 00000000..6c938d1e --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/client/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.client; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file 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 c744f6d6..cd7961ee 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 @@ -26,8 +26,7 @@ import javasabr.rlib.network.packet.impl.WritablePacketWrapper; import javasabr.rlib.network.util.NetworkUtils; import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; @@ -44,33 +43,33 @@ public abstract class AbstractConnection extends WritablePacketWrapper, W> { - public WritablePacketWithFeedback(@NotNull CompletableFuture attachment, @NotNull W packet) { + public WritablePacketWithFeedback(CompletableFuture attachment, W packet) { super(attachment, packet); } } protected final @Getter - @NotNull String remoteAddress; + String remoteAddress; - protected final @NotNull Network> network; - protected final @NotNull BufferAllocator bufferAllocator; - protected final @NotNull AsynchronousSocketChannel channel; - protected final @NotNull LinkedList pendingPackets; - protected final @NotNull StampedLock lock; + protected final Network> network; + protected final BufferAllocator bufferAllocator; + protected final AsynchronousSocketChannel channel; + protected final LinkedList pendingPackets; + protected final StampedLock lock; - protected final @NotNull AtomicBoolean isWriting; - protected final @NotNull AtomicBoolean closed; + protected final AtomicBoolean isWriting; + protected final AtomicBoolean closed; - protected final @NotNull Array, ? super R>> subscribers; + protected final Array, ? super R>> subscribers; protected final int maxPacketsByRead; protected volatile @Getter long lastActivity; public AbstractConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, int maxPacketsByRead) { this.bufferAllocator = bufferAllocator; this.maxPacketsByRead = maxPacketsByRead; @@ -88,11 +87,11 @@ public AbstractConnection( public void onConnected() { } - protected abstract @NotNull PacketReader getPacketReader(); + protected abstract PacketReader getPacketReader(); - protected abstract @NotNull PacketWriter getPacketWriter(); + protected abstract PacketWriter getPacketWriter(); - protected void handleReceivedPacket(@NotNull R packet) { + protected void handleReceivedPacket(R packet) { LOGGER.debug( channel, packet, @@ -101,23 +100,23 @@ protected void handleReceivedPacket(@NotNull R packet) { } @Override - public void onReceive(@NotNull NotNullBiConsumer, ? super R> consumer) { + public void onReceive(NotNullBiConsumer, ? super R> consumer) { subscribers.add(consumer); getPacketReader().startRead(); } @Override - public @NotNull Flux, ? extends R>> receivedEvents() { + public Flux, ? extends R>> receivedEvents() { return Flux.create(this::registerFluxOnReceivedEvents); } @Override - public @NotNull Flux receivedPackets() { + public Flux receivedPackets() { return Flux.create(this::registerFluxOnReceivedPackets); } protected void registerFluxOnReceivedEvents( - @NotNull FluxSink, ? extends R>> sink) { + FluxSink, ? extends R>> sink) { NotNullBiConsumer, R> listener = (connection, packet) -> sink.next(new ReceivedPacketEvent<>(connection, @@ -128,7 +127,7 @@ protected void registerFluxOnReceivedEvents( sink.onDispose(() -> subscribers.remove(listener)); } - protected void registerFluxOnReceivedPackets(@NotNull FluxSink sink) { + protected void registerFluxOnReceivedPackets(FluxSink sink) { NotNullBiConsumer, R> listener = (connection, packet) -> sink.next(packet); @@ -180,10 +179,10 @@ public boolean isClosed() { return closed.get(); } - protected void onWrittenPacket(@NotNull WritablePacket packet) { + protected void onWrittenPacket(WritablePacket packet) { } - protected void onSentPacket(@NotNull WritablePacket packet, @NotNull Boolean result) { + protected void onSentPacket(WritablePacket packet, Boolean result) { if (packet instanceof WritablePacketWithFeedback) { ((WritablePacketWithFeedback) packet) .getAttachment() @@ -192,11 +191,11 @@ protected void onSentPacket(@NotNull WritablePacket packet, @NotNull Boolean res } @Override - public final void send(@NotNull W packet) { + public final void send(W packet) { sendImpl(packet); } - protected void sendImpl(@NotNull WritablePacket packet) { + protected void sendImpl(WritablePacket packet) { if (isClosed()) { return; @@ -212,7 +211,7 @@ protected void sendImpl(@NotNull WritablePacket packet) { getPacketWriter().writeNextPacket(); } - protected void queueAtFirst(@NotNull WritablePacket packet) { + protected void queueAtFirst(WritablePacket packet) { long stamp = lock.writeLock(); try { pendingPackets.addFirst(packet); @@ -222,7 +221,7 @@ protected void queueAtFirst(@NotNull WritablePacket packet) { } @Override - public @NotNull CompletableFuture sendWithFeedback(@NotNull W packet) { + public CompletableFuture sendWithFeedback(W packet) { var asyncResult = new CompletableFuture(); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java index 9b7cb91f..d2b8e76a 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractNetwork.java @@ -7,7 +7,6 @@ import javasabr.rlib.network.Connection; import javasabr.rlib.network.Network; import javasabr.rlib.network.NetworkConfig; -import org.jetbrains.annotations.NotNull; /** * The base implementation of {@link Network}. @@ -18,12 +17,12 @@ public abstract class AbstractNetwork> implements Net protected static final Logger LOGGER = LoggerManager.getLogger(AbstractNetwork.class); - protected final @NotNull NetworkConfig config; - protected final @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection; + protected final NetworkConfig config; + protected final BiFunction, AsynchronousSocketChannel, C> channelToConnection; protected AbstractNetwork( - @NotNull NetworkConfig config, - @NotNull BiFunction, AsynchronousSocketChannel, C> channelToConnection) { + NetworkConfig config, + BiFunction, AsynchronousSocketChannel, C> channelToConnection) { this.config = config; this.channelToConnection = channelToConnection; } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java index b870ff79..80a4ae16 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/AbstractSSLConnection.java @@ -9,18 +9,17 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; -import org.jetbrains.annotations.NotNull; public abstract class AbstractSSLConnection extends AbstractConnection { - protected final @NotNull SSLEngine sslEngine; + protected final SSLEngine sslEngine; public AbstractSSLConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext, + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + SSLContext sslContext, int maxPacketsByRead, boolean clientMode) { super(network, channel, bufferAllocator, maxPacketsByRead); @@ -34,7 +33,7 @@ public AbstractSSLConnection( } @Override - protected void sendImpl(@NotNull WritablePacket packet) { + protected void sendImpl(WritablePacket packet) { super.sendImpl(packet); getPacketReader().startRead(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java index 9d139e8f..70109892 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultBufferAllocator.java @@ -8,7 +8,6 @@ import javasabr.rlib.network.BufferAllocator; import javasabr.rlib.network.NetworkConfig; import lombok.ToString; -import org.jetbrains.annotations.NotNull; /** * The default byte buffer allocator. @@ -20,13 +19,13 @@ public class DefaultBufferAllocator implements BufferAllocator { private static final Logger LOGGER = LoggerManager.getLogger(DefaultBufferAllocator.class); - protected final @NotNull Pool readBufferPool; - protected final @NotNull Pool pendingBufferPool; - protected final @NotNull Pool writeBufferPool; + protected final Pool readBufferPool; + protected final Pool pendingBufferPool; + protected final Pool writeBufferPool; - protected final @NotNull NetworkConfig config; + protected final NetworkConfig config; - public DefaultBufferAllocator(@NotNull NetworkConfig config) { + public DefaultBufferAllocator(NetworkConfig config) { this.config = config; this.readBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); this.pendingBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); @@ -34,7 +33,7 @@ public DefaultBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull ByteBuffer takeReadBuffer() { + public ByteBuffer takeReadBuffer() { var bufferSize = config.getReadBufferSize(); LOGGER.debug(bufferSize, size -> "Allocate a new read buffer with size: " + size); return config.isDirectByteBuffer() @@ -46,7 +45,7 @@ public DefaultBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull ByteBuffer takePendingBuffer() { + public ByteBuffer takePendingBuffer() { var bufferSize = config.getPendingBufferSize(); LOGGER.debug(bufferSize, size -> "Allocate a new pending buffer with size: " + size); return config.isDirectByteBuffer() @@ -58,7 +57,7 @@ public DefaultBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull ByteBuffer takeWriteBuffer() { + public ByteBuffer takeWriteBuffer() { var bufferSize = config.getWriteBufferSize(); LOGGER.debug(bufferSize, size -> "Allocate a new write buffer with size: " + size); return config.isDirectByteBuffer() @@ -70,7 +69,7 @@ public DefaultBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { + public ByteBuffer takeBuffer(int bufferSize) { LOGGER.debug(bufferSize, size -> "Allocate a new buffer with size: " + size); return config.isDirectByteBuffer() ? ByteBuffer.allocateDirect(bufferSize) @@ -81,25 +80,25 @@ public DefaultBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull DefaultBufferAllocator putReadBuffer(@NotNull ByteBuffer buffer) { + public DefaultBufferAllocator putReadBuffer(ByteBuffer buffer) { LOGGER.debug("Skip storing a read buffer"); return this; } @Override - public @NotNull DefaultBufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer) { + public DefaultBufferAllocator putPendingBuffer(ByteBuffer buffer) { LOGGER.debug("Skip storing a pending buffer"); return this; } @Override - public @NotNull DefaultBufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer) { + public DefaultBufferAllocator putWriteBuffer(ByteBuffer buffer) { LOGGER.debug("Skip storing a write buffer"); return this; } @Override - public @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer) { + public BufferAllocator putBuffer(ByteBuffer buffer) { LOGGER.debug("Skip storing a mapped byte buffer"); return this; } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java index db2d93b6..c14df701 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultConnection.java @@ -7,7 +7,6 @@ import javasabr.rlib.network.packet.impl.DefaultReadablePacket; import javasabr.rlib.network.packet.impl.DefaultWritablePacket; import javasabr.rlib.network.packet.registry.ReadablePacketRegistry; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -15,10 +14,10 @@ public class DefaultConnection extends IdBasedPacketConnection { public DefaultConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry) { + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + ReadablePacketRegistry packetRegistry) { super(network, channel, bufferAllocator, packetRegistry, 100, 2, 2); } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java index f34f5afd..c9146330 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataConnection.java @@ -12,7 +12,6 @@ import javasabr.rlib.network.packet.impl.DefaultPacketWriter; import lombok.AccessLevel; import lombok.Getter; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -21,15 +20,15 @@ public abstract class DefaultDataConnection extends AbstractConnection { - private final @NotNull PacketReader packetReader; - private final @NotNull PacketWriter packetWriter; + private final PacketReader packetReader; + private final PacketWriter packetWriter; private final int packetLengthHeaderSize; public DefaultDataConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, int maxPacketsByRead, int packetLengthHeaderSize) { super(network, channel, bufferAllocator, maxPacketsByRead); @@ -38,7 +37,7 @@ public DefaultDataConnection( this.packetWriter = createPacketWriter(); } - protected @NotNull PacketReader createPacketReader() { + protected PacketReader createPacketReader() { return new DefaultPacketReader<>( this, channel, @@ -50,7 +49,7 @@ public DefaultDataConnection( maxPacketsByRead); } - protected @NotNull PacketWriter createPacketWriter() { + protected PacketWriter createPacketWriter() { return new DefaultPacketWriter>( this, channel, @@ -62,5 +61,5 @@ public DefaultDataConnection( packetLengthHeaderSize); } - protected abstract @NotNull R createReadablePacket(); + protected abstract R createReadablePacket(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java index 6ab0232a..283220d2 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/DefaultDataSSLConnection.java @@ -13,7 +13,6 @@ import javax.net.ssl.SSLContext; import lombok.AccessLevel; import lombok.Getter; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -22,16 +21,16 @@ public abstract class DefaultDataSSLConnection extends AbstractSSLConnection { - private final @NotNull PacketReader packetReader; - private final @NotNull PacketWriter packetWriter; + private final PacketReader packetReader; + private final PacketWriter packetWriter; private final int packetLengthHeaderSize; public DefaultDataSSLConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext, + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + SSLContext sslContext, int maxPacketsByRead, int packetLengthHeaderSize, boolean clientMode) { @@ -41,7 +40,7 @@ public DefaultDataSSLConnection( this.packetWriter = createPacketWriter(); } - protected @NotNull PacketReader createPacketReader() { + protected PacketReader createPacketReader() { return new DefaultSSLPacketReader<>( this, channel, @@ -55,7 +54,7 @@ public DefaultDataSSLConnection( maxPacketsByRead); } - protected @NotNull PacketWriter createPacketWriter() { + protected PacketWriter createPacketWriter() { return new DefaultSSLPacketWriter>( this, channel, @@ -70,5 +69,5 @@ public DefaultDataSSLConnection( packetLengthHeaderSize); } - protected abstract @NotNull R createReadablePacket(); + protected abstract R createReadablePacket(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java index a56a641b..3f98fa0b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/IdBasedPacketConnection.java @@ -13,7 +13,6 @@ import javasabr.rlib.network.packet.registry.ReadablePacketRegistry; import lombok.AccessLevel; import lombok.Getter; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -22,18 +21,18 @@ public class IdBasedPacketConnection, W extends IdBasedWritablePacket> extends AbstractConnection { - private final @NotNull PacketReader packetReader; - private final @NotNull PacketWriter packetWriter; - private final @NotNull ReadablePacketRegistry packetRegistry; + private final PacketReader packetReader; + private final PacketWriter packetWriter; + private final ReadablePacketRegistry packetRegistry; private final int packetLengthHeaderSize; private final int packetIdHeaderSize; public IdBasedPacketConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull ReadablePacketRegistry packetRegistry, + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + ReadablePacketRegistry packetRegistry, int maxPacketsByRead, int packetLengthHeaderSize, int packetIdHeaderSize) { @@ -45,7 +44,7 @@ public IdBasedPacketConnection( this.packetWriter = createPacketWriter(); } - protected @NotNull PacketReader createPacketReader() { + protected PacketReader createPacketReader() { return new IdBasedPacketReader<>( this, channel, @@ -58,7 +57,7 @@ public IdBasedPacketConnection( packetRegistry); } - protected @NotNull PacketWriter createPacketWriter() { + protected PacketWriter createPacketWriter() { return new IdBasedPacketWriter<>( this, channel, diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java index 7ad99be2..38634d3a 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/ReuseBufferAllocator.java @@ -12,7 +12,6 @@ import javasabr.rlib.network.BufferAllocator; import javasabr.rlib.network.NetworkConfig; import lombok.ToString; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -22,14 +21,14 @@ public class ReuseBufferAllocator implements BufferAllocator { protected static final Logger LOGGER = LoggerManager.getLogger(ReuseBufferAllocator.class); - protected final @NotNull Pool readBufferPool; - protected final @NotNull Pool pendingBufferPool; - protected final @NotNull Pool writeBufferPool; - protected final @NotNull ConcurrentArray byteBuffers; + protected final Pool readBufferPool; + protected final Pool pendingBufferPool; + protected final Pool writeBufferPool; + protected final ConcurrentArray byteBuffers; - protected final @NotNull NetworkConfig config; + protected final NetworkConfig config; - public ReuseBufferAllocator(@NotNull NetworkConfig config) { + public ReuseBufferAllocator(NetworkConfig config) { this.config = config; this.readBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); this.pendingBufferPool = PoolFactory.newConcurrentStampedLockPool(ByteBuffer.class); @@ -38,27 +37,27 @@ public ReuseBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull ByteBuffer takeReadBuffer() { + public ByteBuffer takeReadBuffer() { return readBufferPool .take(config, readBufferFactory()) .clear(); } @Override - public @NotNull ByteBuffer takePendingBuffer() { + public ByteBuffer takePendingBuffer() { return pendingBufferPool .take(config, pendingBufferFactory()) .clear(); } @Override - public @NotNull ByteBuffer takeWriteBuffer() { + public ByteBuffer takeWriteBuffer() { return writeBufferPool .take(config, writeBufferFactory()) .clear(); } - protected @NotNull Function pendingBufferFactory() { + protected Function pendingBufferFactory() { return config -> { var bufferSize = config.getPendingBufferSize(); LOGGER.debug(bufferSize, size -> "Allocate a new pending buffer with size: " + size); @@ -71,7 +70,7 @@ public ReuseBufferAllocator(@NotNull NetworkConfig config) { }; } - protected @NotNull Function readBufferFactory() { + protected Function readBufferFactory() { return config -> { var bufferSize = config.getReadBufferSize(); LOGGER.debug(bufferSize, size -> "Allocate a new read buffer with size: " + size); @@ -84,7 +83,7 @@ public ReuseBufferAllocator(@NotNull NetworkConfig config) { }; } - protected @NotNull Function writeBufferFactory() { + protected Function writeBufferFactory() { return config -> { var bufferSize = config.getWriteBufferSize(); LOGGER.debug(bufferSize, size -> "Allocate a new write buffer with size: " + size); @@ -98,7 +97,7 @@ public ReuseBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull ByteBuffer takeBuffer(int bufferSize) { + public ByteBuffer takeBuffer(int bufferSize) { // check of existing enough buffer for the size under read lock var exist = byteBuffers.findAnyInReadLock(bufferSize, (required, buffer) -> required < buffer.capacity()); @@ -132,25 +131,25 @@ public ReuseBufferAllocator(@NotNull NetworkConfig config) { } @Override - public @NotNull ReuseBufferAllocator putReadBuffer(@NotNull ByteBuffer buffer) { + public ReuseBufferAllocator putReadBuffer(ByteBuffer buffer) { readBufferPool.put(buffer); return this; } @Override - public @NotNull ReuseBufferAllocator putPendingBuffer(@NotNull ByteBuffer buffer) { + public ReuseBufferAllocator putPendingBuffer(ByteBuffer buffer) { pendingBufferPool.put(buffer); return this; } @Override - public @NotNull ReuseBufferAllocator putWriteBuffer(@NotNull ByteBuffer buffer) { + public ReuseBufferAllocator putWriteBuffer(ByteBuffer buffer) { writeBufferPool.put(buffer); return this; } @Override - public @NotNull BufferAllocator putBuffer(@NotNull ByteBuffer buffer) { + public BufferAllocator putBuffer(ByteBuffer buffer) { LOGGER.debug(buffer, buf -> "Save used temp buffer: " + buf + " - (" + buf.hashCode() + ")"); byteBuffers.runInWriteLock(buffer.clear(), Collection::add); return this; diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java index 4cd47239..cbad855b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataConnection.java @@ -6,7 +6,6 @@ import javasabr.rlib.network.Network; import javasabr.rlib.network.packet.impl.StringReadablePacket; import javasabr.rlib.network.packet.impl.StringWritablePacket; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -14,14 +13,14 @@ public class StringDataConnection extends DefaultDataConnection { public StringDataConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator) { + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator) { super(network, channel, bufferAllocator, 100, 2); } @Override - protected @NotNull StringReadablePacket createReadablePacket() { + protected StringReadablePacket createReadablePacket() { return new StringReadablePacket(); } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java index eae9626e..e07e5050 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/StringDataSSLConnection.java @@ -7,7 +7,6 @@ import javasabr.rlib.network.packet.impl.StringReadablePacket; import javasabr.rlib.network.packet.impl.StringWritablePacket; import javax.net.ssl.SSLContext; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -15,16 +14,16 @@ public class StringDataSSLConnection extends DefaultDataSSLConnection { public StringDataSSLConnection( - @NotNull Network> network, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull SSLContext sslContext, + Network> network, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + SSLContext sslContext, boolean clientMode) { super(network, channel, bufferAllocator, sslContext, 100, 2, clientMode); } @Override - protected @NotNull StringReadablePacket createReadablePacket() { + protected StringReadablePacket createReadablePacket() { return new StringReadablePacket(); } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/impl/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/impl/package-info.java new file mode 100644 index 00000000..b88001e7 --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-network/src/main/java/javasabr/rlib/network/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/package-info.java new file mode 100644 index 00000000..53222c6a --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java index 163b2310..ee45a273 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/IdBasedReadablePacket.java @@ -2,7 +2,6 @@ import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.network.Connection; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -14,7 +13,7 @@ public interface IdBasedReadablePacket> exten * * @return the new instance of this type. */ - default @NotNull S newInstance() { + default S newInstance() { return ClassUtils.newInstance(getClass()); } @@ -23,7 +22,7 @@ public interface IdBasedReadablePacket> exten * * @param connection the owner's connection. */ - default void execute(@NotNull Connection connection) { + default void execute(Connection connection) { } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java index 23bfa123..8be12d1c 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/Packet.java @@ -1,7 +1,5 @@ package javasabr.rlib.network.packet; -import org.jetbrains.annotations.NotNull; - /** * The interface to implement a network packet. * @@ -14,5 +12,5 @@ public interface Packet { * * @return the packet's name. */ - @NotNull String getName(); + String getName(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java index 6487e044..58eab190 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/ReadablePacket.java @@ -2,7 +2,6 @@ import java.nio.ByteBuffer; import javasabr.rlib.network.Connection; -import org.jetbrains.annotations.NotNull; /** * The interface to implement a readable network packet. @@ -19,5 +18,5 @@ public interface ReadablePacket extends Packet { * @param length the data length. * @return true if reading was success. */ - boolean read(@NotNull Connection connection, @NotNull ByteBuffer buffer, int length); + boolean read(Connection connection, ByteBuffer buffer, int length); } 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 9ce22f30..29c14a3d 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 @@ -2,7 +2,6 @@ import javasabr.rlib.common.util.pools.Pool; import javasabr.rlib.common.util.pools.Reusable; -import org.jetbrains.annotations.NotNull; /** * The interface to implement a reusable writable packet. @@ -50,7 +49,7 @@ public interface ReusableWritablePacket extends WritablePacket, Reusable { * * @param pool the pool to store used packet. */ - void setPool(@NotNull Pool pool); + void setPool(Pool pool); default void notifyAddedToSend() { increaseSends(); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java index db51eead..cf392115 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/WritablePacket.java @@ -3,7 +3,6 @@ import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import javasabr.rlib.logger.api.LoggerManager; -import org.jetbrains.annotations.NotNull; /** * Interface to implement a writable packet. @@ -18,7 +17,7 @@ public interface WritablePacket extends Packet { * @param buffer the buffer. * @return true if writing was successful. */ - boolean write(@NotNull ByteBuffer buffer); + boolean write(ByteBuffer buffer); /** * Return an expected data length of this packet or -1. @@ -35,7 +34,7 @@ default int getExpectedLength() { * @param buffer the buffer. * @param value the value. */ - default void writeByte(@NotNull ByteBuffer buffer, int value) { + default void writeByte(ByteBuffer buffer, int value) { buffer.put((byte) value); } @@ -45,7 +44,7 @@ default void writeByte(@NotNull ByteBuffer buffer, int value) { * @param buffer the buffer. * @param value the value. */ - default void writeChar(@NotNull ByteBuffer buffer, char value) { + default void writeChar(ByteBuffer buffer, char value) { buffer.putChar(value); } @@ -55,7 +54,7 @@ default void writeChar(@NotNull ByteBuffer buffer, char value) { * @param buffer the buffer. * @param value the value. */ - default void writeChar(@NotNull final ByteBuffer buffer, final int value) { + default void writeChar(final ByteBuffer buffer, final int value) { buffer.putChar((char) value); } @@ -65,7 +64,7 @@ default void writeChar(@NotNull final ByteBuffer buffer, final int value) { * @param buffer the buffer. * @param value the value. */ - default void writeFloat(@NotNull ByteBuffer buffer, float value) { + default void writeFloat(ByteBuffer buffer, float value) { buffer.putFloat(value); } @@ -75,7 +74,7 @@ default void writeFloat(@NotNull ByteBuffer buffer, float value) { * @param buffer the buffer. * @param value the value. */ - default void writeInt(@NotNull ByteBuffer buffer, int value) { + default void writeInt(ByteBuffer buffer, int value) { buffer.putInt(value); } @@ -85,7 +84,7 @@ default void writeInt(@NotNull ByteBuffer buffer, int value) { * @param buffer the buffer. * @param value the value. */ - default void writeLong(@NotNull ByteBuffer buffer, long value) { + default void writeLong(ByteBuffer buffer, long value) { buffer.putLong(value); } @@ -95,7 +94,7 @@ default void writeLong(@NotNull ByteBuffer buffer, long value) { * @param buffer the buffer. * @param value the value for writing. */ - default void writeShort(@NotNull ByteBuffer buffer, int value) { + default void writeShort(ByteBuffer buffer, int value) { buffer.putShort((short) value); } @@ -105,7 +104,7 @@ default void writeShort(@NotNull ByteBuffer buffer, int value) { * @param buffer the buffer. * @param string the string for writing. */ - default void writeString(@NotNull ByteBuffer buffer, @NotNull String string) { + default void writeString(ByteBuffer buffer, String string) { try { writeInt(buffer, string.length()); @@ -130,7 +129,7 @@ default void writeString(@NotNull ByteBuffer buffer, @NotNull String string) { * @param buffer thr packet buffer. * @param data the data buffer. */ - default void writeBuffer(@NotNull ByteBuffer buffer, @NotNull ByteBuffer data) { + default void writeBuffer(ByteBuffer buffer, ByteBuffer data) { buffer.put(data.array(), data.position(), data.limit()); } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java index 9e4c962e..c3202d4e 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractIdBasedReadablePacket.java @@ -5,7 +5,6 @@ import javasabr.rlib.logger.api.LoggerManager; import javasabr.rlib.network.Connection; import javasabr.rlib.network.packet.IdBasedReadablePacket; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -17,7 +16,7 @@ public abstract class AbstractIdBasedReadablePacket, private static final Logger LOGGER = LoggerManager.getLogger(AbstractIdBasedReadablePacket.class); @Override - public void execute(@NotNull Connection connection) { + public void execute(Connection connection) { try { executeImpl(ClassUtils.unsafeNNCast(connection)); } catch (Exception e) { @@ -25,6 +24,6 @@ public void execute(@NotNull Connection connection) { } } - protected void executeImpl(@NotNull C connection) { + protected void executeImpl(C connection) { } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java index 4004e12f..ecc30c0b 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacket.java @@ -23,7 +23,7 @@ public abstract class AbstractPacket implements Packet { * @param buffer the data buffer. * @param exception the exception. */ - protected void handleException(@NotNull ByteBuffer buffer, @NotNull Exception exception) { + protected void handleException(ByteBuffer buffer, Exception exception) { LOGGER.warning(exception); if (buffer.isDirect()) { @@ -36,7 +36,7 @@ protected void handleException(@NotNull ByteBuffer buffer, @NotNull Exception ex } @Override - public @NotNull String getName() { + public String getName() { return getClass().getSimpleName(); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java index 8bd26bdb..e70fe770 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketReader.java @@ -21,8 +21,7 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @param the readable packet's type. @@ -37,27 +36,27 @@ public abstract class AbstractPacketReader readHandler = new CompletionHandler<>() { @Override - public void completed(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { + public void completed(Integer receivedBytes, ByteBuffer readingBuffer) { handleReceivedData(receivedBytes, readingBuffer); } @Override - public void failed(@NotNull Throwable exc, @NotNull ByteBuffer readingBuffer) { + public void failed(Throwable exc, ByteBuffer readingBuffer) { handleFailedReceiving(exc, readingBuffer); } }; - protected final @NotNull AtomicBoolean isReading = new AtomicBoolean(false); + protected final AtomicBoolean isReading = new AtomicBoolean(false); - protected final @NotNull C connection; - protected final @NotNull AsynchronousSocketChannel channel; - protected final @NotNull BufferAllocator bufferAllocator; + protected final C connection; + protected final AsynchronousSocketChannel channel; + protected final BufferAllocator bufferAllocator; - protected final @NotNull ByteBuffer readBuffer; - protected final @NotNull ByteBuffer pendingBuffer; + protected final ByteBuffer readBuffer; + protected final ByteBuffer pendingBuffer; - protected final @NotNull Runnable updateActivityFunction; - protected final @NotNull Consumer readPacketHandler; + protected final Runnable updateActivityFunction; + protected final Consumer readPacketHandler; @Getter(AccessLevel.PROTECTED) @Setter(AccessLevel.PROTECTED) @@ -66,11 +65,11 @@ public void failed(@NotNull Throwable exc, @NotNull ByteBuffer readingBuffer) { protected final int maxPacketsByRead; protected AbstractPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NotNullConsumer readPacketHandler, int maxPacketsByRead) { this.connection = connection; this.channel = channel; @@ -82,7 +81,7 @@ protected AbstractPacketReader( this.maxPacketsByRead = maxPacketsByRead; } - protected @NotNull ByteBuffer getBufferToReadFromChannel() { + protected ByteBuffer getBufferToReadFromChannel() { return readBuffer; } @@ -106,7 +105,7 @@ public void startRead() { * @param receivedBuffer the buffer with received data. * @return count of read packets. */ - protected int readPackets(@NotNull ByteBuffer receivedBuffer) { + protected int readPackets(ByteBuffer receivedBuffer) { return readPackets(receivedBuffer, pendingBuffer); } @@ -117,7 +116,7 @@ protected int readPackets(@NotNull ByteBuffer receivedBuffer) { * @param pendingBuffer the buffer with pending data from prev. received buffer. * @return count of read packets. */ - protected int readPackets(@NotNull ByteBuffer receivedBuffer, @NotNull ByteBuffer pendingBuffer) { + protected int readPackets(ByteBuffer receivedBuffer, ByteBuffer pendingBuffer) { LOGGER.debug(receivedBuffer, buf -> "Start reading packets from received buffer " + buf); @@ -299,7 +298,7 @@ else if (packetLength > tempPendingBuffer.capacity()) { return readPackets; } - protected void readAndHandlePacket(@NotNull ByteBuffer bufferToRead, int dataLength, @NotNull R packet) { + protected void readAndHandlePacket(ByteBuffer bufferToRead, int dataLength, R packet) { if (packet.read(connection, bufferToRead, dataLength)) { readPacketHandler.accept(packet); } else { @@ -313,7 +312,7 @@ protected void readAndHandlePacket(@NotNull ByteBuffer bufferToRead, int dataLen * @param buffer the buffer to read. * @return true if this buffer has enough data to start initial reading. */ - protected abstract boolean canStartReadPacket(@NotNull ByteBuffer buffer); + protected abstract boolean canStartReadPacket(ByteBuffer buffer); /** * Calculate size of packet data. @@ -323,7 +322,7 @@ protected void readAndHandlePacket(@NotNull ByteBuffer bufferToRead, int dataLen * @param buffer the buffer. * @return the length of packet data part. */ - protected int getDataLength(int packetLength, int readBytes, @NotNull ByteBuffer buffer) { + protected int getDataLength(int packetLength, int readBytes, ByteBuffer buffer) { return packetLength - readBytes; } @@ -333,9 +332,9 @@ protected int getDataLength(int packetLength, int readBytes, @NotNull ByteBuffer * @param buffer the buffer with received data. * @return the packet length or -1 if we have no enough data to read length. */ - protected abstract int readPacketLength(@NotNull ByteBuffer buffer); + protected abstract int readPacketLength(ByteBuffer buffer); - protected void reAllocTempBuffers(@NotNull ByteBuffer sourceBuffer, int packetLength) { + protected void reAllocTempBuffers(ByteBuffer sourceBuffer, int packetLength) { LOGGER.debug( sourceBuffer.capacity(), @@ -356,7 +355,7 @@ protected void reAllocTempBuffers(@NotNull ByteBuffer sourceBuffer, int packetLe this.tempPendingBuffer = newReadTempBuffer; } - protected void allocTempBuffers(@NotNull ByteBuffer sourceBuffer, int packetLength) { + protected void allocTempBuffers(ByteBuffer sourceBuffer, int packetLength) { LOGGER.debug( packetLength, @@ -391,7 +390,7 @@ protected void freeTempBuffers() { * @param receivedBytes the count of received bytes. * @param readingBuffer the currently reading buffer. */ - protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { + protected void handleReceivedData(Integer receivedBytes, ByteBuffer readingBuffer) { updateActivityFunction.run(); if (receivedBytes == -1) { @@ -422,7 +421,7 @@ protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteB * @param exception the exception. * @param readingBuffer the currently reading buffer. */ - protected void handleFailedReceiving(@NotNull Throwable exception, @NotNull ByteBuffer readingBuffer) { + protected void handleFailedReceiving(Throwable exception, ByteBuffer readingBuffer) { if (exception instanceof AsynchronousCloseException) { LOGGER.info(connection, cn -> "Connection " + cn.getRemoteAddress() + " was closed."); } else { @@ -440,7 +439,7 @@ protected int getMaxPacketsByRead() { return maxPacketsByRead; } - protected int readHeader(@NotNull ByteBuffer buffer, int headerSize) { + protected int readHeader(ByteBuffer buffer, int headerSize) { switch (headerSize) { case 1: return buffer.get() & 0xFF; @@ -463,7 +462,7 @@ protected int readHeader(@NotNull ByteBuffer buffer, int headerSize) { * @return the readable packet. */ protected abstract @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, + ByteBuffer buffer, int startPacketPosition, int packetLength, int dataLength); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java index 350a6c11..20b59dd5 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractPacketWriter.java @@ -19,8 +19,7 @@ import javasabr.rlib.network.packet.WritablePacket; import javasabr.rlib.network.util.NetworkUtils; import lombok.RequiredArgsConstructor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr @@ -34,42 +33,42 @@ public abstract class AbstractPacketWriter writeHandler = new CompletionHandler<>() { @Override - public void completed(@NotNull Integer result, @NotNull WritablePacket packet) { + public void completed(Integer result, WritablePacket packet) { handleSuccessfulWriting(result, packet); } @Override - public void failed(@NotNull Throwable exc, @NotNull WritablePacket packet) { + public void failed(Throwable exc, WritablePacket packet) { handleFailedWriting(exc, packet); } }; - protected final @NotNull AtomicBoolean isWriting = new AtomicBoolean(); + protected final AtomicBoolean isWriting = new AtomicBoolean(); - protected final @NotNull C connection; - protected final @NotNull AsynchronousSocketChannel channel; - protected final @NotNull BufferAllocator bufferAllocator; - protected final @NotNull ByteBuffer firstWriteBuffer; - protected final @NotNull ByteBuffer secondWriteBuffer; + protected final C connection; + protected final AsynchronousSocketChannel channel; + protected final BufferAllocator bufferAllocator; + protected final ByteBuffer firstWriteBuffer; + protected final ByteBuffer secondWriteBuffer; protected volatile @Nullable ByteBuffer firstWriteTempBuffer; protected volatile @Nullable ByteBuffer secondWriteTempBuffer; - protected volatile @NotNull ByteBuffer writingBuffer = EMPTY_BUFFER; + protected volatile ByteBuffer writingBuffer = EMPTY_BUFFER; - protected final @NotNull Runnable updateActivityFunction; - protected final @NotNull NullableSupplier nextWritePacketSupplier; - protected final @NotNull NotNullConsumer writtenPacketHandler; - protected final @NotNull NotNullBiConsumer sentPacketHandler; + protected final Runnable updateActivityFunction; + protected final NullableSupplier nextWritePacketSupplier; + protected final NotNullConsumer writtenPacketHandler; + protected final NotNullBiConsumer sentPacketHandler; public AbstractPacketWriter( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NullableSupplier packetProvider, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler) { + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NullableSupplier packetProvider, + NotNullConsumer writtenPacketHandler, + NotNullBiConsumer sentPacketHandler) { this.connection = connection; this.channel = channel; this.bufferAllocator = bufferAllocator; @@ -113,7 +112,7 @@ public void writeNextPacket() { writtenPacketHandler.accept(waitPacket); } - protected @NotNull ByteBuffer serialize(@NotNull WritablePacket packet) { + protected ByteBuffer serialize(WritablePacket packet) { if (packet instanceof WritablePacketWrapper) { packet = ((WritablePacketWrapper) packet).getPacket(); @@ -143,7 +142,7 @@ public void writeNextPacket() { * @param expectedLength the expected size. * @return the total size or -1. */ - protected abstract int getTotalSize(@NotNull WritablePacket packet, int expectedLength); + protected abstract int getTotalSize(WritablePacket packet, int expectedLength); /** * Serialize packet to byte buffer. @@ -155,12 +154,12 @@ public void writeNextPacket() { * @param secondBuffer the second byte buffer. * @return the buffer to write to channel. */ - protected @NotNull ByteBuffer serialize( - @NotNull W packet, + protected ByteBuffer serialize( + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { if (!onBeforeWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer)) { return firstBuffer @@ -190,11 +189,11 @@ public void writeNextPacket() { * @return true if handling was successful. */ protected boolean onBeforeWrite( - @NotNull W packet, + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { firstBuffer.clear(); return true; } @@ -210,11 +209,11 @@ protected boolean onBeforeWrite( * @return true if writing was successful. */ protected boolean onWrite( - @NotNull W packet, + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { return packet.write(firstBuffer); } @@ -229,11 +228,11 @@ protected boolean onWrite( * @return true if handling was successful. */ protected boolean onAfterWrite( - @NotNull W packet, + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { firstBuffer.flip(); return true; } @@ -248,16 +247,16 @@ protected boolean onAfterWrite( * @param secondBuffer the second byte buffer. * @return the same byte buffer. */ - protected @NotNull ByteBuffer onResult( - @NotNull W packet, + protected ByteBuffer onResult( + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { return firstBuffer.position(0); } - protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int position, int value, int headerSize) { + protected ByteBuffer writeHeader(ByteBuffer buffer, int position, int value, int headerSize) { try { switch (headerSize) { @@ -283,7 +282,7 @@ protected boolean onAfterWrite( } } - protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int value, int headerSize) { + protected ByteBuffer writeHeader(ByteBuffer buffer, int value, int headerSize) { switch (headerSize) { case 1: @@ -308,7 +307,7 @@ protected boolean onAfterWrite( * @param result the count of wrote bytes. * @param packet the sent packet. */ - protected void handleSuccessfulWriting(@NotNull Integer result, @NotNull WritablePacket packet) { + protected void handleSuccessfulWriting(Integer result, WritablePacket packet) { updateActivityFunction.run(); if (result == -1) { @@ -350,7 +349,7 @@ protected void handleSuccessfulWriting(@NotNull Integer result, @NotNull Writabl * @param exception the exception. * @param packet the packet. */ - protected void handleFailedWriting(@NotNull Throwable exception, @NotNull WritablePacket packet) { + protected void handleFailedWriting(Throwable exception, WritablePacket packet) { LOGGER.error(new RuntimeException("Failed writing packet: " + packet, exception)); if (!connection.isClosed()) { diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java index 1ff0440e..86a24316 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReadablePacket.java @@ -7,7 +7,6 @@ import javasabr.rlib.network.packet.ReadablePacket; import lombok.AccessLevel; import lombok.NoArgsConstructor; -import org.jetbrains.annotations.NotNull; /** * The base implementation of {@link ReadablePacket}. @@ -19,7 +18,7 @@ public abstract class AbstractReadablePacket> extends ReadablePacket { @Override - public boolean read(@NotNull Connection connection, @NotNull ByteBuffer buffer, int length) { + public boolean read(Connection connection, ByteBuffer buffer, int length) { var oldLimit = buffer.limit(); try { buffer.limit(buffer.position() + length); @@ -39,7 +38,7 @@ public boolean read(@NotNull Connection connection, @NotNull ByteBuffer bu * @param connection the network connection. * @param buffer the buffer with received data. */ - protected void readImpl(@NotNull C connection, @NotNull ByteBuffer buffer) { + protected void readImpl(C connection, ByteBuffer buffer) { } /** @@ -48,7 +47,7 @@ protected void readImpl(@NotNull C connection, @NotNull ByteBuffer buffer) { * @param buffer the buffer to read. * @return 1 byte from the buffer. */ - protected int readByte(@NotNull ByteBuffer buffer) { + protected int readByte(ByteBuffer buffer) { return buffer.get(); } @@ -58,7 +57,7 @@ protected int readByte(@NotNull ByteBuffer buffer) { * @param buffer the buffer to read. * @param array the filled byte array. */ - protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array) { + protected void readBytes(ByteBuffer buffer, byte[] array) { buffer.get(array); } @@ -70,7 +69,7 @@ protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array) { * @param offset the offset to fill the byte array. * @param length the length to fill the byte array. */ - protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array, int offset, int length) { + protected void readBytes(ByteBuffer buffer, byte[] array, int offset, int length) { buffer.get(array, offset, length); } @@ -80,7 +79,7 @@ protected void readBytes(@NotNull ByteBuffer buffer, @NotNull byte[] array, int * @param buffer the buffer to read. * @return 4 bytes as float from the buffer. */ - protected float readFloat(@NotNull ByteBuffer buffer) { + protected float readFloat(ByteBuffer buffer) { return buffer.getFloat(); } @@ -90,7 +89,7 @@ protected float readFloat(@NotNull ByteBuffer buffer) { * @param buffer the buffer to read. * @return 4 bytes as double from the buffer. */ - protected double readDouble(@NotNull ByteBuffer buffer) { + protected double readDouble(ByteBuffer buffer) { return buffer.getDouble(); } @@ -100,7 +99,7 @@ protected double readDouble(@NotNull ByteBuffer buffer) { * @param buffer the buffer to read. * @return 4 bytes as int from the buffer. */ - protected int readInt(@NotNull ByteBuffer buffer) { + protected int readInt(ByteBuffer buffer) { return buffer.getInt(); } @@ -110,7 +109,7 @@ protected int readInt(@NotNull ByteBuffer buffer) { * @param buffer the buffer to read. * @return 8 bytes as long from buffer. */ - protected long readLong(@NotNull ByteBuffer buffer) { + protected long readLong(ByteBuffer buffer) { return buffer.getLong(); } @@ -120,7 +119,7 @@ protected long readLong(@NotNull ByteBuffer buffer) { * @param buffer the buffer to read. * @return 2 bytes as short from buffer. */ - protected int readShort(@NotNull ByteBuffer buffer) { + protected int readShort(ByteBuffer buffer) { return buffer.getShort(); } @@ -130,7 +129,7 @@ protected int readShort(@NotNull ByteBuffer buffer) { * @param buffer the buffer to read. * @return the read string from the buffer. */ - protected @NotNull String readString(@NotNull ByteBuffer buffer) { + protected String readString(ByteBuffer buffer) { var length = readInt(buffer); try { diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java index ff282f20..3187f6f6 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractReusableWritablePacket.java @@ -10,8 +10,7 @@ import javasabr.rlib.common.util.pools.Pool; import javasabr.rlib.common.util.pools.PoolFactory; import javasabr.rlib.network.packet.ReusableWritablePacket; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * The reusable implementation of {@link AbstractWritablePacket} using the counter to control the life cycle of this @@ -39,7 +38,7 @@ public AbstractReusableWritablePacket() { } @Override - public boolean write(@NotNull ByteBuffer buffer) { + public boolean write(ByteBuffer buffer) { if (counter.get() < 1) { LOGGER.warning( @@ -120,7 +119,7 @@ public void forceComplete() { * * @return thread local pool. */ - protected @NotNull Pool getThreadLocalPool() { + protected Pool getThreadLocalPool() { Class packetClass = ClassUtils.unsafeNNCast(getClass()); return LOCAL_POOLS .get() @@ -137,7 +136,7 @@ public void reuse() { * * @return the pool to store used packet. */ - protected @NotNull Pool getPool() { + protected Pool getPool() { Pool local = this.pool; @@ -170,7 +169,7 @@ protected void completeImpl() { * @param the result packet's type. * @return the new instance. */ - public @NotNull T newInstance() { + public T newInstance() { Pool pool = getPool(); ReusableWritablePacket result = pool.take(getClass(), ClassUtils::newInstance); @@ -180,7 +179,7 @@ protected void completeImpl() { } @Override - public final void setPool(@NotNull Pool pool) { + public final void setPool(Pool pool) { this.pool = pool; } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java index 76763953..3ec1d274 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketReader.java @@ -17,7 +17,6 @@ import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLException; -import org.jetbrains.annotations.NotNull; /** * @param the readable packet's type. @@ -34,20 +33,20 @@ public abstract class AbstractSSLPacketReader packetWriter; + protected final SSLEngine sslEngine; + protected final NotNullConsumer packetWriter; - protected volatile @NotNull ByteBuffer sslNetworkBuffer; - protected volatile @NotNull ByteBuffer sslDataBuffer; + protected volatile ByteBuffer sslNetworkBuffer; + protected volatile ByteBuffer sslDataBuffer; protected AbstractSSLPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NotNullConsumer readPacketHandler, + SSLEngine sslEngine, + NotNullConsumer packetWriter, int maxPacketsByRead) { super(connection, channel, bufferAllocator, updateActivityFunction, readPacketHandler, maxPacketsByRead); this.sslEngine = sslEngine; @@ -61,12 +60,12 @@ protected AbstractSSLPacketReader( } @Override - protected @NotNull ByteBuffer getBufferToReadFromChannel() { + protected ByteBuffer getBufferToReadFromChannel() { return sslNetworkBuffer; } @Override - protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) { + protected void handleReceivedData(Integer receivedBytes, ByteBuffer readingBuffer) { if (receivedBytes == -1) { doHandshake(readingBuffer, -1); @@ -77,7 +76,7 @@ protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteB } @Override - protected int readPackets(@NotNull ByteBuffer receivedBuffer) { + protected int readPackets(ByteBuffer receivedBuffer) { var handshakeStatus = sslEngine.getHandshakeStatus(); @@ -89,7 +88,7 @@ protected int readPackets(@NotNull ByteBuffer receivedBuffer) { } } - protected int doHandshake(@NotNull ByteBuffer receivedBuffer, int receivedBytes) { + protected int doHandshake(ByteBuffer receivedBuffer, int receivedBytes) { var handshakeStatus = sslEngine.getHandshakeStatus(); @@ -202,7 +201,7 @@ protected int doHandshake(@NotNull ByteBuffer receivedBuffer, int receivedBytes) return decryptAndRead(receivedBuffer); } - protected int decryptAndRead(@NotNull ByteBuffer receivedBuffer) { + protected int decryptAndRead(ByteBuffer receivedBuffer) { int total = 0; diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java index 27ad65e2..3b96e8be 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractSSLPacketWriter.java @@ -19,8 +19,7 @@ import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; public abstract class AbstractSSLPacketWriter> extends AbstractPacketWriter { @@ -31,23 +30,23 @@ public abstract class AbstractSSLPacketWriter packetWriter; - protected final @NotNull NotNullConsumer queueAtFirst; + protected final SSLEngine sslEngine; + protected final NotNullConsumer packetWriter; + protected final NotNullConsumer queueAtFirst; - protected volatile @NotNull ByteBuffer sslNetworkBuffer; + protected volatile ByteBuffer sslNetworkBuffer; public AbstractSSLPacketWriter( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NullableSupplier packetProvider, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, - @NotNull NotNullConsumer queueAtFirst) { + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NullableSupplier packetProvider, + NotNullConsumer writtenPacketHandler, + NotNullBiConsumer sentPacketHandler, + SSLEngine sslEngine, + NotNullConsumer packetWriter, + NotNullConsumer queueAtFirst) { super( connection, channel, @@ -78,7 +77,7 @@ public void writeNextPacket() { } @Override - protected @NotNull ByteBuffer serialize(@NotNull WritablePacket packet) { + protected ByteBuffer serialize(WritablePacket packet) { var status = sslEngine.getHandshakeStatus(); @@ -122,7 +121,7 @@ public void writeNextPacket() { throw new IllegalStateException(); } - protected @Nullable ByteBuffer doHandshake(@NotNull WritablePacket packet) { + protected @Nullable ByteBuffer doHandshake(WritablePacket packet) { if (!(packet instanceof SSLWritablePacket)) { LOGGER.debug(packet, pck -> "Return packet " + pck + " to queue as first"); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java index 65a024c0..ad82ba84 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/AbstractWritablePacket.java @@ -12,7 +12,7 @@ public abstract class AbstractWritablePacket extends AbstractPacket implements WritablePacket { @Override - public boolean write(@NotNull ByteBuffer buffer) { + public boolean write(ByteBuffer buffer) { try { writeImpl(buffer); return true; @@ -27,6 +27,5 @@ public boolean write(@NotNull ByteBuffer buffer) { * * @param buffer the buffer */ - protected void writeImpl(@NotNull ByteBuffer buffer) { - } + protected void writeImpl(ByteBuffer buffer) {} } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java index b5cca044..2bcb97e4 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketReader.java @@ -7,8 +7,7 @@ import javasabr.rlib.network.BufferAllocator; import javasabr.rlib.network.Connection; import javasabr.rlib.network.packet.ReadablePacket; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @param the readable packet's type. @@ -22,12 +21,12 @@ public class DefaultPacketReader readPacketHandler, - @NotNull IntFunction readPacketFactory, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NotNullConsumer readPacketHandler, + IntFunction readPacketFactory, int packetLengthHeaderSize, int maxPacketsByRead) { super(connection, channel, bufferAllocator, updateActivityFunction, readPacketHandler, maxPacketsByRead); @@ -36,18 +35,18 @@ public DefaultPacketReader( } @Override - protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { + protected boolean canStartReadPacket(ByteBuffer buffer) { return buffer.remaining() >= packetLengthHeaderSize; } @Override - protected int readPacketLength(@NotNull ByteBuffer buffer) { + protected int readPacketLength(ByteBuffer buffer) { return readHeader(buffer, packetLengthHeaderSize); } @Override protected @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, + ByteBuffer buffer, int startPacketPosition, int packetLength, int dataLength) { diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java index 6406ecd6..ea6a8470 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultPacketWriter.java @@ -8,7 +8,6 @@ import javasabr.rlib.network.BufferAllocator; import javasabr.rlib.network.Connection; import javasabr.rlib.network.packet.WritablePacket; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -19,13 +18,13 @@ public class DefaultPacketWriter nextWritePacketSupplier, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NullableSupplier nextWritePacketSupplier, + NotNullConsumer writtenPacketHandler, + NotNullBiConsumer sentPacketHandler, int packetLengthHeaderSize) { super( connection, @@ -39,17 +38,17 @@ public DefaultPacketWriter( } @Override - protected int getTotalSize(@NotNull WritablePacket packet, int expectedLength) { + protected int getTotalSize(WritablePacket packet, int expectedLength) { return expectedLength + packetLengthHeaderSize; } @Override protected boolean onBeforeWrite( - @NotNull W packet, + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { firstBuffer .clear() .position(packetLengthHeaderSize); @@ -57,16 +56,16 @@ protected boolean onBeforeWrite( } @Override - protected @NotNull ByteBuffer onResult( - @NotNull W packet, + protected ByteBuffer onResult( + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { return writePacketLength(firstBuffer, firstBuffer.limit()).position(0); } - protected @NotNull ByteBuffer writePacketLength(@NotNull ByteBuffer buffer, int packetLength) { + protected ByteBuffer writePacketLength(ByteBuffer buffer, int packetLength) { return writeHeader(buffer, 0, packetLength, packetLengthHeaderSize); } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java index d3693252..814eaf51 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketReader.java @@ -9,8 +9,7 @@ import javasabr.rlib.network.packet.ReadablePacket; import javasabr.rlib.network.packet.WritablePacket; import javax.net.ssl.SSLEngine; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @param the readable packet's type. @@ -24,14 +23,14 @@ public class DefaultSSLPacketReader readPacketHandler, - @NotNull IntFunction readPacketFactory, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NotNullConsumer readPacketHandler, + IntFunction readPacketFactory, + SSLEngine sslEngine, + NotNullConsumer packetWriter, int packetLengthHeaderSize, int maxPacketsByRead) { super( @@ -48,18 +47,18 @@ public DefaultSSLPacketReader( } @Override - protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { + protected boolean canStartReadPacket(ByteBuffer buffer) { return buffer.remaining() >= packetLengthHeaderSize; } @Override - protected int readPacketLength(@NotNull ByteBuffer buffer) { + protected int readPacketLength(ByteBuffer buffer) { return readHeader(buffer, packetLengthHeaderSize); } @Override protected @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, + ByteBuffer buffer, int startPacketPosition, int packetLength, int dataLength) { diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java index c14162b9..588b09ac 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/DefaultSSLPacketWriter.java @@ -9,7 +9,6 @@ import javasabr.rlib.network.Connection; import javasabr.rlib.network.packet.WritablePacket; import javax.net.ssl.SSLEngine; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -20,16 +19,16 @@ public class DefaultSSLPacketWriter nextWritePacketSupplier, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, - @NotNull SSLEngine sslEngine, - @NotNull NotNullConsumer packetWriter, - @NotNull NotNullConsumer queueAtFirst, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NullableSupplier nextWritePacketSupplier, + NotNullConsumer writtenPacketHandler, + NotNullBiConsumer sentPacketHandler, + SSLEngine sslEngine, + NotNullConsumer packetWriter, + NotNullConsumer queueAtFirst, int packetLengthHeaderSize) { super( connection, @@ -46,17 +45,17 @@ public DefaultSSLPacketWriter( } @Override - protected int getTotalSize(@NotNull WritablePacket packet, int expectedLength) { + protected int getTotalSize(WritablePacket packet, int expectedLength) { return expectedLength + packetLengthHeaderSize; } @Override protected boolean onBeforeWrite( - @NotNull W packet, + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { firstBuffer .clear() .position(packetLengthHeaderSize); @@ -64,16 +63,16 @@ protected boolean onBeforeWrite( } @Override - protected @NotNull ByteBuffer onResult( - @NotNull W packet, + protected ByteBuffer onResult( + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { return writePacketLength(firstBuffer, firstBuffer.limit()).position(0); } - protected @NotNull ByteBuffer writePacketLength(@NotNull ByteBuffer buffer, int packetLength) { + protected ByteBuffer writePacketLength(ByteBuffer buffer, int packetLength) { return writeHeader(buffer, 0, packetLength, packetLengthHeaderSize); } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java index b77a8343..e4585319 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketReader.java @@ -7,8 +7,7 @@ import javasabr.rlib.network.Connection; import javasabr.rlib.network.packet.IdBasedReadablePacket; import javasabr.rlib.network.packet.registry.ReadablePacketRegistry; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @param the readable packet's type. @@ -23,15 +22,15 @@ public class IdBasedPacketReader, C extends C private final int packetIdHeaderSize; public IdBasedPacketReader( - @NotNull C connection, - @NotNull AsynchronousSocketChannel channel, - @NotNull BufferAllocator bufferAllocator, - @NotNull Runnable updateActivityFunction, - @NotNull NotNullConsumer readPacketHandler, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NotNullConsumer readPacketHandler, int packetLengthHeaderSize, int maxPacketsByRead, int packetIdHeaderSize, - @NotNull ReadablePacketRegistry packetRegistry) { + ReadablePacketRegistry packetRegistry) { super(connection, channel, bufferAllocator, updateActivityFunction, readPacketHandler, maxPacketsByRead); this.packetLengthHeaderSize = packetLengthHeaderSize; this.packetIdHeaderSize = packetIdHeaderSize; @@ -39,18 +38,18 @@ public IdBasedPacketReader( } @Override - protected boolean canStartReadPacket(@NotNull ByteBuffer buffer) { + protected boolean canStartReadPacket(ByteBuffer buffer) { return buffer.remaining() > packetLengthHeaderSize; } @Override - protected int readPacketLength(@NotNull ByteBuffer buffer) { + protected int readPacketLength(ByteBuffer buffer) { return readHeader(buffer, packetLengthHeaderSize); } @Override protected @Nullable R createPacketFor( - @NotNull ByteBuffer buffer, + ByteBuffer buffer, int startPacketPosition, int packetLength, int dataLength) { diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java index 96ed5805..62ec9c39 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/IdBasedPacketWriter.java @@ -9,7 +9,6 @@ import javasabr.rlib.network.Connection; import javasabr.rlib.network.packet.IdBasedWritablePacket; import javasabr.rlib.network.packet.WritablePacket; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -20,13 +19,13 @@ public class IdBasedPacketWriter nextWritePacketSupplier, - @NotNull NotNullConsumer writtenPacketHandler, - @NotNull NotNullBiConsumer sentPacketHandler, + C connection, + AsynchronousSocketChannel channel, + BufferAllocator bufferAllocator, + Runnable updateActivityFunction, + NullableSupplier nextWritePacketSupplier, + NotNullConsumer writtenPacketHandler, + NotNullBiConsumer sentPacketHandler, int packetLengthHeaderSize, int packetIdHeaderSize) { super( @@ -43,11 +42,11 @@ public IdBasedPacketWriter( @Override protected boolean onWrite( - @NotNull W packet, + W packet, int expectedLength, int totalSize, - @NotNull ByteBuffer firstBuffer, - @NotNull ByteBuffer secondBuffer) { + ByteBuffer firstBuffer, + ByteBuffer secondBuffer) { writeHeader(firstBuffer, packet.getPacketId(), packetIdHeaderSize); return super.onWrite(packet, expectedLength, totalSize, firstBuffer, secondBuffer); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java index 9167a1d8..57297699 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/SSLWritablePacket.java @@ -15,7 +15,7 @@ public static SSLWritablePacket getInstance() { } @Override - public boolean write(@NotNull ByteBuffer buffer) { + public boolean write(ByteBuffer buffer) { return true; } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java index 1f34505f..6f8911d1 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringReadablePacket.java @@ -3,8 +3,7 @@ import java.nio.ByteBuffer; import javasabr.rlib.network.Connection; import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.Nullable; /** * @author JavaSaBr @@ -18,12 +17,12 @@ public class StringReadablePacket extends AbstractReadablePacket connection, @NotNull ByteBuffer buffer) { + protected void readImpl(Connection connection, ByteBuffer buffer) { this.data = readString(buffer); } @Override - public @NotNull String toString() { + public String toString() { var data = getData(); diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java index b66c42ae..20d9eea3 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/StringWritablePacket.java @@ -2,7 +2,6 @@ import java.nio.ByteBuffer; import lombok.RequiredArgsConstructor; -import org.jetbrains.annotations.NotNull; /** * @author JavaSaBr @@ -10,10 +9,10 @@ @RequiredArgsConstructor public class StringWritablePacket extends AbstractWritablePacket { - private final @NotNull String data; + private final String data; @Override - protected void writeImpl(@NotNull ByteBuffer buffer) { + protected void writeImpl(ByteBuffer buffer) { super.writeImpl(buffer); writeString(buffer, data); } @@ -24,7 +23,7 @@ public int getExpectedLength() { } @Override - public @NotNull String toString() { + public String toString() { return "StringWritablePacket {\n" + "\"\tdataLength\":" + data.length() + "\n}"; } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java index dd87b530..2aa320fa 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/WritablePacketWrapper.java @@ -4,7 +4,6 @@ import javasabr.rlib.network.packet.WritablePacket; import lombok.Getter; import lombok.RequiredArgsConstructor; -import org.jetbrains.annotations.NotNull; /** * The writable packet wrapper with additional attachment. @@ -20,7 +19,7 @@ public class WritablePacketWrapper implements Writa private final W packet; @Override - public boolean write(@NotNull ByteBuffer buffer) { + public boolean write(ByteBuffer buffer) { return packet.write(buffer); } @@ -30,7 +29,7 @@ public int getExpectedLength() { } @Override - public @NotNull String getName() { + public String getName() { return "WritablePacketWrapper"; } } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/package-info.java new file mode 100644 index 00000000..6dd5141c --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/impl/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.packet.impl; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/package-info.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/package-info.java new file mode 100644 index 00000000..29264ea9 --- /dev/null +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package javasabr.rlib.network.packet; + +import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java index f5221c6a..f6d74548 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/ReadablePacketRegistry.java @@ -7,7 +7,6 @@ import javasabr.rlib.network.annotation.PacketDescription; import javasabr.rlib.network.packet.IdBasedReadablePacket; import javasabr.rlib.network.packet.registry.impl.IdBasedReadablePacketRegistry; -import org.jetbrains.annotations.NotNull; /** * The interface to implement a registry of readable packets. @@ -21,7 +20,7 @@ public interface ReadablePacketRegistry> { * * @return the new packet registry. */ - static @NotNull ReadablePacketRegistry empty() { + static ReadablePacketRegistry empty() { return new IdBasedReadablePacketRegistry<>(IdBasedReadablePacket.class); } @@ -32,7 +31,7 @@ public interface ReadablePacketRegistry> { * @param the packet's type. * @return the new packet registry. */ - static > @NotNull ReadablePacketRegistry empty(@NotNull Class type) { + static > ReadablePacketRegistry empty(Class type) { return new IdBasedReadablePacketRegistry<>(type); } @@ -41,7 +40,7 @@ public interface ReadablePacketRegistry> { * * @return the new packet registry. */ - static @NotNull ReadablePacketRegistry newDefault() { + static ReadablePacketRegistry newDefault() { var scanner = ClassPathScannerFactory.newDefaultScanner(); scanner.setUseSystemClasspath(true); @@ -56,7 +55,7 @@ public interface ReadablePacketRegistry> { * @param mainClass the main class of application. * @return the new packet registry. */ - static @NotNull ReadablePacketRegistry newDefault(@NotNull Class mainClass) { + static ReadablePacketRegistry newDefault(Class mainClass) { var scanner = ClassPathScannerFactory.newManifestScanner(mainClass); scanner.setUseSystemClasspath(false); @@ -71,7 +70,7 @@ public interface ReadablePacketRegistry> { * @param scanner the classpath scanner. * @return the new packet registry. */ - static @NotNull ReadablePacketRegistry of(@NotNull ClassPathScanner scanner) { + static ReadablePacketRegistry of(ClassPathScanner scanner) { var result = scanner .findImplements(IdBasedReadablePacket.class) @@ -94,9 +93,9 @@ public interface ReadablePacketRegistry> { * @return the new packet registry. */ @SafeVarargs - static > @NotNull ReadablePacketRegistry of( - @NotNull Class type, - @NotNull Class... classes) { + static > ReadablePacketRegistry of( + Class type, + Class... classes) { var registry = new IdBasedReadablePacketRegistry<>(type); registry.register(classes, classes.length); return registry; @@ -110,9 +109,9 @@ public interface ReadablePacketRegistry> { * @param the packet's type. * @return the new packet registry. */ - static > @NotNull ReadablePacketRegistry of( - @NotNull Class type, - @NotNull Array> classes) { + static > ReadablePacketRegistry of( + Class type, + Array> classes) { var registry = new IdBasedReadablePacketRegistry<>(type); registry.register(classes); @@ -127,5 +126,5 @@ public interface ReadablePacketRegistry> { * @return the packet. * @throws IllegalArgumentException if can't find a packet by the id. */ - @NotNull R findById(int id); + R findById(int id); } diff --git a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java index f71acfc0..7e418938 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/packet/registry/impl/IdBasedReadablePacketRegistry.java @@ -13,7 +13,6 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; -import org.jetbrains.annotations.NotNull; /** * The id based implementation of readable packets registry. @@ -36,7 +35,7 @@ public class IdBasedReadablePacketRegistry> i @Setter(AccessLevel.PRIVATE) private volatile R[] idToPacket; - public IdBasedReadablePacketRegistry(@NotNull Class type) { + public IdBasedReadablePacketRegistry(Class type) { this.idToPacket = ArrayUtils.create(type, 0); this.type = type; } @@ -49,7 +48,7 @@ public IdBasedReadablePacketRegistry(@NotNull Class type) { * @throws IllegalArgumentException if found a class without packet description annotation or if found duplication by * id. */ - public @NotNull IdBasedReadablePacketRegistry register(@NotNull Array> classes) { + public IdBasedReadablePacketRegistry register(Array> classes) { return register(classes.array(), classes.size()); } @@ -62,7 +61,7 @@ public IdBasedReadablePacketRegistry(@NotNull Class type) { * id. */ @SafeVarargs - public final @NotNull IdBasedReadablePacketRegistry register(@NotNull Class... classes) { + public final IdBasedReadablePacketRegistry register(Class... classes) { return register(classes, classes.length); } @@ -75,7 +74,7 @@ public IdBasedReadablePacketRegistry(@NotNull Class type) { * @throws IllegalArgumentException if found a class without packet description annotation or if found duplication by * id. */ - public @NotNull IdBasedReadablePacketRegistry register(@NotNull Class[] classes, int length) { + public IdBasedReadablePacketRegistry register(Class[] classes, int length) { var incorrectClass = Arrays .stream(classes, 0, length) @@ -133,7 +132,7 @@ public IdBasedReadablePacketRegistry(@NotNull Class type) { * @throws IllegalArgumentException if this class doesn't have {@link PacketDescription}, wrong id or some class is * already presented with the same id. */ - public @NotNull IdBasedReadablePacketRegistry register(@NotNull Class cs) { + public IdBasedReadablePacketRegistry register(Class cs) { return register(cs, () -> ClassUtils.newInstance(cs)); } @@ -147,9 +146,9 @@ public IdBasedReadablePacketRegistry(@NotNull Class type) { * @throws IllegalArgumentException if this class doesn't have {@link PacketDescription}, wrong id or some class is * already presented with the same id. */ - public